httplib.h 654 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939
  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.33.1"
  10. #define CPPHTTPLIB_VERSION_NUM "0x002101"
  11. /*
  12. * Platform compatibility check
  13. */
  14. #if defined(_WIN32) && !defined(_WIN64)
  15. #if defined(_MSC_VER)
  16. #pragma message( \
  17. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler.")
  18. #else
  19. #warning \
  20. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler."
  21. #endif
  22. #elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ < 8
  23. #warning \
  24. "cpp-httplib doesn't support 32-bit platforms. Please use a 64-bit compiler."
  25. #elif defined(__SIZEOF_SIZE_T__) && __SIZEOF_SIZE_T__ < 8
  26. #warning \
  27. "cpp-httplib doesn't support platforms where size_t is less than 64 bits."
  28. #endif
  29. #ifdef _WIN32
  30. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  31. #error \
  32. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  33. #endif
  34. #endif
  35. /*
  36. * Configuration
  37. */
  38. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  39. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  40. #endif
  41. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  42. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  43. #endif
  44. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  45. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  46. #endif
  47. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  60. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  61. #endif
  62. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  63. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  64. #endif
  65. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  66. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  67. #endif
  68. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  69. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  70. #endif
  71. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  72. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  73. #endif
  74. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  75. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  78. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  79. #endif
  80. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  81. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  82. #endif
  83. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  84. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  85. #endif
  86. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  87. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  88. #endif
  89. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  90. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  91. #endif
  92. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  93. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  94. #endif
  95. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  96. #ifdef _WIN32
  97. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  98. #else
  99. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  100. #endif
  101. #endif
  102. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  103. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  106. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  107. #endif
  108. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  109. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  110. #endif
  111. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  112. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  113. #endif
  114. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  115. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  116. #endif
  117. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  118. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  119. #endif
  120. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  121. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  122. #endif
  123. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  124. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  125. #endif
  126. #ifndef CPPHTTPLIB_TCP_NODELAY
  127. #define CPPHTTPLIB_TCP_NODELAY false
  128. #endif
  129. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  130. #define CPPHTTPLIB_IPV6_V6ONLY false
  131. #endif
  132. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  133. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  134. #endif
  135. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  136. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  137. #endif
  138. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  139. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  140. #endif
  141. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  142. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  143. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  144. ? std::thread::hardware_concurrency() - 1 \
  145. : 0))
  146. #endif
  147. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  148. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  149. #endif
  150. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  151. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  152. #endif
  153. #ifndef CPPHTTPLIB_RECV_FLAGS
  154. #define CPPHTTPLIB_RECV_FLAGS 0
  155. #endif
  156. #ifndef CPPHTTPLIB_SEND_FLAGS
  157. #define CPPHTTPLIB_SEND_FLAGS 0
  158. #endif
  159. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  160. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  161. #endif
  162. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  163. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  164. #endif
  165. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  166. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  167. #endif
  168. #ifndef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  169. #define CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND 300
  170. #endif
  171. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  172. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  173. #endif
  174. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  175. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  176. #endif
  177. /*
  178. * Headers
  179. */
  180. #ifdef _WIN32
  181. #ifndef _CRT_SECURE_NO_WARNINGS
  182. #define _CRT_SECURE_NO_WARNINGS
  183. #endif //_CRT_SECURE_NO_WARNINGS
  184. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  185. #define _CRT_NONSTDC_NO_DEPRECATE
  186. #endif //_CRT_NONSTDC_NO_DEPRECATE
  187. #if defined(_MSC_VER)
  188. #if _MSC_VER < 1900
  189. #error Sorry, Visual Studio versions prior to 2015 are not supported
  190. #endif
  191. #pragma comment(lib, "ws2_32.lib")
  192. #ifndef _SSIZE_T_DEFINED
  193. using ssize_t = __int64;
  194. #define _SSIZE_T_DEFINED
  195. #endif
  196. #endif // _MSC_VER
  197. #ifndef S_ISREG
  198. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  199. #endif // S_ISREG
  200. #ifndef S_ISDIR
  201. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  202. #endif // S_ISDIR
  203. #ifndef NOMINMAX
  204. #define NOMINMAX
  205. #endif // NOMINMAX
  206. #include <io.h>
  207. #include <winsock2.h>
  208. #include <ws2tcpip.h>
  209. #if defined(__has_include)
  210. #if __has_include(<afunix.h>)
  211. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  212. #include <afunix.h>
  213. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  214. #endif
  215. #endif
  216. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  217. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  218. #endif
  219. using nfds_t = unsigned long;
  220. using socket_t = SOCKET;
  221. using socklen_t = int;
  222. #else // not _WIN32
  223. #include <arpa/inet.h>
  224. #if !defined(_AIX) && !defined(__MVS__)
  225. #include <ifaddrs.h>
  226. #endif
  227. #ifdef __MVS__
  228. #include <strings.h>
  229. #ifndef NI_MAXHOST
  230. #define NI_MAXHOST 1025
  231. #endif
  232. #endif
  233. #include <net/if.h>
  234. #include <netdb.h>
  235. #include <netinet/in.h>
  236. #ifdef __linux__
  237. #include <resolv.h>
  238. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  239. #endif
  240. #include <csignal>
  241. #include <netinet/tcp.h>
  242. #include <poll.h>
  243. #include <pthread.h>
  244. #include <sys/mman.h>
  245. #include <sys/socket.h>
  246. #include <sys/un.h>
  247. #include <unistd.h>
  248. using socket_t = int;
  249. #ifndef INVALID_SOCKET
  250. #define INVALID_SOCKET (-1)
  251. #endif
  252. #endif //_WIN32
  253. #if defined(__APPLE__)
  254. #include <TargetConditionals.h>
  255. #endif
  256. #include <algorithm>
  257. #include <array>
  258. #include <atomic>
  259. #include <cassert>
  260. #include <cctype>
  261. #include <chrono>
  262. #include <climits>
  263. #include <condition_variable>
  264. #include <cstdlib>
  265. #include <cstring>
  266. #include <errno.h>
  267. #include <exception>
  268. #include <fcntl.h>
  269. #include <fstream>
  270. #include <functional>
  271. #include <iomanip>
  272. #include <iostream>
  273. #include <list>
  274. #include <map>
  275. #include <memory>
  276. #include <mutex>
  277. #include <random>
  278. #include <regex>
  279. #include <set>
  280. #include <sstream>
  281. #include <string>
  282. #include <sys/stat.h>
  283. #include <system_error>
  284. #include <thread>
  285. #include <unordered_map>
  286. #include <unordered_set>
  287. #include <utility>
  288. #if __cplusplus >= 201703L
  289. #include <any>
  290. #endif
  291. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  292. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  293. #if TARGET_OS_MAC
  294. #include <CFNetwork/CFHost.h>
  295. #include <CoreFoundation/CoreFoundation.h>
  296. #endif
  297. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO or
  298. // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  299. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  300. #ifdef _WIN32
  301. #include <wincrypt.h>
  302. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  303. // used
  304. #undef X509_NAME
  305. #undef X509_CERT_PAIR
  306. #undef X509_EXTENSIONS
  307. #undef PKCS7_SIGNER_INFO
  308. #ifdef _MSC_VER
  309. #pragma comment(lib, "crypt32.lib")
  310. #endif
  311. #endif // _WIN32
  312. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  313. #if TARGET_OS_MAC
  314. #include <Security/Security.h>
  315. #endif
  316. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  317. #include <openssl/err.h>
  318. #include <openssl/evp.h>
  319. #include <openssl/ssl.h>
  320. #include <openssl/x509v3.h>
  321. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  322. #include <openssl/applink.c>
  323. #endif
  324. #include <iostream>
  325. #include <sstream>
  326. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  327. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  328. #error Please use OpenSSL or a current version of BoringSSL
  329. #endif
  330. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  331. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  332. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  333. #endif
  334. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  335. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  336. #include <mbedtls/ctr_drbg.h>
  337. #include <mbedtls/entropy.h>
  338. #include <mbedtls/error.h>
  339. #include <mbedtls/md5.h>
  340. #include <mbedtls/net_sockets.h>
  341. #include <mbedtls/oid.h>
  342. #include <mbedtls/pk.h>
  343. #include <mbedtls/sha1.h>
  344. #include <mbedtls/sha256.h>
  345. #include <mbedtls/sha512.h>
  346. #include <mbedtls/ssl.h>
  347. #include <mbedtls/x509_crt.h>
  348. #ifdef _WIN32
  349. #include <wincrypt.h>
  350. #ifdef _MSC_VER
  351. #pragma comment(lib, "crypt32.lib")
  352. #endif
  353. #endif // _WIN32
  354. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  355. #if TARGET_OS_MAC
  356. #include <Security/Security.h>
  357. #endif
  358. #endif // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  359. // Mbed TLS 3.x API compatibility
  360. #if MBEDTLS_VERSION_MAJOR >= 3
  361. #define CPPHTTPLIB_MBEDTLS_V3
  362. #endif
  363. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  364. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  365. #include <wolfssl/options.h>
  366. #include <wolfssl/openssl/x509v3.h>
  367. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  368. #ifndef WOLFSSL_GEN_EMAIL
  369. #define WOLFSSL_GEN_EMAIL 1
  370. #endif
  371. #ifndef WOLFSSL_GEN_DNS
  372. #define WOLFSSL_GEN_DNS 2
  373. #endif
  374. #ifndef WOLFSSL_GEN_URI
  375. #define WOLFSSL_GEN_URI 6
  376. #endif
  377. #ifndef WOLFSSL_GEN_IPADD
  378. #define WOLFSSL_GEN_IPADD 7
  379. #endif
  380. #include <wolfssl/ssl.h>
  381. #include <wolfssl/wolfcrypt/hash.h>
  382. #include <wolfssl/wolfcrypt/md5.h>
  383. #include <wolfssl/wolfcrypt/sha256.h>
  384. #include <wolfssl/wolfcrypt/sha512.h>
  385. #ifdef _WIN32
  386. #include <wincrypt.h>
  387. #ifdef _MSC_VER
  388. #pragma comment(lib, "crypt32.lib")
  389. #endif
  390. #endif // _WIN32
  391. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  392. #if TARGET_OS_MAC
  393. #include <Security/Security.h>
  394. #endif
  395. #endif // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  396. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  397. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  398. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  399. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  400. #define CPPHTTPLIB_SSL_ENABLED
  401. #endif
  402. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  403. #include <zlib.h>
  404. #endif
  405. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  406. #include <brotli/decode.h>
  407. #include <brotli/encode.h>
  408. #endif
  409. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  410. #include <zstd.h>
  411. #endif
  412. /*
  413. * Declaration
  414. */
  415. namespace httplib {
  416. namespace ws {
  417. class WebSocket;
  418. } // namespace ws
  419. namespace detail {
  420. /*
  421. * Backport std::make_unique from C++14.
  422. *
  423. * NOTE: This code came up with the following stackoverflow post:
  424. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  425. *
  426. */
  427. template <class T, class... Args>
  428. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  429. make_unique(Args &&...args) {
  430. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  431. }
  432. template <class T>
  433. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  434. make_unique(std::size_t n) {
  435. typedef typename std::remove_extent<T>::type RT;
  436. return std::unique_ptr<T>(new RT[n]);
  437. }
  438. namespace case_ignore {
  439. inline unsigned char to_lower(int c) {
  440. const static unsigned char table[256] = {
  441. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  442. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  443. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  444. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  445. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  446. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  447. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  448. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  449. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  450. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  451. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  452. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  453. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  454. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  455. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  456. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  457. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  458. 255,
  459. };
  460. return table[(unsigned char)(char)c];
  461. }
  462. inline bool equal(const std::string &a, const std::string &b) {
  463. return a.size() == b.size() &&
  464. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  465. return to_lower(ca) == to_lower(cb);
  466. });
  467. }
  468. struct equal_to {
  469. bool operator()(const std::string &a, const std::string &b) const {
  470. return equal(a, b);
  471. }
  472. };
  473. struct hash {
  474. size_t operator()(const std::string &key) const {
  475. return hash_core(key.data(), key.size(), 0);
  476. }
  477. size_t hash_core(const char *s, size_t l, size_t h) const {
  478. return (l == 0) ? h
  479. : hash_core(s + 1, l - 1,
  480. // Unsets the 6 high bits of h, therefore no
  481. // overflow happens
  482. (((std::numeric_limits<size_t>::max)() >> 6) &
  483. h * 33) ^
  484. static_cast<unsigned char>(to_lower(*s)));
  485. }
  486. };
  487. template <typename T>
  488. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  489. detail::case_ignore::equal_to>;
  490. } // namespace case_ignore
  491. // This is based on
  492. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  493. struct scope_exit {
  494. explicit scope_exit(std::function<void(void)> &&f)
  495. : exit_function(std::move(f)), execute_on_destruction{true} {}
  496. scope_exit(scope_exit &&rhs) noexcept
  497. : exit_function(std::move(rhs.exit_function)),
  498. execute_on_destruction{rhs.execute_on_destruction} {
  499. rhs.release();
  500. }
  501. ~scope_exit() {
  502. if (execute_on_destruction) { this->exit_function(); }
  503. }
  504. void release() { this->execute_on_destruction = false; }
  505. private:
  506. scope_exit(const scope_exit &) = delete;
  507. void operator=(const scope_exit &) = delete;
  508. scope_exit &operator=(scope_exit &&) = delete;
  509. std::function<void(void)> exit_function;
  510. bool execute_on_destruction;
  511. };
  512. // Simple from_chars implementation for integer and double types (C++17
  513. // substitute)
  514. template <typename T> struct from_chars_result {
  515. const char *ptr;
  516. std::errc ec;
  517. };
  518. template <typename T>
  519. inline from_chars_result<T> from_chars(const char *first, const char *last,
  520. T &value, int base = 10) {
  521. value = 0;
  522. const char *p = first;
  523. bool negative = false;
  524. if (p != last && *p == '-') {
  525. negative = true;
  526. ++p;
  527. }
  528. if (p == last) { return {first, std::errc::invalid_argument}; }
  529. T result = 0;
  530. for (; p != last; ++p) {
  531. char c = *p;
  532. int digit = -1;
  533. if ('0' <= c && c <= '9') {
  534. digit = c - '0';
  535. } else if ('a' <= c && c <= 'z') {
  536. digit = c - 'a' + 10;
  537. } else if ('A' <= c && c <= 'Z') {
  538. digit = c - 'A' + 10;
  539. } else {
  540. break;
  541. }
  542. if (digit < 0 || digit >= base) { break; }
  543. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  544. return {p, std::errc::result_out_of_range};
  545. }
  546. result = result * base + digit;
  547. }
  548. if (p == first || (negative && p == first + 1)) {
  549. return {first, std::errc::invalid_argument};
  550. }
  551. value = negative ? -result : result;
  552. return {p, std::errc{}};
  553. }
  554. // from_chars for double (simple wrapper for strtod)
  555. inline from_chars_result<double> from_chars(const char *first, const char *last,
  556. double &value) {
  557. std::string s(first, last);
  558. char *endptr = nullptr;
  559. errno = 0;
  560. value = std::strtod(s.c_str(), &endptr);
  561. if (endptr == s.c_str()) { return {first, std::errc::invalid_argument}; }
  562. if (errno == ERANGE) {
  563. return {first + (endptr - s.c_str()), std::errc::result_out_of_range};
  564. }
  565. return {first + (endptr - s.c_str()), std::errc{}};
  566. }
  567. } // namespace detail
  568. enum SSLVerifierResponse {
  569. // no decision has been made, use the built-in certificate verifier
  570. NoDecisionMade,
  571. // connection certificate is verified and accepted
  572. CertificateAccepted,
  573. // connection certificate was processed but is rejected
  574. CertificateRejected
  575. };
  576. enum StatusCode {
  577. // Information responses
  578. Continue_100 = 100,
  579. SwitchingProtocol_101 = 101,
  580. Processing_102 = 102,
  581. EarlyHints_103 = 103,
  582. // Successful responses
  583. OK_200 = 200,
  584. Created_201 = 201,
  585. Accepted_202 = 202,
  586. NonAuthoritativeInformation_203 = 203,
  587. NoContent_204 = 204,
  588. ResetContent_205 = 205,
  589. PartialContent_206 = 206,
  590. MultiStatus_207 = 207,
  591. AlreadyReported_208 = 208,
  592. IMUsed_226 = 226,
  593. // Redirection messages
  594. MultipleChoices_300 = 300,
  595. MovedPermanently_301 = 301,
  596. Found_302 = 302,
  597. SeeOther_303 = 303,
  598. NotModified_304 = 304,
  599. UseProxy_305 = 305,
  600. unused_306 = 306,
  601. TemporaryRedirect_307 = 307,
  602. PermanentRedirect_308 = 308,
  603. // Client error responses
  604. BadRequest_400 = 400,
  605. Unauthorized_401 = 401,
  606. PaymentRequired_402 = 402,
  607. Forbidden_403 = 403,
  608. NotFound_404 = 404,
  609. MethodNotAllowed_405 = 405,
  610. NotAcceptable_406 = 406,
  611. ProxyAuthenticationRequired_407 = 407,
  612. RequestTimeout_408 = 408,
  613. Conflict_409 = 409,
  614. Gone_410 = 410,
  615. LengthRequired_411 = 411,
  616. PreconditionFailed_412 = 412,
  617. PayloadTooLarge_413 = 413,
  618. UriTooLong_414 = 414,
  619. UnsupportedMediaType_415 = 415,
  620. RangeNotSatisfiable_416 = 416,
  621. ExpectationFailed_417 = 417,
  622. ImATeapot_418 = 418,
  623. MisdirectedRequest_421 = 421,
  624. UnprocessableContent_422 = 422,
  625. Locked_423 = 423,
  626. FailedDependency_424 = 424,
  627. TooEarly_425 = 425,
  628. UpgradeRequired_426 = 426,
  629. PreconditionRequired_428 = 428,
  630. TooManyRequests_429 = 429,
  631. RequestHeaderFieldsTooLarge_431 = 431,
  632. UnavailableForLegalReasons_451 = 451,
  633. // Server error responses
  634. InternalServerError_500 = 500,
  635. NotImplemented_501 = 501,
  636. BadGateway_502 = 502,
  637. ServiceUnavailable_503 = 503,
  638. GatewayTimeout_504 = 504,
  639. HttpVersionNotSupported_505 = 505,
  640. VariantAlsoNegotiates_506 = 506,
  641. InsufficientStorage_507 = 507,
  642. LoopDetected_508 = 508,
  643. NotExtended_510 = 510,
  644. NetworkAuthenticationRequired_511 = 511,
  645. };
  646. using Headers =
  647. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  648. detail::case_ignore::equal_to>;
  649. using Params = std::multimap<std::string, std::string>;
  650. using Match = std::smatch;
  651. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  652. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  653. // ----------------------------------------------------------------------------
  654. // httplib::any — type-erased value container (C++11 compatible)
  655. // On C++17+ builds, thin wrappers around std::any are provided.
  656. // ----------------------------------------------------------------------------
  657. #if __cplusplus >= 201703L
  658. using any = std::any;
  659. using bad_any_cast = std::bad_any_cast;
  660. template <typename T> T any_cast(const any &a) { return std::any_cast<T>(a); }
  661. template <typename T> T any_cast(any &a) { return std::any_cast<T>(a); }
  662. template <typename T> T any_cast(any &&a) {
  663. return std::any_cast<T>(std::move(a));
  664. }
  665. template <typename T> const T *any_cast(const any *a) noexcept {
  666. return std::any_cast<T>(a);
  667. }
  668. template <typename T> T *any_cast(any *a) noexcept {
  669. return std::any_cast<T>(a);
  670. }
  671. #else // C++11/14 implementation
  672. class bad_any_cast : public std::bad_cast {
  673. public:
  674. const char *what() const noexcept override { return "bad any_cast"; }
  675. };
  676. namespace detail {
  677. using any_type_id = const void *;
  678. // Returns a unique per-type ID without RTTI.
  679. // The static address is stable across TUs because function templates are
  680. // implicitly inline and the ODR merges their statics into one.
  681. template <typename T> any_type_id any_typeid() noexcept {
  682. static const char id = 0;
  683. return &id;
  684. }
  685. struct any_storage {
  686. virtual ~any_storage() = default;
  687. virtual std::unique_ptr<any_storage> clone() const = 0;
  688. virtual any_type_id type_id() const noexcept = 0;
  689. };
  690. template <typename T> struct any_value final : any_storage {
  691. T value;
  692. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  693. std::unique_ptr<any_storage> clone() const override {
  694. return std::unique_ptr<any_storage>(new any_value<T>(value));
  695. }
  696. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  697. };
  698. } // namespace detail
  699. class any {
  700. std::unique_ptr<detail::any_storage> storage_;
  701. public:
  702. any() noexcept = default;
  703. any(const any &o) : storage_(o.storage_ ? o.storage_->clone() : nullptr) {}
  704. any(any &&) noexcept = default;
  705. any &operator=(const any &o) {
  706. storage_ = o.storage_ ? o.storage_->clone() : nullptr;
  707. return *this;
  708. }
  709. any &operator=(any &&) noexcept = default;
  710. template <
  711. typename T, typename D = typename std::decay<T>::type,
  712. typename std::enable_if<!std::is_same<D, any>::value, int>::type = 0>
  713. any(T &&v) : storage_(new detail::any_value<D>(std::forward<T>(v))) {}
  714. template <
  715. typename T, typename D = typename std::decay<T>::type,
  716. typename std::enable_if<!std::is_same<D, any>::value, int>::type = 0>
  717. any &operator=(T &&v) {
  718. storage_.reset(new detail::any_value<D>(std::forward<T>(v)));
  719. return *this;
  720. }
  721. bool has_value() const noexcept { return storage_ != nullptr; }
  722. void reset() noexcept { storage_.reset(); }
  723. template <typename T> friend T *any_cast(any *a) noexcept;
  724. template <typename T> friend const T *any_cast(const any *a) noexcept;
  725. };
  726. template <typename T> T *any_cast(any *a) noexcept {
  727. if (!a || !a->storage_) { return nullptr; }
  728. if (a->storage_->type_id() != detail::any_typeid<T>()) { return nullptr; }
  729. return &static_cast<detail::any_value<T> *>(a->storage_.get())->value;
  730. }
  731. template <typename T> const T *any_cast(const any *a) noexcept {
  732. if (!a || !a->storage_) { return nullptr; }
  733. if (a->storage_->type_id() != detail::any_typeid<T>()) { return nullptr; }
  734. return &static_cast<const detail::any_value<T> *>(a->storage_.get())->value;
  735. }
  736. template <typename T> T any_cast(const any &a) {
  737. using U =
  738. typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  739. const U *p = any_cast<U>(&a);
  740. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  741. if (!p) { throw bad_any_cast{}; }
  742. #else
  743. if (!p) { std::abort(); }
  744. #endif
  745. return static_cast<T>(*p);
  746. }
  747. template <typename T> T any_cast(any &a) {
  748. using U =
  749. typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  750. U *p = any_cast<U>(&a);
  751. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  752. if (!p) { throw bad_any_cast{}; }
  753. #else
  754. if (!p) { std::abort(); }
  755. #endif
  756. return static_cast<T>(*p);
  757. }
  758. template <typename T> T any_cast(any &&a) {
  759. using U =
  760. typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  761. U *p = any_cast<U>(&a);
  762. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  763. if (!p) { throw bad_any_cast{}; }
  764. #else
  765. if (!p) { std::abort(); }
  766. #endif
  767. return static_cast<T>(std::move(*p));
  768. }
  769. #endif // __cplusplus >= 201703L
  770. struct Response;
  771. using ResponseHandler = std::function<bool(const Response &response)>;
  772. struct FormData {
  773. std::string name;
  774. std::string content;
  775. std::string filename;
  776. std::string content_type;
  777. Headers headers;
  778. };
  779. struct FormField {
  780. std::string name;
  781. std::string content;
  782. Headers headers;
  783. };
  784. using FormFields = std::multimap<std::string, FormField>;
  785. using FormFiles = std::multimap<std::string, FormData>;
  786. struct MultipartFormData {
  787. FormFields fields; // Text fields from multipart
  788. FormFiles files; // Files from multipart
  789. // Text field access
  790. std::string get_field(const std::string &key, size_t id = 0) const;
  791. std::vector<std::string> get_fields(const std::string &key) const;
  792. bool has_field(const std::string &key) const;
  793. size_t get_field_count(const std::string &key) const;
  794. // File access
  795. FormData get_file(const std::string &key, size_t id = 0) const;
  796. std::vector<FormData> get_files(const std::string &key) const;
  797. bool has_file(const std::string &key) const;
  798. size_t get_file_count(const std::string &key) const;
  799. };
  800. struct UploadFormData {
  801. std::string name;
  802. std::string content;
  803. std::string filename;
  804. std::string content_type;
  805. };
  806. using UploadFormDataItems = std::vector<UploadFormData>;
  807. class DataSink {
  808. public:
  809. DataSink() : os(&sb_), sb_(*this) {}
  810. DataSink(const DataSink &) = delete;
  811. DataSink &operator=(const DataSink &) = delete;
  812. DataSink(DataSink &&) = delete;
  813. DataSink &operator=(DataSink &&) = delete;
  814. std::function<bool(const char *data, size_t data_len)> write;
  815. std::function<bool()> is_writable;
  816. std::function<void()> done;
  817. std::function<void(const Headers &trailer)> done_with_trailer;
  818. std::ostream os;
  819. private:
  820. class data_sink_streambuf final : public std::streambuf {
  821. public:
  822. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  823. protected:
  824. std::streamsize xsputn(const char *s, std::streamsize n) override {
  825. sink_.write(s, static_cast<size_t>(n));
  826. return n;
  827. }
  828. private:
  829. DataSink &sink_;
  830. };
  831. data_sink_streambuf sb_;
  832. };
  833. using ContentProvider =
  834. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  835. using ContentProviderWithoutLength =
  836. std::function<bool(size_t offset, DataSink &sink)>;
  837. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  838. struct FormDataProvider {
  839. std::string name;
  840. ContentProviderWithoutLength provider;
  841. std::string filename;
  842. std::string content_type;
  843. };
  844. using FormDataProviderItems = std::vector<FormDataProvider>;
  845. inline FormDataProvider
  846. make_file_provider(const std::string &name, const std::string &filepath,
  847. const std::string &filename = std::string(),
  848. const std::string &content_type = std::string()) {
  849. FormDataProvider fdp;
  850. fdp.name = name;
  851. fdp.filename = filename.empty() ? filepath : filename;
  852. fdp.content_type = content_type;
  853. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  854. std::ifstream f(filepath, std::ios::binary);
  855. if (!f) { return false; }
  856. if (offset > 0) {
  857. f.seekg(static_cast<std::streamoff>(offset));
  858. if (!f.good()) {
  859. sink.done();
  860. return true;
  861. }
  862. }
  863. char buf[8192];
  864. f.read(buf, sizeof(buf));
  865. auto n = static_cast<size_t>(f.gcount());
  866. if (n > 0) { return sink.write(buf, n); }
  867. sink.done(); // EOF
  868. return true;
  869. };
  870. return fdp;
  871. }
  872. inline std::pair<size_t, ContentProvider>
  873. make_file_body(const std::string &filepath) {
  874. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  875. if (!f) { return {0, ContentProvider{}}; }
  876. auto size = static_cast<size_t>(f.tellg());
  877. ContentProvider provider = [filepath](size_t offset, size_t length,
  878. DataSink &sink) -> bool {
  879. std::ifstream f(filepath, std::ios::binary);
  880. if (!f) { return false; }
  881. f.seekg(static_cast<std::streamoff>(offset));
  882. if (!f.good()) { return false; }
  883. char buf[8192];
  884. while (length > 0) {
  885. auto to_read = (std::min)(sizeof(buf), length);
  886. f.read(buf, static_cast<std::streamsize>(to_read));
  887. auto n = static_cast<size_t>(f.gcount());
  888. if (n == 0) { break; }
  889. if (!sink.write(buf, n)) { return false; }
  890. length -= n;
  891. }
  892. return true;
  893. };
  894. return {size, std::move(provider)};
  895. }
  896. using ContentReceiverWithProgress = std::function<bool(
  897. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  898. using ContentReceiver =
  899. std::function<bool(const char *data, size_t data_length)>;
  900. using FormDataHeader = std::function<bool(const FormData &file)>;
  901. class ContentReader {
  902. public:
  903. using Reader = std::function<bool(ContentReceiver receiver)>;
  904. using FormDataReader =
  905. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  906. ContentReader(Reader reader, FormDataReader multipart_reader)
  907. : reader_(std::move(reader)),
  908. formdata_reader_(std::move(multipart_reader)) {}
  909. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  910. return formdata_reader_(std::move(header), std::move(receiver));
  911. }
  912. bool operator()(ContentReceiver receiver) const {
  913. return reader_(std::move(receiver));
  914. }
  915. Reader reader_;
  916. FormDataReader formdata_reader_;
  917. };
  918. using Range = std::pair<ssize_t, ssize_t>;
  919. using Ranges = std::vector<Range>;
  920. #ifdef CPPHTTPLIB_SSL_ENABLED
  921. // TLS abstraction layer - public type definitions and API
  922. namespace tls {
  923. // Opaque handles (defined as void* for abstraction)
  924. using ctx_t = void *;
  925. using session_t = void *;
  926. using const_session_t = const void *; // For read-only session access
  927. using cert_t = void *;
  928. using ca_store_t = void *;
  929. // TLS versions
  930. enum class Version {
  931. TLS1_2 = 0x0303,
  932. TLS1_3 = 0x0304,
  933. };
  934. // Subject Alternative Names (SAN) entry types
  935. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  936. // SAN entry structure
  937. struct SanEntry {
  938. SanType type;
  939. std::string value;
  940. };
  941. // Verification context for certificate verification callback
  942. struct VerifyContext {
  943. session_t session; // TLS session handle
  944. cert_t cert; // Current certificate being verified
  945. int depth; // Certificate chain depth (0 = leaf)
  946. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  947. long error_code; // Backend-specific error code (0 = no error)
  948. const char *error_string; // Human-readable error description
  949. // Certificate introspection methods
  950. std::string subject_cn() const;
  951. std::string issuer_name() const;
  952. bool check_hostname(const char *hostname) const;
  953. std::vector<SanEntry> sans() const;
  954. bool validity(time_t &not_before, time_t &not_after) const;
  955. std::string serial() const;
  956. };
  957. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  958. // TlsError codes for TLS operations (backend-independent)
  959. enum class ErrorCode : int {
  960. Success = 0,
  961. WantRead, // Non-blocking: need to wait for read
  962. WantWrite, // Non-blocking: need to wait for write
  963. PeerClosed, // Peer closed the connection
  964. Fatal, // Unrecoverable error
  965. SyscallError, // System call error (check sys_errno)
  966. CertVerifyFailed, // Certificate verification failed
  967. HostnameMismatch, // Hostname verification failed
  968. };
  969. // TLS error information
  970. struct TlsError {
  971. ErrorCode code = ErrorCode::Fatal;
  972. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  973. int sys_errno = 0; // errno when SyscallError
  974. // Convert verification error code to human-readable string
  975. static std::string verify_error_to_string(long error_code);
  976. };
  977. // RAII wrapper for peer certificate
  978. class PeerCert {
  979. public:
  980. PeerCert();
  981. PeerCert(PeerCert &&other) noexcept;
  982. PeerCert &operator=(PeerCert &&other) noexcept;
  983. ~PeerCert();
  984. PeerCert(const PeerCert &) = delete;
  985. PeerCert &operator=(const PeerCert &) = delete;
  986. explicit operator bool() const;
  987. std::string subject_cn() const;
  988. std::string issuer_name() const;
  989. bool check_hostname(const char *hostname) const;
  990. std::vector<SanEntry> sans() const;
  991. bool validity(time_t &not_before, time_t &not_after) const;
  992. std::string serial() const;
  993. private:
  994. explicit PeerCert(cert_t cert);
  995. cert_t cert_ = nullptr;
  996. friend PeerCert get_peer_cert_from_session(const_session_t session);
  997. };
  998. // Callback for TLS context setup (used by SSLServer constructor)
  999. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1000. } // namespace tls
  1001. #endif
  1002. struct Request {
  1003. std::string method;
  1004. std::string path;
  1005. std::string matched_route;
  1006. Params params;
  1007. Headers headers;
  1008. Headers trailers;
  1009. std::string body;
  1010. std::string remote_addr;
  1011. int remote_port = -1;
  1012. std::string local_addr;
  1013. int local_port = -1;
  1014. // for server
  1015. std::string version;
  1016. std::string target;
  1017. MultipartFormData form;
  1018. Ranges ranges;
  1019. Match matches;
  1020. std::unordered_map<std::string, std::string> path_params;
  1021. std::function<bool()> is_connection_closed = []() { return true; };
  1022. // for client
  1023. std::vector<std::string> accept_content_types;
  1024. ResponseHandler response_handler;
  1025. ContentReceiverWithProgress content_receiver;
  1026. DownloadProgress download_progress;
  1027. UploadProgress upload_progress;
  1028. bool has_header(const std::string &key) const;
  1029. std::string get_header_value(const std::string &key, const char *def = "",
  1030. size_t id = 0) const;
  1031. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1032. size_t id = 0) const;
  1033. size_t get_header_value_count(const std::string &key) const;
  1034. void set_header(const std::string &key, const std::string &val);
  1035. bool has_trailer(const std::string &key) const;
  1036. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1037. size_t get_trailer_value_count(const std::string &key) const;
  1038. bool has_param(const std::string &key) const;
  1039. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1040. size_t get_param_value_count(const std::string &key) const;
  1041. bool is_multipart_form_data() const;
  1042. // private members...
  1043. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1044. size_t content_length_ = 0;
  1045. ContentProvider content_provider_;
  1046. bool is_chunked_content_provider_ = false;
  1047. size_t authorization_count_ = 0;
  1048. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1049. (std::chrono::steady_clock::time_point::min)();
  1050. #ifdef CPPHTTPLIB_SSL_ENABLED
  1051. tls::const_session_t ssl = nullptr;
  1052. tls::PeerCert peer_cert() const;
  1053. std::string sni() const;
  1054. #endif
  1055. };
  1056. struct Response {
  1057. std::string version;
  1058. int status = -1;
  1059. std::string reason;
  1060. Headers headers;
  1061. Headers trailers;
  1062. std::string body;
  1063. std::string location; // Redirect location
  1064. // User-defined context — set by pre-routing/pre-request handlers and read
  1065. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1066. std::map<std::string, any> user_data;
  1067. bool has_header(const std::string &key) const;
  1068. std::string get_header_value(const std::string &key, const char *def = "",
  1069. size_t id = 0) const;
  1070. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1071. size_t id = 0) const;
  1072. size_t get_header_value_count(const std::string &key) const;
  1073. void set_header(const std::string &key, const std::string &val);
  1074. bool has_trailer(const std::string &key) const;
  1075. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1076. size_t get_trailer_value_count(const std::string &key) const;
  1077. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1078. void set_content(const char *s, size_t n, const std::string &content_type);
  1079. void set_content(const std::string &s, const std::string &content_type);
  1080. void set_content(std::string &&s, const std::string &content_type);
  1081. void set_content_provider(
  1082. size_t length, const std::string &content_type, ContentProvider provider,
  1083. ContentProviderResourceReleaser resource_releaser = nullptr);
  1084. void set_content_provider(
  1085. const std::string &content_type, ContentProviderWithoutLength provider,
  1086. ContentProviderResourceReleaser resource_releaser = nullptr);
  1087. void set_chunked_content_provider(
  1088. const std::string &content_type, ContentProviderWithoutLength provider,
  1089. ContentProviderResourceReleaser resource_releaser = nullptr);
  1090. void set_file_content(const std::string &path,
  1091. const std::string &content_type);
  1092. void set_file_content(const std::string &path);
  1093. Response() = default;
  1094. Response(const Response &) = default;
  1095. Response &operator=(const Response &) = default;
  1096. Response(Response &&) = default;
  1097. Response &operator=(Response &&) = default;
  1098. ~Response() {
  1099. if (content_provider_resource_releaser_) {
  1100. content_provider_resource_releaser_(content_provider_success_);
  1101. }
  1102. }
  1103. // private members...
  1104. size_t content_length_ = 0;
  1105. ContentProvider content_provider_;
  1106. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1107. bool is_chunked_content_provider_ = false;
  1108. bool content_provider_success_ = false;
  1109. std::string file_content_path_;
  1110. std::string file_content_content_type_;
  1111. };
  1112. enum class Error {
  1113. Success = 0,
  1114. Unknown,
  1115. Connection,
  1116. BindIPAddress,
  1117. Read,
  1118. Write,
  1119. ExceedRedirectCount,
  1120. Canceled,
  1121. SSLConnection,
  1122. SSLLoadingCerts,
  1123. SSLServerVerification,
  1124. SSLServerHostnameVerification,
  1125. UnsupportedMultipartBoundaryChars,
  1126. Compression,
  1127. ConnectionTimeout,
  1128. ProxyConnection,
  1129. ConnectionClosed,
  1130. Timeout,
  1131. ResourceExhaustion,
  1132. TooManyFormDataFiles,
  1133. ExceedMaxPayloadSize,
  1134. ExceedUriMaxLength,
  1135. ExceedMaxSocketDescriptorCount,
  1136. InvalidRequestLine,
  1137. InvalidHTTPMethod,
  1138. InvalidHTTPVersion,
  1139. InvalidHeaders,
  1140. MultipartParsing,
  1141. OpenFile,
  1142. Listen,
  1143. GetSockName,
  1144. UnsupportedAddressFamily,
  1145. HTTPParsing,
  1146. InvalidRangeHeader,
  1147. // For internal use only
  1148. SSLPeerCouldBeClosed_,
  1149. };
  1150. std::string to_string(Error error);
  1151. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1152. class Stream {
  1153. public:
  1154. virtual ~Stream() = default;
  1155. virtual bool is_readable() const = 0;
  1156. virtual bool wait_readable() const = 0;
  1157. virtual bool wait_writable() const = 0;
  1158. virtual ssize_t read(char *ptr, size_t size) = 0;
  1159. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1160. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1161. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1162. virtual socket_t socket() const = 0;
  1163. virtual time_t duration() const = 0;
  1164. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1165. (void)sec;
  1166. (void)usec;
  1167. }
  1168. ssize_t write(const char *ptr);
  1169. ssize_t write(const std::string &s);
  1170. Error get_error() const { return error_; }
  1171. protected:
  1172. Error error_ = Error::Success;
  1173. };
  1174. class TaskQueue {
  1175. public:
  1176. TaskQueue() = default;
  1177. virtual ~TaskQueue() = default;
  1178. virtual bool enqueue(std::function<void()> fn) = 0;
  1179. virtual void shutdown() = 0;
  1180. virtual void on_idle() {}
  1181. };
  1182. class ThreadPool final : public TaskQueue {
  1183. public:
  1184. explicit ThreadPool(size_t n, size_t max_n = 0, size_t mqr = 0);
  1185. ThreadPool(const ThreadPool &) = delete;
  1186. ~ThreadPool() override = default;
  1187. bool enqueue(std::function<void()> fn) override;
  1188. void shutdown() override;
  1189. private:
  1190. void worker(bool is_dynamic);
  1191. void move_to_finished(std::thread::id id);
  1192. void cleanup_finished_threads();
  1193. size_t base_thread_count_;
  1194. size_t max_thread_count_;
  1195. size_t max_queued_requests_;
  1196. size_t idle_thread_count_;
  1197. bool shutdown_;
  1198. std::list<std::function<void()>> jobs_;
  1199. std::vector<std::thread> threads_; // base threads
  1200. std::list<std::thread> dynamic_threads_; // dynamic threads
  1201. std::vector<std::thread>
  1202. finished_threads_; // exited dynamic threads awaiting join
  1203. std::condition_variable cond_;
  1204. std::mutex mutex_;
  1205. };
  1206. using Logger = std::function<void(const Request &, const Response &)>;
  1207. // Forward declaration for Error type
  1208. enum class Error;
  1209. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1210. using SocketOptions = std::function<void(socket_t sock)>;
  1211. void default_socket_options(socket_t sock);
  1212. const char *status_message(int status);
  1213. std::string to_string(Error error);
  1214. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1215. std::string get_bearer_token_auth(const Request &req);
  1216. namespace detail {
  1217. class MatcherBase {
  1218. public:
  1219. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1220. virtual ~MatcherBase() = default;
  1221. const std::string &pattern() const { return pattern_; }
  1222. // Match request path and populate its matches and
  1223. virtual bool match(Request &request) const = 0;
  1224. private:
  1225. std::string pattern_;
  1226. };
  1227. /**
  1228. * Captures parameters in request path and stores them in Request::path_params
  1229. *
  1230. * Capture name is a substring of a pattern from : to /.
  1231. * The rest of the pattern is matched against the request path directly
  1232. * Parameters are captured starting from the next character after
  1233. * the end of the last matched static pattern fragment until the next /.
  1234. *
  1235. * Example pattern:
  1236. * "/path/fragments/:capture/more/fragments/:second_capture"
  1237. * Static fragments:
  1238. * "/path/fragments/", "more/fragments/"
  1239. *
  1240. * Given the following request path:
  1241. * "/path/fragments/:1/more/fragments/:2"
  1242. * the resulting capture will be
  1243. * {{"capture", "1"}, {"second_capture", "2"}}
  1244. */
  1245. class PathParamsMatcher final : public MatcherBase {
  1246. public:
  1247. PathParamsMatcher(const std::string &pattern);
  1248. bool match(Request &request) const override;
  1249. private:
  1250. // Treat segment separators as the end of path parameter capture
  1251. // Does not need to handle query parameters as they are parsed before path
  1252. // matching
  1253. static constexpr char separator = '/';
  1254. // Contains static path fragments to match against, excluding the '/' after
  1255. // path params
  1256. // Fragments are separated by path params
  1257. std::vector<std::string> static_fragments_;
  1258. // Stores the names of the path parameters to be used as keys in the
  1259. // Request::path_params map
  1260. std::vector<std::string> param_names_;
  1261. };
  1262. /**
  1263. * Performs std::regex_match on request path
  1264. * and stores the result in Request::matches
  1265. *
  1266. * Note that regex match is performed directly on the whole request.
  1267. * This means that wildcard patterns may match multiple path segments with /:
  1268. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1269. */
  1270. class RegexMatcher final : public MatcherBase {
  1271. public:
  1272. RegexMatcher(const std::string &pattern)
  1273. : MatcherBase(pattern), regex_(pattern) {}
  1274. bool match(Request &request) const override;
  1275. private:
  1276. std::regex regex_;
  1277. };
  1278. int close_socket(socket_t sock);
  1279. ssize_t write_headers(Stream &strm, const Headers &headers);
  1280. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1281. time_t usec);
  1282. } // namespace detail
  1283. class Server {
  1284. public:
  1285. using Handler = std::function<void(const Request &, Response &)>;
  1286. using ExceptionHandler =
  1287. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1288. enum class HandlerResponse {
  1289. Handled,
  1290. Unhandled,
  1291. };
  1292. using HandlerWithResponse =
  1293. std::function<HandlerResponse(const Request &, Response &)>;
  1294. using HandlerWithContentReader = std::function<void(
  1295. const Request &, Response &, const ContentReader &content_reader)>;
  1296. using Expect100ContinueHandler =
  1297. std::function<int(const Request &, Response &)>;
  1298. using WebSocketHandler =
  1299. std::function<void(const Request &, ws::WebSocket &)>;
  1300. using SubProtocolSelector =
  1301. std::function<std::string(const std::vector<std::string> &protocols)>;
  1302. Server();
  1303. virtual ~Server();
  1304. virtual bool is_valid() const;
  1305. Server &Get(const std::string &pattern, Handler handler);
  1306. Server &Post(const std::string &pattern, Handler handler);
  1307. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1308. Server &Put(const std::string &pattern, Handler handler);
  1309. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1310. Server &Patch(const std::string &pattern, Handler handler);
  1311. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1312. Server &Delete(const std::string &pattern, Handler handler);
  1313. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1314. Server &Options(const std::string &pattern, Handler handler);
  1315. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1316. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1317. SubProtocolSelector sub_protocol_selector);
  1318. bool set_base_dir(const std::string &dir,
  1319. const std::string &mount_point = std::string());
  1320. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1321. Headers headers = Headers());
  1322. bool remove_mount_point(const std::string &mount_point);
  1323. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1324. const std::string &mime);
  1325. Server &set_default_file_mimetype(const std::string &mime);
  1326. Server &set_file_request_handler(Handler handler);
  1327. template <class ErrorHandlerFunc>
  1328. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1329. return set_error_handler_core(
  1330. std::forward<ErrorHandlerFunc>(handler),
  1331. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1332. }
  1333. Server &set_exception_handler(ExceptionHandler handler);
  1334. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1335. Server &set_post_routing_handler(Handler handler);
  1336. Server &set_pre_request_handler(HandlerWithResponse handler);
  1337. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1338. Server &set_logger(Logger logger);
  1339. Server &set_pre_compression_logger(Logger logger);
  1340. Server &set_error_logger(ErrorLogger error_logger);
  1341. Server &set_address_family(int family);
  1342. Server &set_tcp_nodelay(bool on);
  1343. Server &set_ipv6_v6only(bool on);
  1344. Server &set_socket_options(SocketOptions socket_options);
  1345. Server &set_default_headers(Headers headers);
  1346. Server &
  1347. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1348. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1349. Server &set_keep_alive_max_count(size_t count);
  1350. Server &set_keep_alive_timeout(time_t sec);
  1351. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1352. template <class Rep, class Period>
  1353. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1354. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1355. template <class Rep, class Period>
  1356. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1357. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1358. template <class Rep, class Period>
  1359. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1360. Server &set_payload_max_length(size_t length);
  1361. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1362. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1363. bool listen_after_bind();
  1364. bool listen(const std::string &host, int port, int socket_flags = 0);
  1365. bool is_running() const;
  1366. void wait_until_ready() const;
  1367. void stop();
  1368. void decommission();
  1369. std::function<TaskQueue *(void)> new_task_queue;
  1370. protected:
  1371. bool process_request(Stream &strm, const std::string &remote_addr,
  1372. int remote_port, const std::string &local_addr,
  1373. int local_port, bool close_connection,
  1374. bool &connection_closed,
  1375. const std::function<void(Request &)> &setup_request,
  1376. bool *websocket_upgraded = nullptr);
  1377. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1378. std::vector<std::string> trusted_proxies_;
  1379. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1380. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1381. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1382. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1383. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1384. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1385. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1386. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1387. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1388. private:
  1389. using Handlers =
  1390. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1391. using HandlersForContentReader =
  1392. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1393. HandlerWithContentReader>>;
  1394. static std::unique_ptr<detail::MatcherBase>
  1395. make_matcher(const std::string &pattern);
  1396. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1397. Server &set_error_handler_core(Handler handler, std::false_type);
  1398. socket_t create_server_socket(const std::string &host, int port,
  1399. int socket_flags,
  1400. SocketOptions socket_options) const;
  1401. int bind_internal(const std::string &host, int port, int socket_flags);
  1402. bool listen_internal();
  1403. bool routing(Request &req, Response &res, Stream &strm);
  1404. bool handle_file_request(Request &req, Response &res);
  1405. bool check_if_not_modified(const Request &req, Response &res,
  1406. const std::string &etag, time_t mtime) const;
  1407. bool check_if_range(Request &req, const std::string &etag,
  1408. time_t mtime) const;
  1409. bool dispatch_request(Request &req, Response &res,
  1410. const Handlers &handlers) const;
  1411. bool dispatch_request_for_content_reader(
  1412. Request &req, Response &res, ContentReader content_reader,
  1413. const HandlersForContentReader &handlers) const;
  1414. bool parse_request_line(const char *s, Request &req) const;
  1415. void apply_ranges(const Request &req, Response &res,
  1416. std::string &content_type, std::string &boundary) const;
  1417. bool write_response(Stream &strm, bool close_connection, Request &req,
  1418. Response &res);
  1419. bool write_response_with_content(Stream &strm, bool close_connection,
  1420. const Request &req, Response &res);
  1421. bool write_response_core(Stream &strm, bool close_connection,
  1422. const Request &req, Response &res,
  1423. bool need_apply_ranges);
  1424. bool write_content_with_provider(Stream &strm, const Request &req,
  1425. Response &res, const std::string &boundary,
  1426. const std::string &content_type);
  1427. bool read_content(Stream &strm, Request &req, Response &res);
  1428. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1429. Response &res,
  1430. ContentReceiver receiver,
  1431. FormDataHeader multipart_header,
  1432. ContentReceiver multipart_receiver);
  1433. bool read_content_core(Stream &strm, Request &req, Response &res,
  1434. ContentReceiver receiver,
  1435. FormDataHeader multipart_header,
  1436. ContentReceiver multipart_receiver) const;
  1437. virtual bool process_and_close_socket(socket_t sock);
  1438. void output_log(const Request &req, const Response &res) const;
  1439. void output_pre_compression_log(const Request &req,
  1440. const Response &res) const;
  1441. void output_error_log(const Error &err, const Request *req) const;
  1442. std::atomic<bool> is_running_{false};
  1443. std::atomic<bool> is_decommissioned{false};
  1444. struct MountPointEntry {
  1445. std::string mount_point;
  1446. std::string base_dir;
  1447. Headers headers;
  1448. };
  1449. std::vector<MountPointEntry> base_dirs_;
  1450. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1451. std::string default_file_mimetype_ = "application/octet-stream";
  1452. Handler file_request_handler_;
  1453. Handlers get_handlers_;
  1454. Handlers post_handlers_;
  1455. HandlersForContentReader post_handlers_for_content_reader_;
  1456. Handlers put_handlers_;
  1457. HandlersForContentReader put_handlers_for_content_reader_;
  1458. Handlers patch_handlers_;
  1459. HandlersForContentReader patch_handlers_for_content_reader_;
  1460. Handlers delete_handlers_;
  1461. HandlersForContentReader delete_handlers_for_content_reader_;
  1462. Handlers options_handlers_;
  1463. struct WebSocketHandlerEntry {
  1464. std::unique_ptr<detail::MatcherBase> matcher;
  1465. WebSocketHandler handler;
  1466. SubProtocolSelector sub_protocol_selector;
  1467. };
  1468. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1469. WebSocketHandlers websocket_handlers_;
  1470. HandlerWithResponse error_handler_;
  1471. ExceptionHandler exception_handler_;
  1472. HandlerWithResponse pre_routing_handler_;
  1473. Handler post_routing_handler_;
  1474. HandlerWithResponse pre_request_handler_;
  1475. Expect100ContinueHandler expect_100_continue_handler_;
  1476. mutable std::mutex logger_mutex_;
  1477. Logger logger_;
  1478. Logger pre_compression_logger_;
  1479. ErrorLogger error_logger_;
  1480. int address_family_ = AF_UNSPEC;
  1481. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1482. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1483. SocketOptions socket_options_ = default_socket_options;
  1484. Headers default_headers_;
  1485. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1486. detail::write_headers;
  1487. };
  1488. class Result {
  1489. public:
  1490. Result() = default;
  1491. Result(std::unique_ptr<Response> &&res, Error err,
  1492. Headers &&request_headers = Headers{})
  1493. : res_(std::move(res)), err_(err),
  1494. request_headers_(std::move(request_headers)) {}
  1495. // Response
  1496. operator bool() const { return res_ != nullptr; }
  1497. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1498. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1499. const Response &value() const { return *res_; }
  1500. Response &value() { return *res_; }
  1501. const Response &operator*() const { return *res_; }
  1502. Response &operator*() { return *res_; }
  1503. const Response *operator->() const { return res_.get(); }
  1504. Response *operator->() { return res_.get(); }
  1505. // Error
  1506. Error error() const { return err_; }
  1507. // Request Headers
  1508. bool has_request_header(const std::string &key) const;
  1509. std::string get_request_header_value(const std::string &key,
  1510. const char *def = "",
  1511. size_t id = 0) const;
  1512. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1513. size_t id = 0) const;
  1514. size_t get_request_header_value_count(const std::string &key) const;
  1515. private:
  1516. std::unique_ptr<Response> res_;
  1517. Error err_ = Error::Unknown;
  1518. Headers request_headers_;
  1519. #ifdef CPPHTTPLIB_SSL_ENABLED
  1520. public:
  1521. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1522. int ssl_error)
  1523. : res_(std::move(res)), err_(err),
  1524. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1525. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1526. int ssl_error, unsigned long ssl_backend_error)
  1527. : res_(std::move(res)), err_(err),
  1528. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1529. ssl_backend_error_(ssl_backend_error) {}
  1530. int ssl_error() const { return ssl_error_; }
  1531. unsigned long ssl_backend_error() const { return ssl_backend_error_; }
  1532. private:
  1533. int ssl_error_ = 0;
  1534. unsigned long ssl_backend_error_ = 0;
  1535. #endif
  1536. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1537. public:
  1538. [[deprecated("Use ssl_backend_error() instead")]]
  1539. unsigned long ssl_openssl_error() const {
  1540. return ssl_backend_error_;
  1541. }
  1542. #endif
  1543. };
  1544. struct ClientConnection {
  1545. socket_t sock = INVALID_SOCKET;
  1546. bool is_open() const { return sock != INVALID_SOCKET; }
  1547. ClientConnection() = default;
  1548. ~ClientConnection();
  1549. ClientConnection(const ClientConnection &) = delete;
  1550. ClientConnection &operator=(const ClientConnection &) = delete;
  1551. ClientConnection(ClientConnection &&other) noexcept
  1552. : sock(other.sock)
  1553. #ifdef CPPHTTPLIB_SSL_ENABLED
  1554. ,
  1555. session(other.session)
  1556. #endif
  1557. {
  1558. other.sock = INVALID_SOCKET;
  1559. #ifdef CPPHTTPLIB_SSL_ENABLED
  1560. other.session = nullptr;
  1561. #endif
  1562. }
  1563. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1564. if (this != &other) {
  1565. sock = other.sock;
  1566. other.sock = INVALID_SOCKET;
  1567. #ifdef CPPHTTPLIB_SSL_ENABLED
  1568. session = other.session;
  1569. other.session = nullptr;
  1570. #endif
  1571. }
  1572. return *this;
  1573. }
  1574. #ifdef CPPHTTPLIB_SSL_ENABLED
  1575. tls::session_t session = nullptr;
  1576. #endif
  1577. };
  1578. namespace detail {
  1579. struct ChunkedDecoder;
  1580. struct BodyReader {
  1581. Stream *stream = nullptr;
  1582. bool has_content_length = false;
  1583. size_t content_length = 0;
  1584. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1585. size_t bytes_read = 0;
  1586. bool chunked = false;
  1587. bool eof = false;
  1588. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1589. Error last_error = Error::Success;
  1590. ssize_t read(char *buf, size_t len);
  1591. bool has_error() const { return last_error != Error::Success; }
  1592. };
  1593. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1594. size_t len) {
  1595. (void)stream;
  1596. return br.read(buf, len);
  1597. }
  1598. class decompressor;
  1599. } // namespace detail
  1600. class ClientImpl {
  1601. public:
  1602. explicit ClientImpl(const std::string &host);
  1603. explicit ClientImpl(const std::string &host, int port);
  1604. explicit ClientImpl(const std::string &host, int port,
  1605. const std::string &client_cert_path,
  1606. const std::string &client_key_path);
  1607. virtual ~ClientImpl();
  1608. virtual bool is_valid() const;
  1609. struct StreamHandle {
  1610. std::unique_ptr<Response> response;
  1611. Error error = Error::Success;
  1612. StreamHandle() = default;
  1613. StreamHandle(const StreamHandle &) = delete;
  1614. StreamHandle &operator=(const StreamHandle &) = delete;
  1615. StreamHandle(StreamHandle &&) = default;
  1616. StreamHandle &operator=(StreamHandle &&) = default;
  1617. ~StreamHandle() = default;
  1618. bool is_valid() const {
  1619. return response != nullptr && error == Error::Success;
  1620. }
  1621. ssize_t read(char *buf, size_t len);
  1622. void parse_trailers_if_needed();
  1623. Error get_read_error() const { return body_reader_.last_error; }
  1624. bool has_read_error() const { return body_reader_.has_error(); }
  1625. bool trailers_parsed_ = false;
  1626. private:
  1627. friend class ClientImpl;
  1628. ssize_t read_with_decompression(char *buf, size_t len);
  1629. std::unique_ptr<ClientConnection> connection_;
  1630. std::unique_ptr<Stream> socket_stream_;
  1631. Stream *stream_ = nullptr;
  1632. detail::BodyReader body_reader_;
  1633. std::unique_ptr<detail::decompressor> decompressor_;
  1634. std::string decompress_buffer_;
  1635. size_t decompress_offset_ = 0;
  1636. size_t decompressed_bytes_read_ = 0;
  1637. };
  1638. // clang-format off
  1639. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1640. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1641. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1642. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1643. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1644. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1645. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1646. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1647. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1648. Result Head(const std::string &path);
  1649. Result Head(const std::string &path, const Headers &headers);
  1650. Result Post(const std::string &path);
  1651. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1652. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1653. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1654. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1655. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1656. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1657. Result Post(const std::string &path, const Params &params);
  1658. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1659. Result Post(const std::string &path, const Headers &headers);
  1660. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1661. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1662. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1663. 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);
  1664. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1665. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1666. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1667. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1668. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1669. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1670. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1671. Result Put(const std::string &path);
  1672. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1673. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1674. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1675. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1676. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1677. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1678. Result Put(const std::string &path, const Params &params);
  1679. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1680. Result Put(const std::string &path, const Headers &headers);
  1681. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1682. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1683. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1684. 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);
  1685. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1686. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1687. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1688. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1689. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1690. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1691. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1692. Result Patch(const std::string &path);
  1693. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1694. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1695. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1696. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1697. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1698. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1699. Result Patch(const std::string &path, const Params &params);
  1700. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1701. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1702. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1703. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1704. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1705. 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);
  1706. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1707. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1708. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1709. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1710. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1711. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1712. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1713. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1714. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1715. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1716. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1717. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1718. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1719. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1720. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1721. Result Options(const std::string &path);
  1722. Result Options(const std::string &path, const Headers &headers);
  1723. // clang-format on
  1724. // Streaming API: Open a stream for reading response body incrementally
  1725. // Socket ownership is transferred to StreamHandle for true streaming
  1726. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1727. StreamHandle open_stream(const std::string &method, const std::string &path,
  1728. const Params &params = {},
  1729. const Headers &headers = {},
  1730. const std::string &body = {},
  1731. const std::string &content_type = {});
  1732. bool send(Request &req, Response &res, Error &error);
  1733. Result send(const Request &req);
  1734. void stop();
  1735. std::string host() const;
  1736. int port() const;
  1737. size_t is_socket_open() const;
  1738. socket_t socket() const;
  1739. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1740. void set_default_headers(Headers headers);
  1741. void
  1742. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1743. void set_address_family(int family);
  1744. void set_tcp_nodelay(bool on);
  1745. void set_ipv6_v6only(bool on);
  1746. void set_socket_options(SocketOptions socket_options);
  1747. void set_connection_timeout(time_t sec, time_t usec = 0);
  1748. template <class Rep, class Period>
  1749. void
  1750. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1751. void set_read_timeout(time_t sec, time_t usec = 0);
  1752. template <class Rep, class Period>
  1753. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1754. void set_write_timeout(time_t sec, time_t usec = 0);
  1755. template <class Rep, class Period>
  1756. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1757. void set_max_timeout(time_t msec);
  1758. template <class Rep, class Period>
  1759. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1760. void set_basic_auth(const std::string &username, const std::string &password);
  1761. void set_bearer_token_auth(const std::string &token);
  1762. void set_keep_alive(bool on);
  1763. void set_follow_location(bool on);
  1764. void set_path_encode(bool on);
  1765. void set_compress(bool on);
  1766. void set_decompress(bool on);
  1767. void set_payload_max_length(size_t length);
  1768. void set_interface(const std::string &intf);
  1769. void set_proxy(const std::string &host, int port);
  1770. void set_proxy_basic_auth(const std::string &username,
  1771. const std::string &password);
  1772. void set_proxy_bearer_token_auth(const std::string &token);
  1773. void set_logger(Logger logger);
  1774. void set_error_logger(ErrorLogger error_logger);
  1775. protected:
  1776. struct Socket {
  1777. socket_t sock = INVALID_SOCKET;
  1778. // For Mbed TLS compatibility: start_time for request timeout tracking
  1779. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1780. bool is_open() const { return sock != INVALID_SOCKET; }
  1781. #ifdef CPPHTTPLIB_SSL_ENABLED
  1782. tls::session_t ssl = nullptr;
  1783. #endif
  1784. };
  1785. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1786. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1787. // All of:
  1788. // shutdown_ssl
  1789. // shutdown_socket
  1790. // close_socket
  1791. // should ONLY be called when socket_mutex_ is locked.
  1792. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1793. // with a DIFFERENT thread sending requests using that socket.
  1794. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1795. void shutdown_socket(Socket &socket) const;
  1796. void close_socket(Socket &socket);
  1797. bool process_request(Stream &strm, Request &req, Response &res,
  1798. bool close_connection, Error &error);
  1799. bool write_content_with_provider(Stream &strm, const Request &req,
  1800. Error &error) const;
  1801. void copy_settings(const ClientImpl &rhs);
  1802. void output_log(const Request &req, const Response &res) const;
  1803. void output_error_log(const Error &err, const Request *req) const;
  1804. // Socket endpoint information
  1805. const std::string host_;
  1806. const int port_;
  1807. // Current open socket
  1808. Socket socket_;
  1809. mutable std::mutex socket_mutex_;
  1810. std::recursive_mutex request_mutex_;
  1811. // These are all protected under socket_mutex
  1812. size_t socket_requests_in_flight_ = 0;
  1813. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1814. bool socket_should_be_closed_when_request_is_done_ = false;
  1815. // Hostname-IP map
  1816. std::map<std::string, std::string> addr_map_;
  1817. // Default headers
  1818. Headers default_headers_;
  1819. // Header writer
  1820. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1821. detail::write_headers;
  1822. // Settings
  1823. std::string client_cert_path_;
  1824. std::string client_key_path_;
  1825. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1826. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1827. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1828. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1829. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1830. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1831. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1832. std::string basic_auth_username_;
  1833. std::string basic_auth_password_;
  1834. std::string bearer_token_auth_token_;
  1835. bool keep_alive_ = false;
  1836. bool follow_location_ = false;
  1837. bool path_encode_ = true;
  1838. int address_family_ = AF_UNSPEC;
  1839. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1840. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1841. SocketOptions socket_options_ = nullptr;
  1842. bool compress_ = false;
  1843. bool decompress_ = true;
  1844. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1845. bool has_payload_max_length_ = false;
  1846. std::string interface_;
  1847. std::string proxy_host_;
  1848. int proxy_port_ = -1;
  1849. std::string proxy_basic_auth_username_;
  1850. std::string proxy_basic_auth_password_;
  1851. std::string proxy_bearer_token_auth_token_;
  1852. mutable std::mutex logger_mutex_;
  1853. Logger logger_;
  1854. ErrorLogger error_logger_;
  1855. private:
  1856. bool send_(Request &req, Response &res, Error &error);
  1857. Result send_(Request &&req);
  1858. socket_t create_client_socket(Error &error) const;
  1859. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1860. bool skip_100_continue = true) const;
  1861. bool write_request(Stream &strm, Request &req, bool close_connection,
  1862. Error &error, bool skip_body = false);
  1863. bool write_request_body(Stream &strm, Request &req, Error &error);
  1864. void prepare_default_headers(Request &r, bool for_stream,
  1865. const std::string &ct);
  1866. bool redirect(Request &req, Response &res, Error &error);
  1867. bool create_redirect_client(const std::string &scheme,
  1868. const std::string &host, int port, Request &req,
  1869. Response &res, const std::string &path,
  1870. const std::string &location, Error &error);
  1871. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1872. bool handle_request(Stream &strm, Request &req, Response &res,
  1873. bool close_connection, Error &error);
  1874. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1875. Request &req, const char *body, size_t content_length,
  1876. ContentProvider content_provider,
  1877. ContentProviderWithoutLength content_provider_without_length,
  1878. const std::string &content_type, ContentReceiver content_receiver,
  1879. Error &error);
  1880. Result send_with_content_provider_and_receiver(
  1881. const std::string &method, const std::string &path,
  1882. const Headers &headers, const char *body, size_t content_length,
  1883. ContentProvider content_provider,
  1884. ContentProviderWithoutLength content_provider_without_length,
  1885. const std::string &content_type, ContentReceiver content_receiver,
  1886. UploadProgress progress);
  1887. ContentProviderWithoutLength get_multipart_content_provider(
  1888. const std::string &boundary, const UploadFormDataItems &items,
  1889. const FormDataProviderItems &provider_items) const;
  1890. virtual bool
  1891. process_socket(const Socket &socket,
  1892. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1893. std::function<bool(Stream &strm)> callback);
  1894. virtual bool is_ssl() const;
  1895. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1896. #ifdef CPPHTTPLIB_SSL_ENABLED
  1897. public:
  1898. void set_digest_auth(const std::string &username,
  1899. const std::string &password);
  1900. void set_proxy_digest_auth(const std::string &username,
  1901. const std::string &password);
  1902. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1903. const std::string &ca_cert_dir_path = std::string());
  1904. void enable_server_certificate_verification(bool enabled);
  1905. void enable_server_hostname_verification(bool enabled);
  1906. protected:
  1907. std::string digest_auth_username_;
  1908. std::string digest_auth_password_;
  1909. std::string proxy_digest_auth_username_;
  1910. std::string proxy_digest_auth_password_;
  1911. std::string ca_cert_file_path_;
  1912. std::string ca_cert_dir_path_;
  1913. bool server_certificate_verification_ = true;
  1914. bool server_hostname_verification_ = true;
  1915. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  1916. int last_ssl_error_ = 0;
  1917. unsigned long last_backend_error_ = 0;
  1918. #endif
  1919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1920. public:
  1921. [[deprecated("Use load_ca_cert_store() instead")]]
  1922. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1923. [[deprecated("Use tls::create_ca_store() instead")]]
  1924. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1925. [[deprecated("Use set_server_certificate_verifier(VerifyCallback) instead")]]
  1926. virtual void set_server_certificate_verifier(
  1927. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1928. #endif
  1929. };
  1930. class Client {
  1931. public:
  1932. // Universal interface
  1933. explicit Client(const std::string &scheme_host_port);
  1934. explicit Client(const std::string &scheme_host_port,
  1935. const std::string &client_cert_path,
  1936. const std::string &client_key_path);
  1937. // HTTP only interface
  1938. explicit Client(const std::string &host, int port);
  1939. explicit Client(const std::string &host, int port,
  1940. const std::string &client_cert_path,
  1941. const std::string &client_key_path);
  1942. Client(Client &&) = default;
  1943. Client &operator=(Client &&) = default;
  1944. ~Client();
  1945. bool is_valid() const;
  1946. // clang-format off
  1947. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1948. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1949. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1950. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1951. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1952. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1953. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1954. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1955. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1956. Result Head(const std::string &path);
  1957. Result Head(const std::string &path, const Headers &headers);
  1958. Result Post(const std::string &path);
  1959. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1960. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1961. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1962. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1963. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1964. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1965. Result Post(const std::string &path, const Params &params);
  1966. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1967. Result Post(const std::string &path, const Headers &headers);
  1968. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1969. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1970. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1971. 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);
  1972. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1973. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1974. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1975. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1976. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1977. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1978. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1979. Result Put(const std::string &path);
  1980. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1981. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1982. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1983. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1984. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1985. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1986. Result Put(const std::string &path, const Params &params);
  1987. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1988. Result Put(const std::string &path, const Headers &headers);
  1989. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1990. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1991. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1992. 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);
  1993. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1994. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1995. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1996. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1997. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1998. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1999. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2000. Result Patch(const std::string &path);
  2001. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2002. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2003. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2004. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2005. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2006. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2007. Result Patch(const std::string &path, const Params &params);
  2008. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2009. Result Patch(const std::string &path, const Headers &headers);
  2010. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2011. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2012. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2013. 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);
  2014. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2015. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2016. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2017. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2018. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2019. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2020. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2021. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2022. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2023. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2024. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2025. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2026. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2027. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2028. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2029. Result Options(const std::string &path);
  2030. Result Options(const std::string &path, const Headers &headers);
  2031. // clang-format on
  2032. // Streaming API: Open a stream for reading response body incrementally
  2033. // Socket ownership is transferred to StreamHandle for true streaming
  2034. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2035. ClientImpl::StreamHandle open_stream(const std::string &method,
  2036. const std::string &path,
  2037. const Params &params = {},
  2038. const Headers &headers = {},
  2039. const std::string &body = {},
  2040. const std::string &content_type = {});
  2041. bool send(Request &req, Response &res, Error &error);
  2042. Result send(const Request &req);
  2043. void stop();
  2044. std::string host() const;
  2045. int port() const;
  2046. size_t is_socket_open() const;
  2047. socket_t socket() const;
  2048. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2049. void set_default_headers(Headers headers);
  2050. void
  2051. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2052. void set_address_family(int family);
  2053. void set_tcp_nodelay(bool on);
  2054. void set_socket_options(SocketOptions socket_options);
  2055. void set_connection_timeout(time_t sec, time_t usec = 0);
  2056. template <class Rep, class Period>
  2057. void
  2058. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2059. void set_read_timeout(time_t sec, time_t usec = 0);
  2060. template <class Rep, class Period>
  2061. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2062. void set_write_timeout(time_t sec, time_t usec = 0);
  2063. template <class Rep, class Period>
  2064. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2065. void set_max_timeout(time_t msec);
  2066. template <class Rep, class Period>
  2067. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2068. void set_basic_auth(const std::string &username, const std::string &password);
  2069. void set_bearer_token_auth(const std::string &token);
  2070. void set_keep_alive(bool on);
  2071. void set_follow_location(bool on);
  2072. void set_path_encode(bool on);
  2073. void set_url_encode(bool on);
  2074. void set_compress(bool on);
  2075. void set_decompress(bool on);
  2076. void set_payload_max_length(size_t length);
  2077. void set_interface(const std::string &intf);
  2078. void set_proxy(const std::string &host, int port);
  2079. void set_proxy_basic_auth(const std::string &username,
  2080. const std::string &password);
  2081. void set_proxy_bearer_token_auth(const std::string &token);
  2082. void set_logger(Logger logger);
  2083. void set_error_logger(ErrorLogger error_logger);
  2084. private:
  2085. std::unique_ptr<ClientImpl> cli_;
  2086. #ifdef CPPHTTPLIB_SSL_ENABLED
  2087. public:
  2088. void set_digest_auth(const std::string &username,
  2089. const std::string &password);
  2090. void set_proxy_digest_auth(const std::string &username,
  2091. const std::string &password);
  2092. void enable_server_certificate_verification(bool enabled);
  2093. void enable_server_hostname_verification(bool enabled);
  2094. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2095. const std::string &ca_cert_dir_path = std::string());
  2096. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2097. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2098. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2099. void set_session_verifier(
  2100. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2101. tls::ctx_t tls_context() const;
  2102. #if defined(_WIN32) && \
  2103. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  2104. void enable_windows_certificate_verification(bool enabled);
  2105. #endif
  2106. private:
  2107. bool is_ssl_ = false;
  2108. #endif
  2109. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2110. public:
  2111. [[deprecated("Use tls_context() instead")]]
  2112. SSL_CTX *ssl_context() const;
  2113. [[deprecated("Use set_session_verifier(session_t) instead")]]
  2114. void set_server_certificate_verifier(
  2115. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  2116. [[deprecated("Use Result::ssl_backend_error() instead")]]
  2117. long get_verify_result() const;
  2118. #endif
  2119. };
  2120. #ifdef CPPHTTPLIB_SSL_ENABLED
  2121. class SSLServer : public Server {
  2122. public:
  2123. SSLServer(const char *cert_path, const char *private_key_path,
  2124. const char *client_ca_cert_file_path = nullptr,
  2125. const char *client_ca_cert_dir_path = nullptr,
  2126. const char *private_key_password = nullptr);
  2127. struct PemMemory {
  2128. const char *cert_pem;
  2129. size_t cert_pem_len;
  2130. const char *key_pem;
  2131. size_t key_pem_len;
  2132. const char *client_ca_pem;
  2133. size_t client_ca_pem_len;
  2134. const char *private_key_password;
  2135. };
  2136. explicit SSLServer(const PemMemory &pem);
  2137. // The callback receives the ctx_t handle which can be cast to the
  2138. // appropriate backend type (SSL_CTX* for OpenSSL,
  2139. // tls::impl::MbedTlsContext* for Mbed TLS)
  2140. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2141. ~SSLServer() override;
  2142. bool is_valid() const override;
  2143. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2144. const char *client_ca_pem = nullptr,
  2145. const char *password = nullptr);
  2146. tls::ctx_t tls_context() const { return ctx_; }
  2147. int ssl_last_error() const { return last_ssl_error_; }
  2148. private:
  2149. bool process_and_close_socket(socket_t sock) override;
  2150. tls::ctx_t ctx_ = nullptr;
  2151. std::mutex ctx_mutex_;
  2152. int last_ssl_error_ = 0;
  2153. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2154. public:
  2155. [[deprecated("Use SSLServer(PemMemory) or "
  2156. "SSLServer(ContextSetupCallback) instead")]]
  2157. SSLServer(X509 *cert, EVP_PKEY *private_key,
  2158. X509_STORE *client_ca_cert_store = nullptr);
  2159. [[deprecated("Use SSLServer(ContextSetupCallback) instead")]]
  2160. SSLServer(
  2161. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  2162. [[deprecated("Use tls_context() instead")]]
  2163. SSL_CTX *ssl_context() const;
  2164. [[deprecated("Use update_certs_pem() instead")]]
  2165. void update_certs(X509 *cert, EVP_PKEY *private_key,
  2166. X509_STORE *client_ca_cert_store = nullptr);
  2167. #endif
  2168. };
  2169. class SSLClient final : public ClientImpl {
  2170. public:
  2171. explicit SSLClient(const std::string &host);
  2172. explicit SSLClient(const std::string &host, int port);
  2173. explicit SSLClient(const std::string &host, int port,
  2174. const std::string &client_cert_path,
  2175. const std::string &client_key_path,
  2176. const std::string &private_key_password = std::string());
  2177. struct PemMemory {
  2178. const char *cert_pem;
  2179. size_t cert_pem_len;
  2180. const char *key_pem;
  2181. size_t key_pem_len;
  2182. const char *private_key_password;
  2183. };
  2184. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2185. ~SSLClient() override;
  2186. bool is_valid() const override;
  2187. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2188. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2189. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2190. // Post-handshake session verifier (backend-independent)
  2191. void set_session_verifier(
  2192. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2193. tls::ctx_t tls_context() const { return ctx_; }
  2194. #if defined(_WIN32) && \
  2195. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  2196. void enable_windows_certificate_verification(bool enabled);
  2197. #endif
  2198. private:
  2199. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2200. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2201. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2202. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2203. bool
  2204. process_socket(const Socket &socket,
  2205. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2206. std::function<bool(Stream &strm)> callback) override;
  2207. bool is_ssl() const override;
  2208. bool connect_with_proxy(
  2209. Socket &sock,
  2210. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2211. Response &res, bool &success, Error &error);
  2212. bool initialize_ssl(Socket &socket, Error &error);
  2213. bool load_certs();
  2214. tls::ctx_t ctx_ = nullptr;
  2215. std::mutex ctx_mutex_;
  2216. std::once_flag initialize_cert_;
  2217. long verify_result_ = 0;
  2218. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2219. #if defined(_WIN32) && \
  2220. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  2221. bool enable_windows_cert_verification_ = true;
  2222. #endif
  2223. friend class ClientImpl;
  2224. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2225. public:
  2226. [[deprecated("Use SSLClient(host, port, PemMemory) instead")]]
  2227. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  2228. EVP_PKEY *client_key,
  2229. const std::string &private_key_password = std::string());
  2230. [[deprecated("Use Result::ssl_backend_error() instead")]]
  2231. long get_verify_result() const;
  2232. [[deprecated("Use tls_context() instead")]]
  2233. SSL_CTX *ssl_context() const;
  2234. [[deprecated("Use set_session_verifier(session_t) instead")]]
  2235. void set_server_certificate_verifier(
  2236. std::function<SSLVerifierResponse(SSL *ssl)> verifier) override;
  2237. private:
  2238. bool verify_host(X509 *server_cert) const;
  2239. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  2240. bool verify_host_with_common_name(X509 *server_cert) const;
  2241. #endif
  2242. };
  2243. #endif // CPPHTTPLIB_SSL_ENABLED
  2244. namespace detail {
  2245. template <typename T, typename U>
  2246. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2247. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2248. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2249. duration - std::chrono::seconds(sec))
  2250. .count();
  2251. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2252. }
  2253. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2254. return N - 1;
  2255. }
  2256. inline bool is_numeric(const std::string &str) {
  2257. return !str.empty() &&
  2258. std::all_of(str.cbegin(), str.cend(),
  2259. [](unsigned char c) { return std::isdigit(c); });
  2260. }
  2261. inline size_t get_header_value_u64(const Headers &headers,
  2262. const std::string &key, size_t def,
  2263. size_t id, bool &is_invalid_value) {
  2264. is_invalid_value = false;
  2265. auto rng = headers.equal_range(key);
  2266. auto it = rng.first;
  2267. std::advance(it, static_cast<ssize_t>(id));
  2268. if (it != rng.second) {
  2269. if (is_numeric(it->second)) {
  2270. return std::strtoull(it->second.data(), nullptr, 10);
  2271. } else {
  2272. is_invalid_value = true;
  2273. }
  2274. }
  2275. return def;
  2276. }
  2277. inline size_t get_header_value_u64(const Headers &headers,
  2278. const std::string &key, size_t def,
  2279. size_t id) {
  2280. auto dummy = false;
  2281. return get_header_value_u64(headers, key, def, id, dummy);
  2282. }
  2283. } // namespace detail
  2284. template <class Rep, class Period>
  2285. inline Server &
  2286. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2287. detail::duration_to_sec_and_usec(
  2288. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2289. return *this;
  2290. }
  2291. template <class Rep, class Period>
  2292. inline Server &
  2293. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2294. detail::duration_to_sec_and_usec(
  2295. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2296. return *this;
  2297. }
  2298. template <class Rep, class Period>
  2299. inline Server &
  2300. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2301. detail::duration_to_sec_and_usec(
  2302. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2303. return *this;
  2304. }
  2305. template <class Rep, class Period>
  2306. inline void ClientImpl::set_connection_timeout(
  2307. const std::chrono::duration<Rep, Period> &duration) {
  2308. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2309. set_connection_timeout(sec, usec);
  2310. });
  2311. }
  2312. template <class Rep, class Period>
  2313. inline void ClientImpl::set_read_timeout(
  2314. const std::chrono::duration<Rep, Period> &duration) {
  2315. detail::duration_to_sec_and_usec(
  2316. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2317. }
  2318. template <class Rep, class Period>
  2319. inline void ClientImpl::set_write_timeout(
  2320. const std::chrono::duration<Rep, Period> &duration) {
  2321. detail::duration_to_sec_and_usec(
  2322. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2323. }
  2324. template <class Rep, class Period>
  2325. inline void ClientImpl::set_max_timeout(
  2326. const std::chrono::duration<Rep, Period> &duration) {
  2327. auto msec =
  2328. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2329. set_max_timeout(msec);
  2330. }
  2331. template <class Rep, class Period>
  2332. inline void Client::set_connection_timeout(
  2333. const std::chrono::duration<Rep, Period> &duration) {
  2334. cli_->set_connection_timeout(duration);
  2335. }
  2336. template <class Rep, class Period>
  2337. inline void
  2338. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2339. cli_->set_read_timeout(duration);
  2340. }
  2341. template <class Rep, class Period>
  2342. inline void
  2343. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2344. cli_->set_write_timeout(duration);
  2345. }
  2346. inline void Client::set_max_timeout(time_t msec) {
  2347. cli_->set_max_timeout(msec);
  2348. }
  2349. template <class Rep, class Period>
  2350. inline void
  2351. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2352. cli_->set_max_timeout(duration);
  2353. }
  2354. /*
  2355. * Forward declarations and types that will be part of the .h file if split into
  2356. * .h + .cc.
  2357. */
  2358. std::string hosted_at(const std::string &hostname);
  2359. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2360. // JavaScript-style URL encoding/decoding functions
  2361. std::string encode_uri_component(const std::string &value);
  2362. std::string encode_uri(const std::string &value);
  2363. std::string decode_uri_component(const std::string &value);
  2364. std::string decode_uri(const std::string &value);
  2365. // RFC 3986 compliant URL component encoding/decoding functions
  2366. std::string encode_path_component(const std::string &component);
  2367. std::string decode_path_component(const std::string &component);
  2368. std::string encode_query_component(const std::string &component,
  2369. bool space_as_plus = true);
  2370. std::string decode_query_component(const std::string &component,
  2371. bool plus_as_space = true);
  2372. std::string append_query_params(const std::string &path, const Params &params);
  2373. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2374. std::pair<std::string, std::string>
  2375. make_basic_authentication_header(const std::string &username,
  2376. const std::string &password,
  2377. bool is_proxy = false);
  2378. namespace detail {
  2379. #if defined(_WIN32)
  2380. inline std::wstring u8string_to_wstring(const char *s) {
  2381. if (!s) { return std::wstring(); }
  2382. auto len = static_cast<int>(strlen(s));
  2383. if (!len) { return std::wstring(); }
  2384. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2385. if (!wlen) { return std::wstring(); }
  2386. std::wstring ws;
  2387. ws.resize(wlen);
  2388. wlen = ::MultiByteToWideChar(
  2389. CP_UTF8, 0, s, len,
  2390. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2391. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2392. return ws;
  2393. }
  2394. #endif
  2395. struct FileStat {
  2396. FileStat(const std::string &path);
  2397. bool is_file() const;
  2398. bool is_dir() const;
  2399. time_t mtime() const;
  2400. size_t size() const;
  2401. private:
  2402. #if defined(_WIN32)
  2403. struct _stat st_;
  2404. #else
  2405. struct stat st_;
  2406. #endif
  2407. int ret_ = -1;
  2408. };
  2409. std::string make_host_and_port_string(const std::string &host, int port,
  2410. bool is_ssl);
  2411. std::string trim_copy(const std::string &s);
  2412. void divide(
  2413. const char *data, std::size_t size, char d,
  2414. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2415. fn);
  2416. void divide(
  2417. const std::string &str, char d,
  2418. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2419. fn);
  2420. void split(const char *b, const char *e, char d,
  2421. std::function<void(const char *, const char *)> fn);
  2422. void split(const char *b, const char *e, char d, size_t m,
  2423. std::function<void(const char *, const char *)> fn);
  2424. bool process_client_socket(
  2425. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2426. time_t write_timeout_sec, time_t write_timeout_usec,
  2427. time_t max_timeout_msec,
  2428. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2429. std::function<bool(Stream &)> callback);
  2430. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2431. int port, int address_family, bool tcp_nodelay,
  2432. bool ipv6_v6only, SocketOptions socket_options,
  2433. time_t connection_timeout_sec,
  2434. time_t connection_timeout_usec,
  2435. time_t read_timeout_sec, time_t read_timeout_usec,
  2436. time_t write_timeout_sec,
  2437. time_t write_timeout_usec,
  2438. const std::string &intf, Error &error);
  2439. const char *get_header_value(const Headers &headers, const std::string &key,
  2440. const char *def, size_t id);
  2441. std::string params_to_query_str(const Params &params);
  2442. void parse_query_text(const char *data, std::size_t size, Params &params);
  2443. void parse_query_text(const std::string &s, Params &params);
  2444. bool parse_multipart_boundary(const std::string &content_type,
  2445. std::string &boundary);
  2446. bool parse_range_header(const std::string &s, Ranges &ranges);
  2447. bool parse_accept_header(const std::string &s,
  2448. std::vector<std::string> &content_types);
  2449. int close_socket(socket_t sock);
  2450. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2451. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2452. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2453. EncodingType encoding_type(const Request &req, const Response &res);
  2454. class BufferStream final : public Stream {
  2455. public:
  2456. BufferStream() = default;
  2457. ~BufferStream() override = default;
  2458. bool is_readable() const override;
  2459. bool wait_readable() const override;
  2460. bool wait_writable() const override;
  2461. ssize_t read(char *ptr, size_t size) override;
  2462. ssize_t write(const char *ptr, size_t size) override;
  2463. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2464. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2465. socket_t socket() const override;
  2466. time_t duration() const override;
  2467. const std::string &get_buffer() const;
  2468. private:
  2469. std::string buffer;
  2470. size_t position = 0;
  2471. };
  2472. class compressor {
  2473. public:
  2474. virtual ~compressor() = default;
  2475. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2476. virtual bool compress(const char *data, size_t data_length, bool last,
  2477. Callback callback) = 0;
  2478. };
  2479. class decompressor {
  2480. public:
  2481. virtual ~decompressor() = default;
  2482. virtual bool is_valid() const = 0;
  2483. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2484. virtual bool decompress(const char *data, size_t data_length,
  2485. Callback callback) = 0;
  2486. };
  2487. class nocompressor final : public compressor {
  2488. public:
  2489. ~nocompressor() override = default;
  2490. bool compress(const char *data, size_t data_length, bool /*last*/,
  2491. Callback callback) override;
  2492. };
  2493. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2494. class gzip_compressor final : public compressor {
  2495. public:
  2496. gzip_compressor();
  2497. ~gzip_compressor() override;
  2498. bool compress(const char *data, size_t data_length, bool last,
  2499. Callback callback) override;
  2500. private:
  2501. bool is_valid_ = false;
  2502. z_stream strm_;
  2503. };
  2504. class gzip_decompressor final : public decompressor {
  2505. public:
  2506. gzip_decompressor();
  2507. ~gzip_decompressor() override;
  2508. bool is_valid() const override;
  2509. bool decompress(const char *data, size_t data_length,
  2510. Callback callback) override;
  2511. private:
  2512. bool is_valid_ = false;
  2513. z_stream strm_;
  2514. };
  2515. #endif
  2516. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2517. class brotli_compressor final : public compressor {
  2518. public:
  2519. brotli_compressor();
  2520. ~brotli_compressor();
  2521. bool compress(const char *data, size_t data_length, bool last,
  2522. Callback callback) override;
  2523. private:
  2524. BrotliEncoderState *state_ = nullptr;
  2525. };
  2526. class brotli_decompressor final : public decompressor {
  2527. public:
  2528. brotli_decompressor();
  2529. ~brotli_decompressor();
  2530. bool is_valid() const override;
  2531. bool decompress(const char *data, size_t data_length,
  2532. Callback callback) override;
  2533. private:
  2534. BrotliDecoderResult decoder_r;
  2535. BrotliDecoderState *decoder_s = nullptr;
  2536. };
  2537. #endif
  2538. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2539. class zstd_compressor : public compressor {
  2540. public:
  2541. zstd_compressor();
  2542. ~zstd_compressor();
  2543. bool compress(const char *data, size_t data_length, bool last,
  2544. Callback callback) override;
  2545. private:
  2546. ZSTD_CCtx *ctx_ = nullptr;
  2547. };
  2548. class zstd_decompressor : public decompressor {
  2549. public:
  2550. zstd_decompressor();
  2551. ~zstd_decompressor();
  2552. bool is_valid() const override;
  2553. bool decompress(const char *data, size_t data_length,
  2554. Callback callback) override;
  2555. private:
  2556. ZSTD_DCtx *ctx_ = nullptr;
  2557. };
  2558. #endif
  2559. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2560. // to store data. The call can set memory on stack for performance.
  2561. class stream_line_reader {
  2562. public:
  2563. stream_line_reader(Stream &strm, char *fixed_buffer,
  2564. size_t fixed_buffer_size);
  2565. const char *ptr() const;
  2566. size_t size() const;
  2567. bool end_with_crlf() const;
  2568. bool getline();
  2569. private:
  2570. void append(char c);
  2571. Stream &strm_;
  2572. char *fixed_buffer_;
  2573. const size_t fixed_buffer_size_;
  2574. size_t fixed_buffer_used_size_ = 0;
  2575. std::string growable_buffer_;
  2576. };
  2577. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2578. const Headers &src_headers);
  2579. struct ChunkedDecoder {
  2580. Stream &strm;
  2581. size_t chunk_remaining = 0;
  2582. bool finished = false;
  2583. char line_buf[64];
  2584. size_t last_chunk_total = 0;
  2585. size_t last_chunk_offset = 0;
  2586. explicit ChunkedDecoder(Stream &s);
  2587. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2588. size_t &out_chunk_total);
  2589. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2590. };
  2591. class mmap {
  2592. public:
  2593. mmap(const char *path);
  2594. ~mmap();
  2595. bool open(const char *path);
  2596. void close();
  2597. bool is_open() const;
  2598. size_t size() const;
  2599. const char *data() const;
  2600. private:
  2601. #if defined(_WIN32)
  2602. HANDLE hFile_ = NULL;
  2603. HANDLE hMapping_ = NULL;
  2604. #else
  2605. int fd_ = -1;
  2606. #endif
  2607. size_t size_ = 0;
  2608. void *addr_ = nullptr;
  2609. bool is_open_empty_file = false;
  2610. };
  2611. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2612. namespace fields {
  2613. bool is_token_char(char c);
  2614. bool is_token(const std::string &s);
  2615. bool is_field_name(const std::string &s);
  2616. bool is_vchar(char c);
  2617. bool is_obs_text(char c);
  2618. bool is_field_vchar(char c);
  2619. bool is_field_content(const std::string &s);
  2620. bool is_field_value(const std::string &s);
  2621. } // namespace fields
  2622. } // namespace detail
  2623. /*
  2624. * TLS Abstraction Layer Declarations
  2625. */
  2626. #ifdef CPPHTTPLIB_SSL_ENABLED
  2627. // TLS abstraction layer - backend-specific type declarations
  2628. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2629. namespace tls {
  2630. namespace impl {
  2631. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2632. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2633. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2634. struct MbedTlsContext {
  2635. mbedtls_ssl_config conf;
  2636. mbedtls_entropy_context entropy;
  2637. mbedtls_ctr_drbg_context ctr_drbg;
  2638. mbedtls_x509_crt ca_chain;
  2639. mbedtls_x509_crt own_cert;
  2640. mbedtls_pk_context own_key;
  2641. bool is_server = false;
  2642. bool verify_client = false;
  2643. bool has_verify_callback = false;
  2644. MbedTlsContext();
  2645. ~MbedTlsContext();
  2646. MbedTlsContext(const MbedTlsContext &) = delete;
  2647. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2648. };
  2649. } // namespace impl
  2650. } // namespace tls
  2651. #endif
  2652. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2653. namespace tls {
  2654. namespace impl {
  2655. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2656. // This struct is accessible via tls::impl for use in SSL context
  2657. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2658. struct WolfSSLContext {
  2659. WOLFSSL_CTX *ctx = nullptr;
  2660. bool is_server = false;
  2661. bool verify_client = false;
  2662. bool has_verify_callback = false;
  2663. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2664. WolfSSLContext();
  2665. ~WolfSSLContext();
  2666. WolfSSLContext(const WolfSSLContext &) = delete;
  2667. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2668. };
  2669. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2670. struct WolfSSLCAStore {
  2671. std::string pem_data;
  2672. };
  2673. } // namespace impl
  2674. } // namespace tls
  2675. #endif
  2676. #endif // CPPHTTPLIB_SSL_ENABLED
  2677. namespace stream {
  2678. class Result {
  2679. public:
  2680. Result();
  2681. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2682. Result(Result &&other) noexcept;
  2683. Result &operator=(Result &&other) noexcept;
  2684. Result(const Result &) = delete;
  2685. Result &operator=(const Result &) = delete;
  2686. // Response info
  2687. bool is_valid() const;
  2688. explicit operator bool() const;
  2689. int status() const;
  2690. const Headers &headers() const;
  2691. std::string get_header_value(const std::string &key,
  2692. const char *def = "") const;
  2693. bool has_header(const std::string &key) const;
  2694. Error error() const;
  2695. Error read_error() const;
  2696. bool has_read_error() const;
  2697. // Stream reading
  2698. bool next();
  2699. const char *data() const;
  2700. size_t size() const;
  2701. std::string read_all();
  2702. private:
  2703. ClientImpl::StreamHandle handle_;
  2704. std::string buffer_;
  2705. size_t current_size_ = 0;
  2706. size_t chunk_size_;
  2707. bool finished_ = false;
  2708. };
  2709. // GET
  2710. template <typename ClientType>
  2711. inline Result Get(ClientType &cli, const std::string &path,
  2712. size_t chunk_size = 8192) {
  2713. return Result{cli.open_stream("GET", path), chunk_size};
  2714. }
  2715. template <typename ClientType>
  2716. inline Result Get(ClientType &cli, const std::string &path,
  2717. const Headers &headers, size_t chunk_size = 8192) {
  2718. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2719. }
  2720. template <typename ClientType>
  2721. inline Result Get(ClientType &cli, const std::string &path,
  2722. const Params &params, size_t chunk_size = 8192) {
  2723. return Result{cli.open_stream("GET", path, params), chunk_size};
  2724. }
  2725. template <typename ClientType>
  2726. inline Result Get(ClientType &cli, const std::string &path,
  2727. const Params &params, const Headers &headers,
  2728. size_t chunk_size = 8192) {
  2729. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2730. }
  2731. // POST
  2732. template <typename ClientType>
  2733. inline Result Post(ClientType &cli, const std::string &path,
  2734. const std::string &body, const std::string &content_type,
  2735. size_t chunk_size = 8192) {
  2736. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2737. chunk_size};
  2738. }
  2739. template <typename ClientType>
  2740. inline Result Post(ClientType &cli, const std::string &path,
  2741. const Headers &headers, const std::string &body,
  2742. const std::string &content_type, size_t chunk_size = 8192) {
  2743. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2744. chunk_size};
  2745. }
  2746. template <typename ClientType>
  2747. inline Result Post(ClientType &cli, const std::string &path,
  2748. const Params &params, const std::string &body,
  2749. const std::string &content_type, size_t chunk_size = 8192) {
  2750. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2751. chunk_size};
  2752. }
  2753. template <typename ClientType>
  2754. inline Result Post(ClientType &cli, const std::string &path,
  2755. const Params &params, const Headers &headers,
  2756. const std::string &body, const std::string &content_type,
  2757. size_t chunk_size = 8192) {
  2758. return Result{
  2759. cli.open_stream("POST", path, params, headers, body, content_type),
  2760. chunk_size};
  2761. }
  2762. // PUT
  2763. template <typename ClientType>
  2764. inline Result Put(ClientType &cli, const std::string &path,
  2765. const std::string &body, const std::string &content_type,
  2766. size_t chunk_size = 8192) {
  2767. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2768. chunk_size};
  2769. }
  2770. template <typename ClientType>
  2771. inline Result Put(ClientType &cli, const std::string &path,
  2772. const Headers &headers, const std::string &body,
  2773. const std::string &content_type, size_t chunk_size = 8192) {
  2774. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2775. chunk_size};
  2776. }
  2777. template <typename ClientType>
  2778. inline Result Put(ClientType &cli, const std::string &path,
  2779. const Params &params, const std::string &body,
  2780. const std::string &content_type, size_t chunk_size = 8192) {
  2781. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2782. chunk_size};
  2783. }
  2784. template <typename ClientType>
  2785. inline Result Put(ClientType &cli, const std::string &path,
  2786. const Params &params, const Headers &headers,
  2787. const std::string &body, const std::string &content_type,
  2788. size_t chunk_size = 8192) {
  2789. return Result{
  2790. cli.open_stream("PUT", path, params, headers, body, content_type),
  2791. chunk_size};
  2792. }
  2793. // PATCH
  2794. template <typename ClientType>
  2795. inline Result Patch(ClientType &cli, const std::string &path,
  2796. const std::string &body, const std::string &content_type,
  2797. size_t chunk_size = 8192) {
  2798. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2799. chunk_size};
  2800. }
  2801. template <typename ClientType>
  2802. inline Result Patch(ClientType &cli, const std::string &path,
  2803. const Headers &headers, const std::string &body,
  2804. const std::string &content_type, size_t chunk_size = 8192) {
  2805. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2806. chunk_size};
  2807. }
  2808. template <typename ClientType>
  2809. inline Result Patch(ClientType &cli, const std::string &path,
  2810. const Params &params, const std::string &body,
  2811. const std::string &content_type, size_t chunk_size = 8192) {
  2812. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2813. chunk_size};
  2814. }
  2815. template <typename ClientType>
  2816. inline Result Patch(ClientType &cli, const std::string &path,
  2817. const Params &params, const Headers &headers,
  2818. const std::string &body, const std::string &content_type,
  2819. size_t chunk_size = 8192) {
  2820. return Result{
  2821. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2822. chunk_size};
  2823. }
  2824. // DELETE
  2825. template <typename ClientType>
  2826. inline Result Delete(ClientType &cli, const std::string &path,
  2827. size_t chunk_size = 8192) {
  2828. return Result{cli.open_stream("DELETE", path), chunk_size};
  2829. }
  2830. template <typename ClientType>
  2831. inline Result Delete(ClientType &cli, const std::string &path,
  2832. const Headers &headers, size_t chunk_size = 8192) {
  2833. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2834. }
  2835. template <typename ClientType>
  2836. inline Result Delete(ClientType &cli, const std::string &path,
  2837. const std::string &body, const std::string &content_type,
  2838. size_t chunk_size = 8192) {
  2839. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2840. chunk_size};
  2841. }
  2842. template <typename ClientType>
  2843. inline Result Delete(ClientType &cli, const std::string &path,
  2844. const Headers &headers, const std::string &body,
  2845. const std::string &content_type,
  2846. size_t chunk_size = 8192) {
  2847. return Result{
  2848. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2849. chunk_size};
  2850. }
  2851. template <typename ClientType>
  2852. inline Result Delete(ClientType &cli, const std::string &path,
  2853. const Params &params, size_t chunk_size = 8192) {
  2854. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2855. }
  2856. template <typename ClientType>
  2857. inline Result Delete(ClientType &cli, const std::string &path,
  2858. const Params &params, const Headers &headers,
  2859. size_t chunk_size = 8192) {
  2860. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2861. }
  2862. template <typename ClientType>
  2863. inline Result Delete(ClientType &cli, const std::string &path,
  2864. const Params &params, const std::string &body,
  2865. const std::string &content_type,
  2866. size_t chunk_size = 8192) {
  2867. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2868. chunk_size};
  2869. }
  2870. template <typename ClientType>
  2871. inline Result Delete(ClientType &cli, const std::string &path,
  2872. const Params &params, const Headers &headers,
  2873. const std::string &body, const std::string &content_type,
  2874. size_t chunk_size = 8192) {
  2875. return Result{
  2876. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2877. chunk_size};
  2878. }
  2879. // HEAD
  2880. template <typename ClientType>
  2881. inline Result Head(ClientType &cli, const std::string &path,
  2882. size_t chunk_size = 8192) {
  2883. return Result{cli.open_stream("HEAD", path), chunk_size};
  2884. }
  2885. template <typename ClientType>
  2886. inline Result Head(ClientType &cli, const std::string &path,
  2887. const Headers &headers, size_t chunk_size = 8192) {
  2888. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2889. }
  2890. template <typename ClientType>
  2891. inline Result Head(ClientType &cli, const std::string &path,
  2892. const Params &params, size_t chunk_size = 8192) {
  2893. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2894. }
  2895. template <typename ClientType>
  2896. inline Result Head(ClientType &cli, const std::string &path,
  2897. const Params &params, const Headers &headers,
  2898. size_t chunk_size = 8192) {
  2899. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2900. }
  2901. // OPTIONS
  2902. template <typename ClientType>
  2903. inline Result Options(ClientType &cli, const std::string &path,
  2904. size_t chunk_size = 8192) {
  2905. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2906. }
  2907. template <typename ClientType>
  2908. inline Result Options(ClientType &cli, const std::string &path,
  2909. const Headers &headers, size_t chunk_size = 8192) {
  2910. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2911. }
  2912. template <typename ClientType>
  2913. inline Result Options(ClientType &cli, const std::string &path,
  2914. const Params &params, size_t chunk_size = 8192) {
  2915. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2916. }
  2917. template <typename ClientType>
  2918. inline Result Options(ClientType &cli, const std::string &path,
  2919. const Params &params, const Headers &headers,
  2920. size_t chunk_size = 8192) {
  2921. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2922. }
  2923. } // namespace stream
  2924. namespace sse {
  2925. struct SSEMessage {
  2926. std::string event; // Event type (default: "message")
  2927. std::string data; // Event payload
  2928. std::string id; // Event ID for Last-Event-ID header
  2929. SSEMessage();
  2930. void clear();
  2931. };
  2932. class SSEClient {
  2933. public:
  2934. using MessageHandler = std::function<void(const SSEMessage &)>;
  2935. using ErrorHandler = std::function<void(Error)>;
  2936. using OpenHandler = std::function<void()>;
  2937. SSEClient(Client &client, const std::string &path);
  2938. SSEClient(Client &client, const std::string &path, const Headers &headers);
  2939. ~SSEClient();
  2940. SSEClient(const SSEClient &) = delete;
  2941. SSEClient &operator=(const SSEClient &) = delete;
  2942. // Event handlers
  2943. SSEClient &on_message(MessageHandler handler);
  2944. SSEClient &on_event(const std::string &type, MessageHandler handler);
  2945. SSEClient &on_open(OpenHandler handler);
  2946. SSEClient &on_error(ErrorHandler handler);
  2947. SSEClient &set_reconnect_interval(int ms);
  2948. SSEClient &set_max_reconnect_attempts(int n);
  2949. // State accessors
  2950. bool is_connected() const;
  2951. const std::string &last_event_id() const;
  2952. // Blocking start - runs event loop with auto-reconnect
  2953. void start();
  2954. // Non-blocking start - runs in background thread
  2955. void start_async();
  2956. // Stop the client (thread-safe)
  2957. void stop();
  2958. private:
  2959. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  2960. void run_event_loop();
  2961. void dispatch_event(const SSEMessage &msg);
  2962. bool should_reconnect(int count) const;
  2963. void wait_for_reconnect();
  2964. // Client and path
  2965. Client &client_;
  2966. std::string path_;
  2967. Headers headers_;
  2968. // Callbacks
  2969. MessageHandler on_message_;
  2970. std::map<std::string, MessageHandler> event_handlers_;
  2971. OpenHandler on_open_;
  2972. ErrorHandler on_error_;
  2973. // Configuration
  2974. int reconnect_interval_ms_ = 3000;
  2975. int max_reconnect_attempts_ = 0; // 0 = unlimited
  2976. // State
  2977. std::atomic<bool> running_{false};
  2978. std::atomic<bool> connected_{false};
  2979. std::string last_event_id_;
  2980. // Async support
  2981. std::thread async_thread_;
  2982. };
  2983. } // namespace sse
  2984. namespace ws {
  2985. enum class Opcode : uint8_t {
  2986. Continuation = 0x0,
  2987. Text = 0x1,
  2988. Binary = 0x2,
  2989. Close = 0x8,
  2990. Ping = 0x9,
  2991. Pong = 0xA,
  2992. };
  2993. enum class CloseStatus : uint16_t {
  2994. Normal = 1000,
  2995. GoingAway = 1001,
  2996. ProtocolError = 1002,
  2997. UnsupportedData = 1003,
  2998. NoStatus = 1005,
  2999. Abnormal = 1006,
  3000. InvalidPayload = 1007,
  3001. PolicyViolation = 1008,
  3002. MessageTooBig = 1009,
  3003. MandatoryExtension = 1010,
  3004. InternalError = 1011,
  3005. };
  3006. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3007. class WebSocket {
  3008. public:
  3009. WebSocket(const WebSocket &) = delete;
  3010. WebSocket &operator=(const WebSocket &) = delete;
  3011. ~WebSocket();
  3012. ReadResult read(std::string &msg);
  3013. bool send(const std::string &data);
  3014. bool send(const char *data, size_t len);
  3015. void close(CloseStatus status = CloseStatus::Normal,
  3016. const std::string &reason = "");
  3017. const Request &request() const;
  3018. bool is_open() const;
  3019. private:
  3020. friend class httplib::Server;
  3021. friend class WebSocketClient;
  3022. WebSocket(Stream &strm, const Request &req, bool is_server)
  3023. : strm_(strm), req_(req), is_server_(is_server) {
  3024. start_heartbeat();
  3025. }
  3026. WebSocket(std::unique_ptr<Stream> &&owned_strm, const Request &req,
  3027. bool is_server)
  3028. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3029. is_server_(is_server) {
  3030. start_heartbeat();
  3031. }
  3032. void start_heartbeat();
  3033. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3034. Stream &strm_;
  3035. std::unique_ptr<Stream> owned_strm_;
  3036. Request req_;
  3037. bool is_server_;
  3038. std::atomic<bool> closed_{false};
  3039. std::mutex write_mutex_;
  3040. std::thread ping_thread_;
  3041. std::mutex ping_mutex_;
  3042. std::condition_variable ping_cv_;
  3043. };
  3044. class WebSocketClient {
  3045. public:
  3046. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3047. const Headers &headers = {});
  3048. ~WebSocketClient();
  3049. WebSocketClient(const WebSocketClient &) = delete;
  3050. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3051. bool is_valid() const;
  3052. bool connect();
  3053. ReadResult read(std::string &msg);
  3054. bool send(const std::string &data);
  3055. bool send(const char *data, size_t len);
  3056. void close(CloseStatus status = CloseStatus::Normal,
  3057. const std::string &reason = "");
  3058. bool is_open() const;
  3059. const std::string &subprotocol() const;
  3060. void set_read_timeout(time_t sec, time_t usec = 0);
  3061. void set_write_timeout(time_t sec, time_t usec = 0);
  3062. #ifdef CPPHTTPLIB_SSL_ENABLED
  3063. void set_ca_cert_path(const std::string &path);
  3064. void set_ca_cert_store(tls::ca_store_t store);
  3065. void enable_server_certificate_verification(bool enabled);
  3066. #endif
  3067. private:
  3068. void shutdown_and_close();
  3069. bool create_stream(std::unique_ptr<Stream> &strm);
  3070. std::string host_;
  3071. int port_;
  3072. std::string path_;
  3073. Headers headers_;
  3074. std::string subprotocol_;
  3075. bool is_valid_ = false;
  3076. socket_t sock_ = INVALID_SOCKET;
  3077. std::unique_ptr<WebSocket> ws_;
  3078. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3079. time_t read_timeout_usec_ = 0;
  3080. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3081. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3082. #ifdef CPPHTTPLIB_SSL_ENABLED
  3083. bool is_ssl_ = false;
  3084. tls::ctx_t tls_ctx_ = nullptr;
  3085. tls::session_t tls_session_ = nullptr;
  3086. std::string ca_cert_file_path_;
  3087. tls::ca_store_t ca_cert_store_ = nullptr;
  3088. bool server_certificate_verification_ = true;
  3089. #endif
  3090. };
  3091. namespace impl {
  3092. bool is_valid_utf8(const std::string &s);
  3093. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3094. bool &fin, bool expect_masked, size_t max_len);
  3095. } // namespace impl
  3096. } // namespace ws
  3097. // ----------------------------------------------------------------------------
  3098. /*
  3099. * Implementation that will be part of the .cc file if split into .h + .cc.
  3100. */
  3101. namespace stream {
  3102. // stream::Result implementations
  3103. inline Result::Result() : chunk_size_(8192) {}
  3104. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3105. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3106. inline Result::Result(Result &&other) noexcept
  3107. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3108. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3109. finished_(other.finished_) {
  3110. other.current_size_ = 0;
  3111. other.finished_ = true;
  3112. }
  3113. inline Result &Result::operator=(Result &&other) noexcept {
  3114. if (this != &other) {
  3115. handle_ = std::move(other.handle_);
  3116. buffer_ = std::move(other.buffer_);
  3117. current_size_ = other.current_size_;
  3118. chunk_size_ = other.chunk_size_;
  3119. finished_ = other.finished_;
  3120. other.current_size_ = 0;
  3121. other.finished_ = true;
  3122. }
  3123. return *this;
  3124. }
  3125. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3126. inline Result::operator bool() const { return is_valid(); }
  3127. inline int Result::status() const {
  3128. return handle_.response ? handle_.response->status : -1;
  3129. }
  3130. inline const Headers &Result::headers() const {
  3131. static const Headers empty_headers;
  3132. return handle_.response ? handle_.response->headers : empty_headers;
  3133. }
  3134. inline std::string Result::get_header_value(const std::string &key,
  3135. const char *def) const {
  3136. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3137. }
  3138. inline bool Result::has_header(const std::string &key) const {
  3139. return handle_.response ? handle_.response->has_header(key) : false;
  3140. }
  3141. inline Error Result::error() const { return handle_.error; }
  3142. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3143. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3144. inline bool Result::next() {
  3145. if (!handle_.is_valid() || finished_) { return false; }
  3146. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3147. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3148. if (n > 0) {
  3149. current_size_ = static_cast<size_t>(n);
  3150. return true;
  3151. }
  3152. current_size_ = 0;
  3153. finished_ = true;
  3154. return false;
  3155. }
  3156. inline const char *Result::data() const { return buffer_.data(); }
  3157. inline size_t Result::size() const { return current_size_; }
  3158. inline std::string Result::read_all() {
  3159. std::string result;
  3160. while (next()) {
  3161. result.append(data(), size());
  3162. }
  3163. return result;
  3164. }
  3165. } // namespace stream
  3166. namespace sse {
  3167. // SSEMessage implementations
  3168. inline SSEMessage::SSEMessage() : event("message") {}
  3169. inline void SSEMessage::clear() {
  3170. event = "message";
  3171. data.clear();
  3172. id.clear();
  3173. }
  3174. // SSEClient implementations
  3175. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3176. : client_(client), path_(path) {}
  3177. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3178. const Headers &headers)
  3179. : client_(client), path_(path), headers_(headers) {}
  3180. inline SSEClient::~SSEClient() { stop(); }
  3181. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3182. on_message_ = std::move(handler);
  3183. return *this;
  3184. }
  3185. inline SSEClient &SSEClient::on_event(const std::string &type,
  3186. MessageHandler handler) {
  3187. event_handlers_[type] = std::move(handler);
  3188. return *this;
  3189. }
  3190. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3191. on_open_ = std::move(handler);
  3192. return *this;
  3193. }
  3194. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3195. on_error_ = std::move(handler);
  3196. return *this;
  3197. }
  3198. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3199. reconnect_interval_ms_ = ms;
  3200. return *this;
  3201. }
  3202. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3203. max_reconnect_attempts_ = n;
  3204. return *this;
  3205. }
  3206. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3207. inline const std::string &SSEClient::last_event_id() const {
  3208. return last_event_id_;
  3209. }
  3210. inline void SSEClient::start() {
  3211. running_.store(true);
  3212. run_event_loop();
  3213. }
  3214. inline void SSEClient::start_async() {
  3215. running_.store(true);
  3216. async_thread_ = std::thread([this]() { run_event_loop(); });
  3217. }
  3218. inline void SSEClient::stop() {
  3219. running_.store(false);
  3220. client_.stop(); // Cancel any pending operations
  3221. if (async_thread_.joinable()) { async_thread_.join(); }
  3222. }
  3223. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3224. int &retry_ms) {
  3225. // Blank line signals end of event
  3226. if (line.empty() || line == "\r") { return true; }
  3227. // Lines starting with ':' are comments (ignored)
  3228. if (!line.empty() && line[0] == ':') { return false; }
  3229. // Find the colon separator
  3230. auto colon_pos = line.find(':');
  3231. if (colon_pos == std::string::npos) {
  3232. // Line with no colon is treated as field name with empty value
  3233. return false;
  3234. }
  3235. auto field = line.substr(0, colon_pos);
  3236. std::string value;
  3237. // Value starts after colon, skip optional single space
  3238. if (colon_pos + 1 < line.size()) {
  3239. auto value_start = colon_pos + 1;
  3240. if (line[value_start] == ' ') { value_start++; }
  3241. value = line.substr(value_start);
  3242. // Remove trailing \r if present
  3243. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3244. }
  3245. // Handle known fields
  3246. if (field == "event") {
  3247. msg.event = value;
  3248. } else if (field == "data") {
  3249. // Multiple data lines are concatenated with newlines
  3250. if (!msg.data.empty()) { msg.data += "\n"; }
  3251. msg.data += value;
  3252. } else if (field == "id") {
  3253. // Empty id is valid (clears the last event ID)
  3254. msg.id = value;
  3255. } else if (field == "retry") {
  3256. // Parse retry interval in milliseconds
  3257. {
  3258. int v = 0;
  3259. auto res =
  3260. detail::from_chars(value.data(), value.data() + value.size(), v);
  3261. if (res.ec == std::errc{}) { retry_ms = v; }
  3262. }
  3263. }
  3264. // Unknown fields are ignored per SSE spec
  3265. return false;
  3266. }
  3267. inline void SSEClient::run_event_loop() {
  3268. auto reconnect_count = 0;
  3269. while (running_.load()) {
  3270. // Build headers, including Last-Event-ID if we have one
  3271. auto request_headers = headers_;
  3272. if (!last_event_id_.empty()) {
  3273. request_headers.emplace("Last-Event-ID", last_event_id_);
  3274. }
  3275. // Open streaming connection
  3276. auto result = stream::Get(client_, path_, request_headers);
  3277. // Connection error handling
  3278. if (!result) {
  3279. connected_.store(false);
  3280. if (on_error_) { on_error_(result.error()); }
  3281. if (!should_reconnect(reconnect_count)) { break; }
  3282. wait_for_reconnect();
  3283. reconnect_count++;
  3284. continue;
  3285. }
  3286. if (result.status() != 200) {
  3287. connected_.store(false);
  3288. // For certain errors, don't reconnect
  3289. if (result.status() == 204 || // No Content - server wants us to stop
  3290. result.status() == 404 || // Not Found
  3291. result.status() == 401 || // Unauthorized
  3292. result.status() == 403) { // Forbidden
  3293. if (on_error_) { on_error_(Error::Connection); }
  3294. break;
  3295. }
  3296. if (on_error_) { on_error_(Error::Connection); }
  3297. if (!should_reconnect(reconnect_count)) { break; }
  3298. wait_for_reconnect();
  3299. reconnect_count++;
  3300. continue;
  3301. }
  3302. // Connection successful
  3303. connected_.store(true);
  3304. reconnect_count = 0;
  3305. if (on_open_) { on_open_(); }
  3306. // Event receiving loop
  3307. std::string buffer;
  3308. SSEMessage current_msg;
  3309. while (running_.load() && result.next()) {
  3310. buffer.append(result.data(), result.size());
  3311. // Process complete lines in the buffer
  3312. size_t line_start = 0;
  3313. size_t newline_pos;
  3314. while ((newline_pos = buffer.find('\n', line_start)) !=
  3315. std::string::npos) {
  3316. auto line = buffer.substr(line_start, newline_pos - line_start);
  3317. line_start = newline_pos + 1;
  3318. // Parse the line and check if event is complete
  3319. auto event_complete =
  3320. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3321. if (event_complete && !current_msg.data.empty()) {
  3322. // Update last_event_id for reconnection
  3323. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3324. // Dispatch event to appropriate handler
  3325. dispatch_event(current_msg);
  3326. current_msg.clear();
  3327. }
  3328. }
  3329. // Keep unprocessed data in buffer
  3330. buffer.erase(0, line_start);
  3331. }
  3332. // Connection ended
  3333. connected_.store(false);
  3334. if (!running_.load()) { break; }
  3335. // Check for read errors
  3336. if (result.has_read_error()) {
  3337. if (on_error_) { on_error_(result.read_error()); }
  3338. }
  3339. if (!should_reconnect(reconnect_count)) { break; }
  3340. wait_for_reconnect();
  3341. reconnect_count++;
  3342. }
  3343. connected_.store(false);
  3344. }
  3345. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3346. // Check for specific event type handler first
  3347. auto it = event_handlers_.find(msg.event);
  3348. if (it != event_handlers_.end()) {
  3349. it->second(msg);
  3350. return;
  3351. }
  3352. // Fall back to generic message handler
  3353. if (on_message_) { on_message_(msg); }
  3354. }
  3355. inline bool SSEClient::should_reconnect(int count) const {
  3356. if (!running_.load()) { return false; }
  3357. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3358. return count < max_reconnect_attempts_;
  3359. }
  3360. inline void SSEClient::wait_for_reconnect() {
  3361. // Use small increments to check running_ flag frequently
  3362. auto waited = 0;
  3363. while (running_.load() && waited < reconnect_interval_ms_) {
  3364. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3365. waited += 100;
  3366. }
  3367. }
  3368. } // namespace sse
  3369. #ifdef CPPHTTPLIB_SSL_ENABLED
  3370. /*
  3371. * TLS abstraction layer - internal function declarations
  3372. * These are implementation details and not part of the public API.
  3373. */
  3374. namespace tls {
  3375. // Client context
  3376. ctx_t create_client_context();
  3377. void free_context(ctx_t ctx);
  3378. bool set_min_version(ctx_t ctx, Version version);
  3379. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3380. bool load_ca_file(ctx_t ctx, const char *file_path);
  3381. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3382. bool load_system_certs(ctx_t ctx);
  3383. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3384. const char *password);
  3385. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3386. const char *key_path, const char *password);
  3387. // Server context
  3388. ctx_t create_server_context();
  3389. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3390. const char *password);
  3391. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3392. const char *key_path, const char *password);
  3393. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3394. void set_verify_client(ctx_t ctx, bool require);
  3395. // Session management
  3396. session_t create_session(ctx_t ctx, socket_t sock);
  3397. void free_session(session_t session);
  3398. bool set_sni(session_t session, const char *hostname);
  3399. bool set_hostname(session_t session, const char *hostname);
  3400. // Handshake (non-blocking capable)
  3401. TlsError connect(session_t session);
  3402. TlsError accept(session_t session);
  3403. // Handshake with timeout (blocking until timeout)
  3404. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3405. time_t timeout_usec, TlsError *err);
  3406. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3407. time_t timeout_usec, TlsError *err);
  3408. // I/O (non-blocking capable)
  3409. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3410. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3411. int pending(const_session_t session);
  3412. void shutdown(session_t session, bool graceful);
  3413. // Connection state
  3414. bool is_peer_closed(session_t session, socket_t sock);
  3415. // Certificate verification
  3416. cert_t get_peer_cert(const_session_t session);
  3417. void free_cert(cert_t cert);
  3418. bool verify_hostname(cert_t cert, const char *hostname);
  3419. uint64_t hostname_mismatch_code();
  3420. long get_verify_result(const_session_t session);
  3421. // Certificate introspection
  3422. std::string get_cert_subject_cn(cert_t cert);
  3423. std::string get_cert_issuer_name(cert_t cert);
  3424. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3425. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3426. std::string get_cert_serial(cert_t cert);
  3427. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3428. const char *get_sni(const_session_t session);
  3429. // CA store management
  3430. ca_store_t create_ca_store(const char *pem, size_t len);
  3431. void free_ca_store(ca_store_t store);
  3432. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3433. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3434. std::vector<std::string> get_ca_names(ctx_t ctx);
  3435. // Dynamic certificate update (for servers)
  3436. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3437. const char *password);
  3438. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3439. // Certificate verification callback
  3440. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3441. long get_verify_error(const_session_t session);
  3442. std::string verify_error_string(long error_code);
  3443. // TlsError information
  3444. uint64_t peek_error();
  3445. uint64_t get_error();
  3446. std::string error_string(uint64_t code);
  3447. } // namespace tls
  3448. #endif // CPPHTTPLIB_SSL_ENABLED
  3449. /*
  3450. * Group 1: detail namespace - Non-SSL utilities
  3451. */
  3452. namespace detail {
  3453. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3454. const void *optval, socklen_t optlen) {
  3455. return setsockopt(sock, level, optname,
  3456. #ifdef _WIN32
  3457. reinterpret_cast<const char *>(optval),
  3458. #else
  3459. optval,
  3460. #endif
  3461. optlen) == 0;
  3462. }
  3463. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  3464. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  3465. }
  3466. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3467. time_t sec, time_t usec) {
  3468. #ifdef _WIN32
  3469. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3470. #else
  3471. timeval timeout;
  3472. timeout.tv_sec = static_cast<long>(sec);
  3473. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3474. #endif
  3475. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3476. }
  3477. inline bool is_hex(char c, int &v) {
  3478. if (isdigit(c)) {
  3479. v = c - '0';
  3480. return true;
  3481. } else if ('A' <= c && c <= 'F') {
  3482. v = c - 'A' + 10;
  3483. return true;
  3484. } else if ('a' <= c && c <= 'f') {
  3485. v = c - 'a' + 10;
  3486. return true;
  3487. }
  3488. return false;
  3489. }
  3490. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3491. int &val) {
  3492. if (i >= s.size()) { return false; }
  3493. val = 0;
  3494. for (; cnt; i++, cnt--) {
  3495. if (!s[i]) { return false; }
  3496. auto v = 0;
  3497. if (is_hex(s[i], v)) {
  3498. val = val * 16 + v;
  3499. } else {
  3500. return false;
  3501. }
  3502. }
  3503. return true;
  3504. }
  3505. inline std::string from_i_to_hex(size_t n) {
  3506. static const auto charset = "0123456789abcdef";
  3507. std::string ret;
  3508. do {
  3509. ret = charset[n & 15] + ret;
  3510. n >>= 4;
  3511. } while (n > 0);
  3512. return ret;
  3513. }
  3514. inline std::string compute_etag(const FileStat &fs) {
  3515. if (!fs.is_file()) { return std::string(); }
  3516. // If mtime cannot be determined (negative value indicates an error
  3517. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3518. // value like 0 could collide with a real file that legitimately has
  3519. // mtime == 0 (epoch) and lead to misleading validators.
  3520. auto mtime_raw = fs.mtime();
  3521. if (mtime_raw < 0) { return std::string(); }
  3522. auto mtime = static_cast<size_t>(mtime_raw);
  3523. auto size = fs.size();
  3524. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3525. from_i_to_hex(size) + "\"";
  3526. }
  3527. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3528. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3529. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3530. inline std::string file_mtime_to_http_date(time_t mtime) {
  3531. if (mtime < 0) { return std::string(); }
  3532. struct tm tm_buf;
  3533. #ifdef _WIN32
  3534. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3535. #else
  3536. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3537. #endif
  3538. char buf[64];
  3539. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3540. return std::string();
  3541. }
  3542. return std::string(buf);
  3543. }
  3544. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3545. inline time_t parse_http_date(const std::string &date_str) {
  3546. struct tm tm_buf;
  3547. // Create a classic locale object once for all parsing attempts
  3548. const std::locale classic_locale = std::locale::classic();
  3549. // Try to parse using std::get_time (C++11, cross-platform)
  3550. auto try_parse = [&](const char *fmt) -> bool {
  3551. std::istringstream ss(date_str);
  3552. ss.imbue(classic_locale);
  3553. memset(&tm_buf, 0, sizeof(tm_buf));
  3554. ss >> std::get_time(&tm_buf, fmt);
  3555. return !ss.fail();
  3556. };
  3557. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3558. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3559. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3560. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3561. // asctime format: "Sun Nov 6 08:49:37 1994"
  3562. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3563. return static_cast<time_t>(-1);
  3564. }
  3565. }
  3566. }
  3567. #ifdef _WIN32
  3568. return _mkgmtime(&tm_buf);
  3569. #elif defined _AIX
  3570. return mktime(&tm_buf);
  3571. #else
  3572. return timegm(&tm_buf);
  3573. #endif
  3574. }
  3575. inline bool is_weak_etag(const std::string &s) {
  3576. // Check if the string is a weak ETag (starts with 'W/"')
  3577. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3578. }
  3579. inline bool is_strong_etag(const std::string &s) {
  3580. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3581. // chars)
  3582. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3583. }
  3584. inline size_t to_utf8(int code, char *buff) {
  3585. if (code < 0x0080) {
  3586. buff[0] = static_cast<char>(code & 0x7F);
  3587. return 1;
  3588. } else if (code < 0x0800) {
  3589. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3590. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3591. return 2;
  3592. } else if (code < 0xD800) {
  3593. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3594. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3595. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3596. return 3;
  3597. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3598. return 0;
  3599. } else if (code < 0x10000) {
  3600. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3601. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3602. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3603. return 3;
  3604. } else if (code < 0x110000) {
  3605. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3606. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3607. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3608. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3609. return 4;
  3610. }
  3611. // NOTREACHED
  3612. return 0;
  3613. }
  3614. } // namespace detail
  3615. namespace ws {
  3616. namespace impl {
  3617. inline bool is_valid_utf8(const std::string &s) {
  3618. size_t i = 0;
  3619. auto n = s.size();
  3620. while (i < n) {
  3621. auto c = static_cast<unsigned char>(s[i]);
  3622. size_t len;
  3623. uint32_t cp;
  3624. if (c < 0x80) {
  3625. i++;
  3626. continue;
  3627. } else if ((c & 0xE0) == 0xC0) {
  3628. len = 2;
  3629. cp = c & 0x1F;
  3630. } else if ((c & 0xF0) == 0xE0) {
  3631. len = 3;
  3632. cp = c & 0x0F;
  3633. } else if ((c & 0xF8) == 0xF0) {
  3634. len = 4;
  3635. cp = c & 0x07;
  3636. } else {
  3637. return false;
  3638. }
  3639. if (i + len > n) { return false; }
  3640. for (size_t j = 1; j < len; j++) {
  3641. auto b = static_cast<unsigned char>(s[i + j]);
  3642. if ((b & 0xC0) != 0x80) { return false; }
  3643. cp = (cp << 6) | (b & 0x3F);
  3644. }
  3645. // Overlong encoding check
  3646. if (len == 2 && cp < 0x80) { return false; }
  3647. if (len == 3 && cp < 0x800) { return false; }
  3648. if (len == 4 && cp < 0x10000) { return false; }
  3649. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3650. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3651. if (cp > 0x10FFFF) { return false; }
  3652. i += len;
  3653. }
  3654. return true;
  3655. }
  3656. } // namespace impl
  3657. } // namespace ws
  3658. namespace detail {
  3659. // NOTE: This code came up with the following stackoverflow post:
  3660. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3661. inline std::string base64_encode(const std::string &in) {
  3662. static const auto lookup =
  3663. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3664. std::string out;
  3665. out.reserve(in.size());
  3666. auto val = 0;
  3667. auto valb = -6;
  3668. for (auto c : in) {
  3669. val = (val << 8) + static_cast<uint8_t>(c);
  3670. valb += 8;
  3671. while (valb >= 0) {
  3672. out.push_back(lookup[(val >> valb) & 0x3F]);
  3673. valb -= 6;
  3674. }
  3675. }
  3676. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3677. while (out.size() % 4) {
  3678. out.push_back('=');
  3679. }
  3680. return out;
  3681. }
  3682. inline std::string sha1(const std::string &input) {
  3683. // RFC 3174 SHA-1 implementation
  3684. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3685. return (x << n) | (x >> (32 - n));
  3686. };
  3687. uint32_t h0 = 0x67452301;
  3688. uint32_t h1 = 0xEFCDAB89;
  3689. uint32_t h2 = 0x98BADCFE;
  3690. uint32_t h3 = 0x10325476;
  3691. uint32_t h4 = 0xC3D2E1F0;
  3692. // Pre-processing: adding padding bits
  3693. std::string msg = input;
  3694. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3695. msg.push_back(static_cast<char>(0x80));
  3696. while (msg.size() % 64 != 56) {
  3697. msg.push_back(0);
  3698. }
  3699. // Append original length in bits as 64-bit big-endian
  3700. for (int i = 56; i >= 0; i -= 8) {
  3701. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3702. }
  3703. // Process each 512-bit chunk
  3704. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3705. uint32_t w[80];
  3706. for (size_t i = 0; i < 16; i++) {
  3707. w[i] =
  3708. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3709. << 24) |
  3710. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3711. << 16) |
  3712. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3713. << 8) |
  3714. (static_cast<uint32_t>(
  3715. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3716. }
  3717. for (int i = 16; i < 80; i++) {
  3718. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3719. }
  3720. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3721. for (int i = 0; i < 80; i++) {
  3722. uint32_t f, k;
  3723. if (i < 20) {
  3724. f = (b & c) | ((~b) & d);
  3725. k = 0x5A827999;
  3726. } else if (i < 40) {
  3727. f = b ^ c ^ d;
  3728. k = 0x6ED9EBA1;
  3729. } else if (i < 60) {
  3730. f = (b & c) | (b & d) | (c & d);
  3731. k = 0x8F1BBCDC;
  3732. } else {
  3733. f = b ^ c ^ d;
  3734. k = 0xCA62C1D6;
  3735. }
  3736. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3737. e = d;
  3738. d = c;
  3739. c = left_rotate(b, 30);
  3740. b = a;
  3741. a = temp;
  3742. }
  3743. h0 += a;
  3744. h1 += b;
  3745. h2 += c;
  3746. h3 += d;
  3747. h4 += e;
  3748. }
  3749. // Produce the final hash as a 20-byte binary string
  3750. std::string hash(20, '\0');
  3751. for (size_t i = 0; i < 4; i++) {
  3752. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3753. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3754. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3755. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3756. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3757. }
  3758. return hash;
  3759. }
  3760. inline std::string websocket_accept_key(const std::string &client_key) {
  3761. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3762. return base64_encode(sha1(client_key + magic));
  3763. }
  3764. inline bool is_websocket_upgrade(const Request &req) {
  3765. if (req.method != "GET") { return false; }
  3766. // Check Upgrade: websocket (case-insensitive)
  3767. auto upgrade_it = req.headers.find("Upgrade");
  3768. if (upgrade_it == req.headers.end()) { return false; }
  3769. auto upgrade_val = upgrade_it->second;
  3770. std::transform(upgrade_val.begin(), upgrade_val.end(), upgrade_val.begin(),
  3771. ::tolower);
  3772. if (upgrade_val != "websocket") { return false; }
  3773. // Check Connection header contains "Upgrade"
  3774. auto connection_it = req.headers.find("Connection");
  3775. if (connection_it == req.headers.end()) { return false; }
  3776. auto connection_val = connection_it->second;
  3777. std::transform(connection_val.begin(), connection_val.end(),
  3778. connection_val.begin(), ::tolower);
  3779. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3780. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3781. // RFC 6455 Section 4.2.1
  3782. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3783. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3784. return false;
  3785. }
  3786. static const std::string b64chars =
  3787. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3788. for (size_t i = 0; i < 22; i++) {
  3789. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3790. }
  3791. // Check Sec-WebSocket-Version: 13
  3792. auto version = req.get_header_value("Sec-WebSocket-Version");
  3793. if (version != "13") { return false; }
  3794. return true;
  3795. }
  3796. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  3797. const char *data, size_t len, bool fin,
  3798. bool mask) {
  3799. // First byte: FIN + opcode
  3800. uint8_t header[2];
  3801. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  3802. (static_cast<uint8_t>(opcode) & 0x0F));
  3803. // Second byte: MASK + payload length
  3804. if (len < 126) {
  3805. header[1] = static_cast<uint8_t>(len);
  3806. if (mask) { header[1] |= 0x80; }
  3807. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3808. } else if (len <= 0xFFFF) {
  3809. header[1] = 126;
  3810. if (mask) { header[1] |= 0x80; }
  3811. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3812. uint8_t ext[2];
  3813. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  3814. ext[1] = static_cast<uint8_t>(len & 0xFF);
  3815. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  3816. } else {
  3817. header[1] = 127;
  3818. if (mask) { header[1] |= 0x80; }
  3819. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3820. uint8_t ext[8];
  3821. for (int i = 7; i >= 0; i--) {
  3822. ext[7 - i] = static_cast<uint8_t>((len >> (i * 8)) & 0xFF);
  3823. }
  3824. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  3825. }
  3826. if (mask) {
  3827. // Generate random mask key
  3828. thread_local std::mt19937 rng(std::random_device{}());
  3829. uint8_t mask_key[4];
  3830. auto r = rng();
  3831. std::memcpy(mask_key, &r, 4);
  3832. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  3833. // Write masked payload in chunks
  3834. const size_t chunk_size = 4096;
  3835. std::vector<char> buf((std::min)(len, chunk_size));
  3836. for (size_t offset = 0; offset < len; offset += chunk_size) {
  3837. size_t n = (std::min)(chunk_size, len - offset);
  3838. for (size_t i = 0; i < n; i++) {
  3839. buf[i] =
  3840. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  3841. }
  3842. if (strm.write(buf.data(), n) < 0) { return false; }
  3843. }
  3844. } else {
  3845. if (len > 0) {
  3846. if (strm.write(data, len) < 0) { return false; }
  3847. }
  3848. }
  3849. return true;
  3850. }
  3851. } // namespace detail
  3852. namespace ws {
  3853. namespace impl {
  3854. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  3855. std::string &payload, bool &fin,
  3856. bool expect_masked, size_t max_len) {
  3857. // Read first 2 bytes
  3858. uint8_t header[2];
  3859. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  3860. fin = (header[0] & 0x80) != 0;
  3861. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  3862. if (header[0] & 0x70) { return false; }
  3863. opcode = static_cast<Opcode>(header[0] & 0x0F);
  3864. bool masked = (header[1] & 0x80) != 0;
  3865. uint64_t payload_len = header[1] & 0x7F;
  3866. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  3867. // MUST have a payload length of 125 bytes or less
  3868. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  3869. if (is_control) {
  3870. if (!fin) { return false; }
  3871. if (payload_len > 125) { return false; }
  3872. }
  3873. if (masked != expect_masked) { return false; }
  3874. // Extended payload length
  3875. if (payload_len == 126) {
  3876. uint8_t ext[2];
  3877. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  3878. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  3879. } else if (payload_len == 127) {
  3880. uint8_t ext[8];
  3881. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  3882. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  3883. if (ext[0] & 0x80) { return false; }
  3884. payload_len = 0;
  3885. for (int i = 0; i < 8; i++) {
  3886. payload_len = (payload_len << 8) | ext[i];
  3887. }
  3888. }
  3889. if (payload_len > max_len) { return false; }
  3890. // Read mask key if present
  3891. uint8_t mask_key[4] = {0};
  3892. if (masked) {
  3893. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  3894. }
  3895. // Read payload
  3896. payload.resize(static_cast<size_t>(payload_len));
  3897. if (payload_len > 0) {
  3898. size_t total_read = 0;
  3899. while (total_read < payload_len) {
  3900. auto n = strm.read(&payload[total_read],
  3901. static_cast<size_t>(payload_len - total_read));
  3902. if (n <= 0) { return false; }
  3903. total_read += static_cast<size_t>(n);
  3904. }
  3905. }
  3906. // Unmask if needed
  3907. if (masked) {
  3908. for (size_t i = 0; i < payload.size(); i++) {
  3909. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  3910. }
  3911. }
  3912. return true;
  3913. }
  3914. } // namespace impl
  3915. } // namespace ws
  3916. namespace detail {
  3917. inline bool is_valid_path(const std::string &path) {
  3918. size_t level = 0;
  3919. size_t i = 0;
  3920. // Skip slash
  3921. while (i < path.size() && path[i] == '/') {
  3922. i++;
  3923. }
  3924. while (i < path.size()) {
  3925. // Read component
  3926. auto beg = i;
  3927. while (i < path.size() && path[i] != '/') {
  3928. if (path[i] == '\0') {
  3929. return false;
  3930. } else if (path[i] == '\\') {
  3931. return false;
  3932. }
  3933. i++;
  3934. }
  3935. auto len = i - beg;
  3936. assert(len > 0);
  3937. if (!path.compare(beg, len, ".")) {
  3938. ;
  3939. } else if (!path.compare(beg, len, "..")) {
  3940. if (level == 0) { return false; }
  3941. level--;
  3942. } else {
  3943. level++;
  3944. }
  3945. // Skip slash
  3946. while (i < path.size() && path[i] == '/') {
  3947. i++;
  3948. }
  3949. }
  3950. return true;
  3951. }
  3952. inline FileStat::FileStat(const std::string &path) {
  3953. #if defined(_WIN32)
  3954. auto wpath = u8string_to_wstring(path.c_str());
  3955. ret_ = _wstat(wpath.c_str(), &st_);
  3956. #else
  3957. ret_ = stat(path.c_str(), &st_);
  3958. #endif
  3959. }
  3960. inline bool FileStat::is_file() const {
  3961. return ret_ >= 0 && S_ISREG(st_.st_mode);
  3962. }
  3963. inline bool FileStat::is_dir() const {
  3964. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  3965. }
  3966. inline time_t FileStat::mtime() const {
  3967. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  3968. : static_cast<time_t>(-1);
  3969. }
  3970. inline size_t FileStat::size() const {
  3971. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  3972. }
  3973. inline std::string encode_path(const std::string &s) {
  3974. std::string result;
  3975. result.reserve(s.size());
  3976. for (size_t i = 0; s[i]; i++) {
  3977. switch (s[i]) {
  3978. case ' ': result += "%20"; break;
  3979. case '+': result += "%2B"; break;
  3980. case '\r': result += "%0D"; break;
  3981. case '\n': result += "%0A"; break;
  3982. case '\'': result += "%27"; break;
  3983. case ',': result += "%2C"; break;
  3984. // case ':': result += "%3A"; break; // ok? probably...
  3985. case ';': result += "%3B"; break;
  3986. default:
  3987. auto c = static_cast<uint8_t>(s[i]);
  3988. if (c >= 0x80) {
  3989. result += '%';
  3990. char hex[4];
  3991. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  3992. assert(len == 2);
  3993. result.append(hex, static_cast<size_t>(len));
  3994. } else {
  3995. result += s[i];
  3996. }
  3997. break;
  3998. }
  3999. }
  4000. return result;
  4001. }
  4002. inline std::string file_extension(const std::string &path) {
  4003. std::smatch m;
  4004. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4005. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4006. return std::string();
  4007. }
  4008. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4009. template <typename T>
  4010. inline bool parse_header(const char *beg, const char *end, T fn);
  4011. template <typename T>
  4012. inline bool parse_header(const char *beg, const char *end, T fn) {
  4013. // Skip trailing spaces and tabs.
  4014. while (beg < end && is_space_or_tab(end[-1])) {
  4015. end--;
  4016. }
  4017. auto p = beg;
  4018. while (p < end && *p != ':') {
  4019. p++;
  4020. }
  4021. auto name = std::string(beg, p);
  4022. if (!detail::fields::is_field_name(name)) { return false; }
  4023. if (p == end) { return false; }
  4024. auto key_end = p;
  4025. if (*p++ != ':') { return false; }
  4026. while (p < end && is_space_or_tab(*p)) {
  4027. p++;
  4028. }
  4029. if (p <= end) {
  4030. auto key_len = key_end - beg;
  4031. if (!key_len) { return false; }
  4032. auto key = std::string(beg, key_end);
  4033. auto val = std::string(p, end);
  4034. if (!detail::fields::is_field_value(val)) { return false; }
  4035. if (case_ignore::equal(key, "Location") ||
  4036. case_ignore::equal(key, "Referer")) {
  4037. fn(key, val);
  4038. } else {
  4039. fn(key, decode_path_component(val));
  4040. }
  4041. return true;
  4042. }
  4043. return false;
  4044. }
  4045. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4046. const Headers &src_headers) {
  4047. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4048. // transfer coding is complete when a chunk with a chunk-size of zero is
  4049. // received, possibly followed by a trailer section, and finally terminated by
  4050. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4051. //
  4052. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4053. // doesn't care for the existence of the final CRLF. In other words, it seems
  4054. // to be ok whether the final CRLF exists or not in the chunked data.
  4055. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4056. //
  4057. // According to the reference code in RFC 9112, cpp-httplib now allows
  4058. // chunked transfer coding data without the final CRLF.
  4059. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4060. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4061. "transfer-encoding",
  4062. "content-length",
  4063. "host",
  4064. "authorization",
  4065. "www-authenticate",
  4066. "proxy-authenticate",
  4067. "proxy-authorization",
  4068. "cookie",
  4069. "set-cookie",
  4070. "cache-control",
  4071. "expect",
  4072. "max-forwards",
  4073. "pragma",
  4074. "range",
  4075. "te",
  4076. "age",
  4077. "expires",
  4078. "date",
  4079. "location",
  4080. "retry-after",
  4081. "vary",
  4082. "warning",
  4083. "content-encoding",
  4084. "content-type",
  4085. "content-range",
  4086. "trailer"};
  4087. case_ignore::unordered_set<std::string> declared_trailers;
  4088. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4089. if (trailer_header && std::strlen(trailer_header)) {
  4090. auto len = std::strlen(trailer_header);
  4091. split(trailer_header, trailer_header + len, ',',
  4092. [&](const char *b, const char *e) {
  4093. const char *kbeg = b;
  4094. const char *kend = e;
  4095. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4096. ++kbeg;
  4097. }
  4098. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4099. --kend;
  4100. }
  4101. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4102. if (!key.empty() &&
  4103. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4104. declared_trailers.insert(key);
  4105. }
  4106. });
  4107. }
  4108. size_t trailer_header_count = 0;
  4109. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4110. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4111. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4112. constexpr auto line_terminator_len = 2;
  4113. auto line_beg = line_reader.ptr();
  4114. auto line_end =
  4115. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4116. if (!parse_header(line_beg, line_end,
  4117. [&](const std::string &key, const std::string &val) {
  4118. if (declared_trailers.find(key) !=
  4119. declared_trailers.end()) {
  4120. dest.emplace(key, val);
  4121. trailer_header_count++;
  4122. }
  4123. })) {
  4124. return false;
  4125. }
  4126. if (!line_reader.getline()) { return false; }
  4127. }
  4128. return true;
  4129. }
  4130. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4131. size_t right) {
  4132. while (b + left < e && is_space_or_tab(b[left])) {
  4133. left++;
  4134. }
  4135. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4136. right--;
  4137. }
  4138. return std::make_pair(left, right);
  4139. }
  4140. inline std::string trim_copy(const std::string &s) {
  4141. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4142. return s.substr(r.first, r.second - r.first);
  4143. }
  4144. inline std::string trim_double_quotes_copy(const std::string &s) {
  4145. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4146. return s.substr(1, s.size() - 2);
  4147. }
  4148. return s;
  4149. }
  4150. inline void
  4151. divide(const char *data, std::size_t size, char d,
  4152. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4153. fn) {
  4154. const auto it = std::find(data, data + size, d);
  4155. const auto found = static_cast<std::size_t>(it != data + size);
  4156. const auto lhs_data = data;
  4157. const auto lhs_size = static_cast<std::size_t>(it - data);
  4158. const auto rhs_data = it + found;
  4159. const auto rhs_size = size - lhs_size - found;
  4160. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4161. }
  4162. inline void
  4163. divide(const std::string &str, char d,
  4164. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4165. fn) {
  4166. divide(str.data(), str.size(), d, std::move(fn));
  4167. }
  4168. inline void split(const char *b, const char *e, char d,
  4169. std::function<void(const char *, const char *)> fn) {
  4170. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4171. }
  4172. inline void split(const char *b, const char *e, char d, size_t m,
  4173. std::function<void(const char *, const char *)> fn) {
  4174. size_t i = 0;
  4175. size_t beg = 0;
  4176. size_t count = 1;
  4177. while (e ? (b + i < e) : (b[i] != '\0')) {
  4178. if (b[i] == d && count < m) {
  4179. auto r = trim(b, e, beg, i);
  4180. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4181. beg = i + 1;
  4182. count++;
  4183. }
  4184. i++;
  4185. }
  4186. if (i) {
  4187. auto r = trim(b, e, beg, i);
  4188. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4189. }
  4190. }
  4191. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4192. std::function<bool(const char *, const char *)> fn) {
  4193. size_t i = 0;
  4194. size_t beg = 0;
  4195. size_t count = 1;
  4196. while (e ? (b + i < e) : (b[i] != '\0')) {
  4197. if (b[i] == d && count < m) {
  4198. auto r = trim(b, e, beg, i);
  4199. if (r.first < r.second) {
  4200. auto found = fn(&b[r.first], &b[r.second]);
  4201. if (found) { return true; }
  4202. }
  4203. beg = i + 1;
  4204. count++;
  4205. }
  4206. i++;
  4207. }
  4208. if (i) {
  4209. auto r = trim(b, e, beg, i);
  4210. if (r.first < r.second) {
  4211. auto found = fn(&b[r.first], &b[r.second]);
  4212. if (found) { return true; }
  4213. }
  4214. }
  4215. return false;
  4216. }
  4217. inline bool split_find(const char *b, const char *e, char d,
  4218. std::function<bool(const char *, const char *)> fn) {
  4219. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4220. std::move(fn));
  4221. }
  4222. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4223. size_t fixed_buffer_size)
  4224. : strm_(strm), fixed_buffer_(fixed_buffer),
  4225. fixed_buffer_size_(fixed_buffer_size) {}
  4226. inline const char *stream_line_reader::ptr() const {
  4227. if (growable_buffer_.empty()) {
  4228. return fixed_buffer_;
  4229. } else {
  4230. return growable_buffer_.data();
  4231. }
  4232. }
  4233. inline size_t stream_line_reader::size() const {
  4234. if (growable_buffer_.empty()) {
  4235. return fixed_buffer_used_size_;
  4236. } else {
  4237. return growable_buffer_.size();
  4238. }
  4239. }
  4240. inline bool stream_line_reader::end_with_crlf() const {
  4241. auto end = ptr() + size();
  4242. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4243. }
  4244. inline bool stream_line_reader::getline() {
  4245. fixed_buffer_used_size_ = 0;
  4246. growable_buffer_.clear();
  4247. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4248. char prev_byte = 0;
  4249. #endif
  4250. for (size_t i = 0;; i++) {
  4251. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4252. // Treat exceptionally long lines as an error to
  4253. // prevent infinite loops/memory exhaustion
  4254. return false;
  4255. }
  4256. char byte;
  4257. auto n = strm_.read(&byte, 1);
  4258. if (n < 0) {
  4259. return false;
  4260. } else if (n == 0) {
  4261. if (i == 0) {
  4262. return false;
  4263. } else {
  4264. break;
  4265. }
  4266. }
  4267. append(byte);
  4268. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4269. if (byte == '\n') { break; }
  4270. #else
  4271. if (prev_byte == '\r' && byte == '\n') { break; }
  4272. prev_byte = byte;
  4273. #endif
  4274. }
  4275. return true;
  4276. }
  4277. inline void stream_line_reader::append(char c) {
  4278. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4279. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4280. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4281. } else {
  4282. if (growable_buffer_.empty()) {
  4283. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4284. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4285. }
  4286. growable_buffer_ += c;
  4287. }
  4288. }
  4289. inline mmap::mmap(const char *path) { open(path); }
  4290. inline mmap::~mmap() { close(); }
  4291. inline bool mmap::open(const char *path) {
  4292. close();
  4293. #if defined(_WIN32)
  4294. auto wpath = u8string_to_wstring(path);
  4295. if (wpath.empty()) { return false; }
  4296. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  4297. OPEN_EXISTING, NULL);
  4298. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4299. LARGE_INTEGER size{};
  4300. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4301. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4302. // See:
  4303. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4304. if (static_cast<ULONGLONG>(size.QuadPart) >
  4305. (std::numeric_limits<decltype(size_)>::max)()) {
  4306. // `size_t` might be 32-bits, on 32-bits Windows.
  4307. return false;
  4308. }
  4309. size_ = static_cast<size_t>(size.QuadPart);
  4310. hMapping_ =
  4311. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4312. // Special treatment for an empty file...
  4313. if (hMapping_ == NULL && size_ == 0) {
  4314. close();
  4315. is_open_empty_file = true;
  4316. return true;
  4317. }
  4318. if (hMapping_ == NULL) {
  4319. close();
  4320. return false;
  4321. }
  4322. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4323. if (addr_ == nullptr) {
  4324. close();
  4325. return false;
  4326. }
  4327. #else
  4328. fd_ = ::open(path, O_RDONLY);
  4329. if (fd_ == -1) { return false; }
  4330. struct stat sb;
  4331. if (fstat(fd_, &sb) == -1) {
  4332. close();
  4333. return false;
  4334. }
  4335. size_ = static_cast<size_t>(sb.st_size);
  4336. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4337. // Special treatment for an empty file...
  4338. if (addr_ == MAP_FAILED && size_ == 0) {
  4339. close();
  4340. is_open_empty_file = true;
  4341. return false;
  4342. }
  4343. #endif
  4344. return true;
  4345. }
  4346. inline bool mmap::is_open() const {
  4347. return is_open_empty_file ? true : addr_ != nullptr;
  4348. }
  4349. inline size_t mmap::size() const { return size_; }
  4350. inline const char *mmap::data() const {
  4351. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4352. }
  4353. inline void mmap::close() {
  4354. #if defined(_WIN32)
  4355. if (addr_) {
  4356. ::UnmapViewOfFile(addr_);
  4357. addr_ = nullptr;
  4358. }
  4359. if (hMapping_) {
  4360. ::CloseHandle(hMapping_);
  4361. hMapping_ = NULL;
  4362. }
  4363. if (hFile_ != INVALID_HANDLE_VALUE) {
  4364. ::CloseHandle(hFile_);
  4365. hFile_ = INVALID_HANDLE_VALUE;
  4366. }
  4367. is_open_empty_file = false;
  4368. #else
  4369. if (addr_ != nullptr) {
  4370. munmap(addr_, size_);
  4371. addr_ = nullptr;
  4372. }
  4373. if (fd_ != -1) {
  4374. ::close(fd_);
  4375. fd_ = -1;
  4376. }
  4377. #endif
  4378. size_ = 0;
  4379. }
  4380. inline int close_socket(socket_t sock) {
  4381. #ifdef _WIN32
  4382. return closesocket(sock);
  4383. #else
  4384. return close(sock);
  4385. #endif
  4386. }
  4387. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4388. ssize_t res = 0;
  4389. while (true) {
  4390. res = fn();
  4391. if (res < 0 && errno == EINTR) {
  4392. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4393. continue;
  4394. }
  4395. break;
  4396. }
  4397. return res;
  4398. }
  4399. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4400. return handle_EINTR([&]() {
  4401. return recv(sock,
  4402. #ifdef _WIN32
  4403. static_cast<char *>(ptr), static_cast<int>(size),
  4404. #else
  4405. ptr, size,
  4406. #endif
  4407. flags);
  4408. });
  4409. }
  4410. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4411. int flags) {
  4412. return handle_EINTR([&]() {
  4413. return send(sock,
  4414. #ifdef _WIN32
  4415. static_cast<const char *>(ptr), static_cast<int>(size),
  4416. #else
  4417. ptr, size,
  4418. #endif
  4419. flags);
  4420. });
  4421. }
  4422. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4423. #ifdef _WIN32
  4424. return ::WSAPoll(fds, nfds, timeout);
  4425. #else
  4426. return ::poll(fds, nfds, timeout);
  4427. #endif
  4428. }
  4429. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4430. time_t usec) {
  4431. struct pollfd pfd;
  4432. pfd.fd = sock;
  4433. pfd.events = events;
  4434. pfd.revents = 0;
  4435. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4436. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4437. }
  4438. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4439. return select_impl(sock, POLLIN, sec, usec);
  4440. }
  4441. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4442. return select_impl(sock, POLLOUT, sec, usec);
  4443. }
  4444. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4445. time_t usec) {
  4446. struct pollfd pfd_read;
  4447. pfd_read.fd = sock;
  4448. pfd_read.events = POLLIN | POLLOUT;
  4449. pfd_read.revents = 0;
  4450. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4451. auto poll_res =
  4452. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4453. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4454. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4455. auto error = 0;
  4456. socklen_t len = sizeof(error);
  4457. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4458. reinterpret_cast<char *>(&error), &len);
  4459. auto successful = res >= 0 && !error;
  4460. return successful ? Error::Success : Error::Connection;
  4461. }
  4462. return Error::Connection;
  4463. }
  4464. inline bool is_socket_alive(socket_t sock) {
  4465. const auto val = detail::select_read(sock, 0, 0);
  4466. if (val == 0) {
  4467. return true;
  4468. } else if (val < 0 && errno == EBADF) {
  4469. return false;
  4470. }
  4471. char buf[1];
  4472. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4473. }
  4474. class SocketStream final : public Stream {
  4475. public:
  4476. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4477. time_t write_timeout_sec, time_t write_timeout_usec,
  4478. time_t max_timeout_msec = 0,
  4479. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4480. (std::chrono::steady_clock::time_point::min)());
  4481. ~SocketStream() override;
  4482. bool is_readable() const override;
  4483. bool wait_readable() const override;
  4484. bool wait_writable() const override;
  4485. ssize_t read(char *ptr, size_t size) override;
  4486. ssize_t write(const char *ptr, size_t size) override;
  4487. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4488. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4489. socket_t socket() const override;
  4490. time_t duration() const override;
  4491. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4492. private:
  4493. socket_t sock_;
  4494. time_t read_timeout_sec_;
  4495. time_t read_timeout_usec_;
  4496. time_t write_timeout_sec_;
  4497. time_t write_timeout_usec_;
  4498. time_t max_timeout_msec_;
  4499. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4500. std::vector<char> read_buff_;
  4501. size_t read_buff_off_ = 0;
  4502. size_t read_buff_content_size_ = 0;
  4503. static const size_t read_buff_size_ = 1024l * 4;
  4504. };
  4505. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4506. time_t keep_alive_timeout_sec) {
  4507. using namespace std::chrono;
  4508. const auto interval_usec =
  4509. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4510. // Avoid expensive `steady_clock::now()` call for the first time
  4511. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4512. const auto start = steady_clock::now() - microseconds{interval_usec};
  4513. const auto timeout = seconds{keep_alive_timeout_sec};
  4514. while (true) {
  4515. if (svr_sock == INVALID_SOCKET) {
  4516. break; // Server socket is closed
  4517. }
  4518. auto val = select_read(sock, 0, interval_usec);
  4519. if (val < 0) {
  4520. break; // Ssocket error
  4521. } else if (val == 0) {
  4522. if (steady_clock::now() - start > timeout) {
  4523. break; // Timeout
  4524. }
  4525. } else {
  4526. return true; // Ready for read
  4527. }
  4528. }
  4529. return false;
  4530. }
  4531. template <typename T>
  4532. inline bool
  4533. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4534. size_t keep_alive_max_count,
  4535. time_t keep_alive_timeout_sec, T callback) {
  4536. assert(keep_alive_max_count > 0);
  4537. auto ret = false;
  4538. auto count = keep_alive_max_count;
  4539. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4540. auto close_connection = count == 1;
  4541. auto connection_closed = false;
  4542. ret = callback(close_connection, connection_closed);
  4543. if (!ret || connection_closed) { break; }
  4544. count--;
  4545. }
  4546. return ret;
  4547. }
  4548. template <typename T>
  4549. inline bool
  4550. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4551. size_t keep_alive_max_count,
  4552. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4553. time_t read_timeout_usec, time_t write_timeout_sec,
  4554. time_t write_timeout_usec, T callback) {
  4555. return process_server_socket_core(
  4556. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4557. [&](bool close_connection, bool &connection_closed) {
  4558. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4559. write_timeout_sec, write_timeout_usec);
  4560. return callback(strm, close_connection, connection_closed);
  4561. });
  4562. }
  4563. inline bool process_client_socket(
  4564. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4565. time_t write_timeout_sec, time_t write_timeout_usec,
  4566. time_t max_timeout_msec,
  4567. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4568. std::function<bool(Stream &)> callback) {
  4569. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4570. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4571. start_time);
  4572. return callback(strm);
  4573. }
  4574. inline int shutdown_socket(socket_t sock) {
  4575. #ifdef _WIN32
  4576. return shutdown(sock, SD_BOTH);
  4577. #else
  4578. return shutdown(sock, SHUT_RDWR);
  4579. #endif
  4580. }
  4581. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4582. if (s.size() > 1 && s[0] == '\0') {
  4583. auto ret = s;
  4584. ret[0] = '@';
  4585. return ret;
  4586. }
  4587. return s;
  4588. }
  4589. inline std::string
  4590. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4591. if (s.size() > 1 && s[0] == '@') {
  4592. auto ret = s;
  4593. ret[0] = '\0';
  4594. return ret;
  4595. }
  4596. return s;
  4597. }
  4598. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4599. const struct addrinfo *hints,
  4600. struct addrinfo **res, time_t timeout_sec) {
  4601. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4602. if (timeout_sec <= 0) {
  4603. // No timeout specified, use standard getaddrinfo
  4604. return getaddrinfo(node, service, hints, res);
  4605. }
  4606. #ifdef _WIN32
  4607. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4608. OVERLAPPED overlapped = {0};
  4609. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4610. if (!event) { return EAI_FAIL; }
  4611. overlapped.hEvent = event;
  4612. PADDRINFOEXW result_addrinfo = nullptr;
  4613. HANDLE cancel_handle = nullptr;
  4614. ADDRINFOEXW hints_ex = {0};
  4615. if (hints) {
  4616. hints_ex.ai_flags = hints->ai_flags;
  4617. hints_ex.ai_family = hints->ai_family;
  4618. hints_ex.ai_socktype = hints->ai_socktype;
  4619. hints_ex.ai_protocol = hints->ai_protocol;
  4620. }
  4621. auto wnode = u8string_to_wstring(node);
  4622. auto wservice = u8string_to_wstring(service);
  4623. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4624. hints ? &hints_ex : nullptr, &result_addrinfo,
  4625. nullptr, &overlapped, nullptr, &cancel_handle);
  4626. if (ret == WSA_IO_PENDING) {
  4627. auto wait_result =
  4628. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4629. if (wait_result == WAIT_TIMEOUT) {
  4630. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4631. ::CloseHandle(event);
  4632. return EAI_AGAIN;
  4633. }
  4634. DWORD bytes_returned;
  4635. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4636. &bytes_returned, FALSE)) {
  4637. ::CloseHandle(event);
  4638. return ::WSAGetLastError();
  4639. }
  4640. }
  4641. ::CloseHandle(event);
  4642. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4643. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4644. return 0;
  4645. }
  4646. return ret;
  4647. #elif TARGET_OS_MAC
  4648. if (!node) { return EAI_NONAME; }
  4649. // macOS implementation using CFHost API for asynchronous DNS resolution
  4650. CFStringRef hostname_ref = CFStringCreateWithCString(
  4651. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4652. if (!hostname_ref) { return EAI_MEMORY; }
  4653. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4654. CFRelease(hostname_ref);
  4655. if (!host_ref) { return EAI_MEMORY; }
  4656. // Set up context for callback
  4657. struct CFHostContext {
  4658. bool completed = false;
  4659. bool success = false;
  4660. CFArrayRef addresses = nullptr;
  4661. std::mutex mutex;
  4662. std::condition_variable cv;
  4663. } context;
  4664. CFHostClientContext client_context;
  4665. memset(&client_context, 0, sizeof(client_context));
  4666. client_context.info = &context;
  4667. // Set callback
  4668. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4669. const CFStreamError *error, void *info) {
  4670. auto ctx = static_cast<CFHostContext *>(info);
  4671. std::lock_guard<std::mutex> lock(ctx->mutex);
  4672. if (error && error->error != 0) {
  4673. ctx->success = false;
  4674. } else {
  4675. Boolean hasBeenResolved;
  4676. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4677. if (ctx->addresses && hasBeenResolved) {
  4678. CFRetain(ctx->addresses);
  4679. ctx->success = true;
  4680. } else {
  4681. ctx->success = false;
  4682. }
  4683. }
  4684. ctx->completed = true;
  4685. ctx->cv.notify_one();
  4686. };
  4687. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4688. CFRelease(host_ref);
  4689. return EAI_SYSTEM;
  4690. }
  4691. // Schedule on run loop
  4692. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4693. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4694. // Start resolution
  4695. CFStreamError stream_error;
  4696. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4697. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4698. CFRelease(host_ref);
  4699. return EAI_FAIL;
  4700. }
  4701. // Wait for completion with timeout
  4702. auto timeout_time =
  4703. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4704. bool timed_out = false;
  4705. {
  4706. std::unique_lock<std::mutex> lock(context.mutex);
  4707. while (!context.completed) {
  4708. auto now = std::chrono::steady_clock::now();
  4709. if (now >= timeout_time) {
  4710. timed_out = true;
  4711. break;
  4712. }
  4713. // Run the runloop for a short time
  4714. lock.unlock();
  4715. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4716. lock.lock();
  4717. }
  4718. }
  4719. // Clean up
  4720. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4721. CFHostSetClient(host_ref, nullptr, nullptr);
  4722. if (timed_out || !context.completed) {
  4723. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4724. CFRelease(host_ref);
  4725. return EAI_AGAIN;
  4726. }
  4727. if (!context.success || !context.addresses) {
  4728. CFRelease(host_ref);
  4729. return EAI_NODATA;
  4730. }
  4731. // Convert CFArray to addrinfo
  4732. CFIndex count = CFArrayGetCount(context.addresses);
  4733. if (count == 0) {
  4734. CFRelease(context.addresses);
  4735. CFRelease(host_ref);
  4736. return EAI_NODATA;
  4737. }
  4738. struct addrinfo *result_addrinfo = nullptr;
  4739. struct addrinfo **current = &result_addrinfo;
  4740. for (CFIndex i = 0; i < count; i++) {
  4741. CFDataRef addr_data =
  4742. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4743. if (!addr_data) continue;
  4744. const struct sockaddr *sockaddr_ptr =
  4745. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4746. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4747. // Allocate addrinfo structure
  4748. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4749. if (!*current) {
  4750. freeaddrinfo(result_addrinfo);
  4751. CFRelease(context.addresses);
  4752. CFRelease(host_ref);
  4753. return EAI_MEMORY;
  4754. }
  4755. memset(*current, 0, sizeof(struct addrinfo));
  4756. // Set up addrinfo fields
  4757. (*current)->ai_family = sockaddr_ptr->sa_family;
  4758. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4759. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4760. (*current)->ai_addrlen = sockaddr_len;
  4761. // Copy sockaddr
  4762. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4763. if (!(*current)->ai_addr) {
  4764. freeaddrinfo(result_addrinfo);
  4765. CFRelease(context.addresses);
  4766. CFRelease(host_ref);
  4767. return EAI_MEMORY;
  4768. }
  4769. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4770. // Set port if service is specified
  4771. if (service && strlen(service) > 0) {
  4772. int port = atoi(service);
  4773. if (port > 0) {
  4774. if (sockaddr_ptr->sa_family == AF_INET) {
  4775. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4776. ->sin_port = htons(static_cast<uint16_t>(port));
  4777. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4778. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4779. ->sin6_port = htons(static_cast<uint16_t>(port));
  4780. }
  4781. }
  4782. }
  4783. current = &((*current)->ai_next);
  4784. }
  4785. CFRelease(context.addresses);
  4786. CFRelease(host_ref);
  4787. *res = result_addrinfo;
  4788. return 0;
  4789. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  4790. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  4791. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  4792. struct gaicb request;
  4793. struct gaicb *requests[1] = {&request};
  4794. struct sigevent sevp;
  4795. struct timespec timeout;
  4796. // Initialize the request structure
  4797. memset(&request, 0, sizeof(request));
  4798. request.ar_name = node;
  4799. request.ar_service = service;
  4800. request.ar_request = hints;
  4801. // Set up timeout
  4802. timeout.tv_sec = timeout_sec;
  4803. timeout.tv_nsec = 0;
  4804. // Initialize sigevent structure (not used, but required)
  4805. memset(&sevp, 0, sizeof(sevp));
  4806. sevp.sigev_notify = SIGEV_NONE;
  4807. // Start asynchronous resolution
  4808. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  4809. if (start_result != 0) { return start_result; }
  4810. // Wait for completion with timeout
  4811. int wait_result =
  4812. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  4813. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  4814. // Completed successfully, get the result
  4815. int gai_result = gai_error(&request);
  4816. if (gai_result == 0) {
  4817. *res = request.ar_result;
  4818. return 0;
  4819. } else {
  4820. // Clean up on error
  4821. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  4822. return gai_result;
  4823. }
  4824. } else if (wait_result == EAI_AGAIN) {
  4825. // Timeout occurred, cancel the request
  4826. gai_cancel(&request);
  4827. return EAI_AGAIN;
  4828. } else {
  4829. // Other error occurred
  4830. gai_cancel(&request);
  4831. return wait_result;
  4832. }
  4833. #else
  4834. // Fallback implementation using thread-based timeout for other Unix systems
  4835. struct GetAddrInfoState {
  4836. ~GetAddrInfoState() {
  4837. if (info) { freeaddrinfo(info); }
  4838. }
  4839. std::mutex mutex;
  4840. std::condition_variable result_cv;
  4841. bool completed = false;
  4842. int result = EAI_SYSTEM;
  4843. std::string node;
  4844. std::string service;
  4845. struct addrinfo hints;
  4846. struct addrinfo *info = nullptr;
  4847. };
  4848. // Allocate on the heap, so the resolver thread can keep using the data.
  4849. auto state = std::make_shared<GetAddrInfoState>();
  4850. if (node) { state->node = node; }
  4851. state->service = service;
  4852. state->hints = *hints;
  4853. std::thread resolve_thread([state]() {
  4854. auto thread_result =
  4855. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4856. &state->info);
  4857. std::lock_guard<std::mutex> lock(state->mutex);
  4858. state->result = thread_result;
  4859. state->completed = true;
  4860. state->result_cv.notify_one();
  4861. });
  4862. // Wait for completion or timeout
  4863. std::unique_lock<std::mutex> lock(state->mutex);
  4864. auto finished =
  4865. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4866. [&] { return state->completed; });
  4867. if (finished) {
  4868. // Operation completed within timeout
  4869. resolve_thread.join();
  4870. *res = state->info;
  4871. state->info = nullptr; // Pass ownership to caller
  4872. return state->result;
  4873. } else {
  4874. // Timeout occurred
  4875. resolve_thread.detach(); // Let the thread finish in background
  4876. return EAI_AGAIN; // Return timeout error
  4877. }
  4878. #endif
  4879. #else
  4880. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4881. return getaddrinfo(node, service, hints, res);
  4882. #endif
  4883. }
  4884. template <typename BindOrConnect>
  4885. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4886. int address_family, int socket_flags, bool tcp_nodelay,
  4887. bool ipv6_v6only, SocketOptions socket_options,
  4888. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4889. // Get address info
  4890. const char *node = nullptr;
  4891. struct addrinfo hints;
  4892. struct addrinfo *result;
  4893. memset(&hints, 0, sizeof(struct addrinfo));
  4894. hints.ai_socktype = SOCK_STREAM;
  4895. hints.ai_protocol = IPPROTO_IP;
  4896. if (!ip.empty()) {
  4897. node = ip.c_str();
  4898. // Ask getaddrinfo to convert IP in c-string to address
  4899. hints.ai_family = AF_UNSPEC;
  4900. hints.ai_flags = AI_NUMERICHOST;
  4901. } else {
  4902. if (!host.empty()) { node = host.c_str(); }
  4903. hints.ai_family = address_family;
  4904. hints.ai_flags = socket_flags;
  4905. }
  4906. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  4907. if (hints.ai_family == AF_UNIX) {
  4908. const auto addrlen = host.length();
  4909. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  4910. #ifdef SOCK_CLOEXEC
  4911. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  4912. hints.ai_protocol);
  4913. #else
  4914. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4915. #endif
  4916. if (sock != INVALID_SOCKET) {
  4917. sockaddr_un addr{};
  4918. addr.sun_family = AF_UNIX;
  4919. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  4920. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  4921. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  4922. hints.ai_addrlen = static_cast<socklen_t>(
  4923. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  4924. #ifndef SOCK_CLOEXEC
  4925. #ifndef _WIN32
  4926. fcntl(sock, F_SETFD, FD_CLOEXEC);
  4927. #endif
  4928. #endif
  4929. if (socket_options) { socket_options(sock); }
  4930. #ifdef _WIN32
  4931. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  4932. // remove the option.
  4933. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  4934. #endif
  4935. bool dummy;
  4936. if (!bind_or_connect(sock, hints, dummy)) {
  4937. close_socket(sock);
  4938. sock = INVALID_SOCKET;
  4939. }
  4940. }
  4941. return sock;
  4942. }
  4943. #endif
  4944. auto service = std::to_string(port);
  4945. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  4946. timeout_sec)) {
  4947. #if defined __linux__ && !defined __ANDROID__
  4948. res_init();
  4949. #endif
  4950. return INVALID_SOCKET;
  4951. }
  4952. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4953. for (auto rp = result; rp; rp = rp->ai_next) {
  4954. // Create a socket
  4955. #ifdef _WIN32
  4956. auto sock =
  4957. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  4958. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  4959. /**
  4960. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  4961. * and above the socket creation fails on older Windows Systems.
  4962. *
  4963. * Let's try to create a socket the old way in this case.
  4964. *
  4965. * Reference:
  4966. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  4967. *
  4968. * WSA_FLAG_NO_HANDLE_INHERIT:
  4969. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  4970. * SP1, and later
  4971. *
  4972. */
  4973. if (sock == INVALID_SOCKET) {
  4974. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4975. }
  4976. #else
  4977. #ifdef SOCK_CLOEXEC
  4978. auto sock =
  4979. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  4980. #else
  4981. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4982. #endif
  4983. #endif
  4984. if (sock == INVALID_SOCKET) { continue; }
  4985. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  4986. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  4987. close_socket(sock);
  4988. continue;
  4989. }
  4990. #endif
  4991. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  4992. if (rp->ai_family == AF_INET6) {
  4993. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  4994. }
  4995. if (socket_options) { socket_options(sock); }
  4996. // bind or connect
  4997. auto quit = false;
  4998. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  4999. close_socket(sock);
  5000. if (quit) { break; }
  5001. }
  5002. return INVALID_SOCKET;
  5003. }
  5004. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5005. #ifdef _WIN32
  5006. auto flags = nonblocking ? 1UL : 0UL;
  5007. ioctlsocket(sock, FIONBIO, &flags);
  5008. #else
  5009. auto flags = fcntl(sock, F_GETFL, 0);
  5010. fcntl(sock, F_SETFL,
  5011. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5012. #endif
  5013. }
  5014. inline bool is_connection_error() {
  5015. #ifdef _WIN32
  5016. return WSAGetLastError() != WSAEWOULDBLOCK;
  5017. #else
  5018. return errno != EINPROGRESS;
  5019. #endif
  5020. }
  5021. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5022. struct addrinfo hints;
  5023. struct addrinfo *result;
  5024. memset(&hints, 0, sizeof(struct addrinfo));
  5025. hints.ai_family = AF_UNSPEC;
  5026. hints.ai_socktype = SOCK_STREAM;
  5027. hints.ai_protocol = 0;
  5028. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5029. return false;
  5030. }
  5031. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5032. auto ret = false;
  5033. for (auto rp = result; rp; rp = rp->ai_next) {
  5034. const auto &ai = *rp;
  5035. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5036. ret = true;
  5037. break;
  5038. }
  5039. }
  5040. return ret;
  5041. }
  5042. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5043. #define USE_IF2IP
  5044. #endif
  5045. #ifdef USE_IF2IP
  5046. inline std::string if2ip(int address_family, const std::string &ifn) {
  5047. struct ifaddrs *ifap;
  5048. getifaddrs(&ifap);
  5049. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5050. std::string addr_candidate;
  5051. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5052. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5053. (AF_UNSPEC == address_family ||
  5054. ifa->ifa_addr->sa_family == address_family)) {
  5055. if (ifa->ifa_addr->sa_family == AF_INET) {
  5056. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5057. char buf[INET_ADDRSTRLEN];
  5058. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5059. return std::string(buf, INET_ADDRSTRLEN);
  5060. }
  5061. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5062. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5063. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5064. char buf[INET6_ADDRSTRLEN] = {};
  5065. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5066. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5067. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5068. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5069. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5070. } else {
  5071. return std::string(buf, INET6_ADDRSTRLEN);
  5072. }
  5073. }
  5074. }
  5075. }
  5076. }
  5077. }
  5078. return addr_candidate;
  5079. }
  5080. #endif
  5081. inline socket_t create_client_socket(
  5082. const std::string &host, const std::string &ip, int port,
  5083. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5084. SocketOptions socket_options, time_t connection_timeout_sec,
  5085. time_t connection_timeout_usec, time_t read_timeout_sec,
  5086. time_t read_timeout_usec, time_t write_timeout_sec,
  5087. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5088. auto sock = create_socket(
  5089. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5090. std::move(socket_options),
  5091. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5092. if (!intf.empty()) {
  5093. #ifdef USE_IF2IP
  5094. auto ip_from_if = if2ip(address_family, intf);
  5095. if (ip_from_if.empty()) { ip_from_if = intf; }
  5096. if (!bind_ip_address(sock2, ip_from_if)) {
  5097. error = Error::BindIPAddress;
  5098. return false;
  5099. }
  5100. #endif
  5101. }
  5102. set_nonblocking(sock2, true);
  5103. auto ret =
  5104. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5105. if (ret < 0) {
  5106. if (is_connection_error()) {
  5107. error = Error::Connection;
  5108. return false;
  5109. }
  5110. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5111. connection_timeout_usec);
  5112. if (error != Error::Success) {
  5113. if (error == Error::ConnectionTimeout) { quit = true; }
  5114. return false;
  5115. }
  5116. }
  5117. set_nonblocking(sock2, false);
  5118. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5119. read_timeout_usec);
  5120. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5121. write_timeout_usec);
  5122. error = Error::Success;
  5123. return true;
  5124. },
  5125. connection_timeout_sec); // Pass DNS timeout
  5126. if (sock != INVALID_SOCKET) {
  5127. error = Error::Success;
  5128. } else {
  5129. if (error == Error::Success) { error = Error::Connection; }
  5130. }
  5131. return sock;
  5132. }
  5133. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5134. socklen_t addr_len, std::string &ip, int &port) {
  5135. if (addr.ss_family == AF_INET) {
  5136. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5137. } else if (addr.ss_family == AF_INET6) {
  5138. port =
  5139. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5140. } else {
  5141. return false;
  5142. }
  5143. std::array<char, NI_MAXHOST> ipstr{};
  5144. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5145. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5146. 0, NI_NUMERICHOST)) {
  5147. return false;
  5148. }
  5149. ip = ipstr.data();
  5150. return true;
  5151. }
  5152. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5153. struct sockaddr_storage addr;
  5154. socklen_t addr_len = sizeof(addr);
  5155. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5156. &addr_len)) {
  5157. get_ip_and_port(addr, addr_len, ip, port);
  5158. }
  5159. }
  5160. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5161. struct sockaddr_storage addr;
  5162. socklen_t addr_len = sizeof(addr);
  5163. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5164. &addr_len)) {
  5165. #ifndef _WIN32
  5166. if (addr.ss_family == AF_UNIX) {
  5167. #if defined(__linux__)
  5168. struct ucred ucred;
  5169. socklen_t len = sizeof(ucred);
  5170. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5171. port = ucred.pid;
  5172. }
  5173. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5174. pid_t pid;
  5175. socklen_t len = sizeof(pid);
  5176. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5177. port = pid;
  5178. }
  5179. #endif
  5180. return;
  5181. }
  5182. #endif
  5183. get_ip_and_port(addr, addr_len, ip, port);
  5184. }
  5185. }
  5186. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5187. unsigned int h) {
  5188. return (l == 0)
  5189. ? h
  5190. : str2tag_core(
  5191. s + 1, l - 1,
  5192. // Unsets the 6 high bits of h, therefore no overflow happens
  5193. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5194. h * 33) ^
  5195. static_cast<unsigned char>(*s));
  5196. }
  5197. inline unsigned int str2tag(const std::string &s) {
  5198. return str2tag_core(s.data(), s.size(), 0);
  5199. }
  5200. namespace udl {
  5201. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5202. return str2tag_core(s, l, 0);
  5203. }
  5204. } // namespace udl
  5205. inline std::string
  5206. find_content_type(const std::string &path,
  5207. const std::map<std::string, std::string> &user_data,
  5208. const std::string &default_content_type) {
  5209. auto ext = file_extension(path);
  5210. auto it = user_data.find(ext);
  5211. if (it != user_data.end()) { return it->second; }
  5212. using udl::operator""_t;
  5213. switch (str2tag(ext)) {
  5214. default: return default_content_type;
  5215. case "css"_t: return "text/css";
  5216. case "csv"_t: return "text/csv";
  5217. case "htm"_t:
  5218. case "html"_t: return "text/html";
  5219. case "js"_t:
  5220. case "mjs"_t: return "text/javascript";
  5221. case "txt"_t: return "text/plain";
  5222. case "vtt"_t: return "text/vtt";
  5223. case "apng"_t: return "image/apng";
  5224. case "avif"_t: return "image/avif";
  5225. case "bmp"_t: return "image/bmp";
  5226. case "gif"_t: return "image/gif";
  5227. case "png"_t: return "image/png";
  5228. case "svg"_t: return "image/svg+xml";
  5229. case "webp"_t: return "image/webp";
  5230. case "ico"_t: return "image/x-icon";
  5231. case "tif"_t: return "image/tiff";
  5232. case "tiff"_t: return "image/tiff";
  5233. case "jpg"_t:
  5234. case "jpeg"_t: return "image/jpeg";
  5235. case "mp4"_t: return "video/mp4";
  5236. case "mpeg"_t: return "video/mpeg";
  5237. case "webm"_t: return "video/webm";
  5238. case "mp3"_t: return "audio/mp3";
  5239. case "mpga"_t: return "audio/mpeg";
  5240. case "weba"_t: return "audio/webm";
  5241. case "wav"_t: return "audio/wave";
  5242. case "otf"_t: return "font/otf";
  5243. case "ttf"_t: return "font/ttf";
  5244. case "woff"_t: return "font/woff";
  5245. case "woff2"_t: return "font/woff2";
  5246. case "7z"_t: return "application/x-7z-compressed";
  5247. case "atom"_t: return "application/atom+xml";
  5248. case "pdf"_t: return "application/pdf";
  5249. case "json"_t: return "application/json";
  5250. case "rss"_t: return "application/rss+xml";
  5251. case "tar"_t: return "application/x-tar";
  5252. case "xht"_t:
  5253. case "xhtml"_t: return "application/xhtml+xml";
  5254. case "xslt"_t: return "application/xslt+xml";
  5255. case "xml"_t: return "application/xml";
  5256. case "gz"_t: return "application/gzip";
  5257. case "zip"_t: return "application/zip";
  5258. case "wasm"_t: return "application/wasm";
  5259. }
  5260. }
  5261. inline bool can_compress_content_type(const std::string &content_type) {
  5262. using udl::operator""_t;
  5263. auto tag = str2tag(content_type);
  5264. switch (tag) {
  5265. case "image/svg+xml"_t:
  5266. case "application/javascript"_t:
  5267. case "application/json"_t:
  5268. case "application/xml"_t:
  5269. case "application/protobuf"_t:
  5270. case "application/xhtml+xml"_t: return true;
  5271. case "text/event-stream"_t: return false;
  5272. default: return !content_type.rfind("text/", 0);
  5273. }
  5274. }
  5275. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5276. auto ret =
  5277. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  5278. if (!ret) { return EncodingType::None; }
  5279. const auto &s = req.get_header_value("Accept-Encoding");
  5280. (void)(s);
  5281. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5282. // TODO: 'Accept-Encoding' has br, not br;q=0
  5283. ret = s.find("br") != std::string::npos;
  5284. if (ret) { return EncodingType::Brotli; }
  5285. #endif
  5286. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5287. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  5288. ret = s.find("gzip") != std::string::npos;
  5289. if (ret) { return EncodingType::Gzip; }
  5290. #endif
  5291. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5292. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  5293. ret = s.find("zstd") != std::string::npos;
  5294. if (ret) { return EncodingType::Zstd; }
  5295. #endif
  5296. return EncodingType::None;
  5297. }
  5298. inline bool nocompressor::compress(const char *data, size_t data_length,
  5299. bool /*last*/, Callback callback) {
  5300. if (!data_length) { return true; }
  5301. return callback(data, data_length);
  5302. }
  5303. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5304. inline gzip_compressor::gzip_compressor() {
  5305. std::memset(&strm_, 0, sizeof(strm_));
  5306. strm_.zalloc = Z_NULL;
  5307. strm_.zfree = Z_NULL;
  5308. strm_.opaque = Z_NULL;
  5309. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5310. Z_DEFAULT_STRATEGY) == Z_OK;
  5311. }
  5312. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5313. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5314. bool last, Callback callback) {
  5315. assert(is_valid_);
  5316. do {
  5317. constexpr size_t max_avail_in =
  5318. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5319. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5320. (std::min)(data_length, max_avail_in));
  5321. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5322. data_length -= strm_.avail_in;
  5323. data += strm_.avail_in;
  5324. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5325. auto ret = Z_OK;
  5326. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5327. do {
  5328. strm_.avail_out = static_cast<uInt>(buff.size());
  5329. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5330. ret = deflate(&strm_, flush);
  5331. if (ret == Z_STREAM_ERROR) { return false; }
  5332. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5333. return false;
  5334. }
  5335. } while (strm_.avail_out == 0);
  5336. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5337. (flush == Z_NO_FLUSH && ret == Z_OK));
  5338. assert(strm_.avail_in == 0);
  5339. } while (data_length > 0);
  5340. return true;
  5341. }
  5342. inline gzip_decompressor::gzip_decompressor() {
  5343. std::memset(&strm_, 0, sizeof(strm_));
  5344. strm_.zalloc = Z_NULL;
  5345. strm_.zfree = Z_NULL;
  5346. strm_.opaque = Z_NULL;
  5347. // 15 is the value of wbits, which should be at the maximum possible value
  5348. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5349. // that the stream type should be automatically detected either gzip or
  5350. // deflate.
  5351. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5352. }
  5353. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5354. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5355. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5356. Callback callback) {
  5357. assert(is_valid_);
  5358. auto ret = Z_OK;
  5359. do {
  5360. constexpr size_t max_avail_in =
  5361. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5362. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5363. (std::min)(data_length, max_avail_in));
  5364. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5365. data_length -= strm_.avail_in;
  5366. data += strm_.avail_in;
  5367. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5368. while (strm_.avail_in > 0 && ret == Z_OK) {
  5369. strm_.avail_out = static_cast<uInt>(buff.size());
  5370. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5371. ret = inflate(&strm_, Z_NO_FLUSH);
  5372. assert(ret != Z_STREAM_ERROR);
  5373. switch (ret) {
  5374. case Z_NEED_DICT:
  5375. case Z_DATA_ERROR:
  5376. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5377. }
  5378. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5379. return false;
  5380. }
  5381. }
  5382. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5383. } while (data_length > 0);
  5384. return true;
  5385. }
  5386. #endif
  5387. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5388. inline brotli_compressor::brotli_compressor() {
  5389. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5390. }
  5391. inline brotli_compressor::~brotli_compressor() {
  5392. BrotliEncoderDestroyInstance(state_);
  5393. }
  5394. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5395. bool last, Callback callback) {
  5396. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5397. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5398. auto available_in = data_length;
  5399. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5400. for (;;) {
  5401. if (last) {
  5402. if (BrotliEncoderIsFinished(state_)) { break; }
  5403. } else {
  5404. if (!available_in) { break; }
  5405. }
  5406. auto available_out = buff.size();
  5407. auto next_out = buff.data();
  5408. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5409. &available_out, &next_out, nullptr)) {
  5410. return false;
  5411. }
  5412. auto output_bytes = buff.size() - available_out;
  5413. if (output_bytes) {
  5414. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5415. }
  5416. }
  5417. return true;
  5418. }
  5419. inline brotli_decompressor::brotli_decompressor() {
  5420. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5421. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5422. : BROTLI_DECODER_RESULT_ERROR;
  5423. }
  5424. inline brotli_decompressor::~brotli_decompressor() {
  5425. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5426. }
  5427. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5428. inline bool brotli_decompressor::decompress(const char *data,
  5429. size_t data_length,
  5430. Callback callback) {
  5431. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5432. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5433. return 0;
  5434. }
  5435. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5436. size_t avail_in = data_length;
  5437. size_t total_out;
  5438. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5439. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5440. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5441. char *next_out = buff.data();
  5442. size_t avail_out = buff.size();
  5443. decoder_r = BrotliDecoderDecompressStream(
  5444. decoder_s, &avail_in, &next_in, &avail_out,
  5445. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5446. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5447. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5448. }
  5449. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5450. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5451. }
  5452. #endif
  5453. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5454. inline zstd_compressor::zstd_compressor() {
  5455. ctx_ = ZSTD_createCCtx();
  5456. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5457. }
  5458. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5459. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5460. bool last, Callback callback) {
  5461. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5462. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5463. ZSTD_inBuffer input = {data, data_length, 0};
  5464. bool finished;
  5465. do {
  5466. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5467. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5468. if (ZSTD_isError(remaining)) { return false; }
  5469. if (!callback(buff.data(), output.pos)) { return false; }
  5470. finished = last ? (remaining == 0) : (input.pos == input.size);
  5471. } while (!finished);
  5472. return true;
  5473. }
  5474. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5475. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5476. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5477. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5478. Callback callback) {
  5479. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5480. ZSTD_inBuffer input = {data, data_length, 0};
  5481. while (input.pos < input.size) {
  5482. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5483. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5484. if (ZSTD_isError(remaining)) { return false; }
  5485. if (!callback(buff.data(), output.pos)) { return false; }
  5486. }
  5487. return true;
  5488. }
  5489. #endif
  5490. inline std::unique_ptr<decompressor>
  5491. create_decompressor(const std::string &encoding) {
  5492. std::unique_ptr<decompressor> decompressor;
  5493. if (encoding == "gzip" || encoding == "deflate") {
  5494. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5495. decompressor = detail::make_unique<gzip_decompressor>();
  5496. #endif
  5497. } else if (encoding.find("br") != std::string::npos) {
  5498. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5499. decompressor = detail::make_unique<brotli_decompressor>();
  5500. #endif
  5501. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5502. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5503. decompressor = detail::make_unique<zstd_decompressor>();
  5504. #endif
  5505. }
  5506. return decompressor;
  5507. }
  5508. inline bool is_prohibited_header_name(const std::string &name) {
  5509. using udl::operator""_t;
  5510. switch (str2tag(name)) {
  5511. case "REMOTE_ADDR"_t:
  5512. case "REMOTE_PORT"_t:
  5513. case "LOCAL_ADDR"_t:
  5514. case "LOCAL_PORT"_t: return true;
  5515. default: return false;
  5516. }
  5517. }
  5518. inline bool has_header(const Headers &headers, const std::string &key) {
  5519. if (is_prohibited_header_name(key)) { return false; }
  5520. return headers.find(key) != headers.end();
  5521. }
  5522. inline const char *get_header_value(const Headers &headers,
  5523. const std::string &key, const char *def,
  5524. size_t id) {
  5525. if (is_prohibited_header_name(key)) {
  5526. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5527. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5528. throw std::invalid_argument(msg);
  5529. #else
  5530. return "";
  5531. #endif
  5532. }
  5533. auto rng = headers.equal_range(key);
  5534. auto it = rng.first;
  5535. std::advance(it, static_cast<ssize_t>(id));
  5536. if (it != rng.second) { return it->second.c_str(); }
  5537. return def;
  5538. }
  5539. inline bool read_headers(Stream &strm, Headers &headers) {
  5540. const auto bufsiz = 2048;
  5541. char buf[bufsiz];
  5542. stream_line_reader line_reader(strm, buf, bufsiz);
  5543. size_t header_count = 0;
  5544. for (;;) {
  5545. if (!line_reader.getline()) { return false; }
  5546. // Check if the line ends with CRLF.
  5547. auto line_terminator_len = 2;
  5548. if (line_reader.end_with_crlf()) {
  5549. // Blank line indicates end of headers.
  5550. if (line_reader.size() == 2) { break; }
  5551. } else {
  5552. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5553. // Blank line indicates end of headers.
  5554. if (line_reader.size() == 1) { break; }
  5555. line_terminator_len = 1;
  5556. #else
  5557. continue; // Skip invalid line.
  5558. #endif
  5559. }
  5560. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5561. // Check header count limit
  5562. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5563. // Exclude line terminator
  5564. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5565. if (!parse_header(line_reader.ptr(), end,
  5566. [&](const std::string &key, const std::string &val) {
  5567. headers.emplace(key, val);
  5568. })) {
  5569. return false;
  5570. }
  5571. header_count++;
  5572. }
  5573. return true;
  5574. }
  5575. inline bool read_websocket_upgrade_response(Stream &strm,
  5576. const std::string &expected_accept,
  5577. std::string &selected_subprotocol) {
  5578. // Read status line
  5579. const auto bufsiz = 2048;
  5580. char buf[bufsiz];
  5581. stream_line_reader line_reader(strm, buf, bufsiz);
  5582. if (!line_reader.getline()) { return false; }
  5583. // Check for "HTTP/1.1 101"
  5584. auto line = std::string(line_reader.ptr(), line_reader.size());
  5585. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  5586. // Parse headers using existing read_headers
  5587. Headers headers;
  5588. if (!read_headers(strm, headers)) { return false; }
  5589. // Verify Upgrade: websocket (case-insensitive)
  5590. auto upgrade_it = headers.find("Upgrade");
  5591. if (upgrade_it == headers.end()) { return false; }
  5592. auto upgrade_val = upgrade_it->second;
  5593. std::transform(upgrade_val.begin(), upgrade_val.end(), upgrade_val.begin(),
  5594. ::tolower);
  5595. if (upgrade_val != "websocket") { return false; }
  5596. // Verify Connection header contains "Upgrade" (case-insensitive)
  5597. auto connection_it = headers.find("Connection");
  5598. if (connection_it == headers.end()) { return false; }
  5599. auto connection_val = connection_it->second;
  5600. std::transform(connection_val.begin(), connection_val.end(),
  5601. connection_val.begin(), ::tolower);
  5602. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  5603. // Verify Sec-WebSocket-Accept header value
  5604. auto it = headers.find("Sec-WebSocket-Accept");
  5605. if (it == headers.end() || it->second != expected_accept) { return false; }
  5606. // Extract negotiated subprotocol
  5607. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  5608. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  5609. return true;
  5610. }
  5611. enum class ReadContentResult {
  5612. Success, // Successfully read the content
  5613. PayloadTooLarge, // The content exceeds the specified payload limit
  5614. Error // An error occurred while reading the content
  5615. };
  5616. inline ReadContentResult read_content_with_length(
  5617. Stream &strm, size_t len, DownloadProgress progress,
  5618. ContentReceiverWithProgress out,
  5619. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  5620. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5621. detail::BodyReader br;
  5622. br.stream = &strm;
  5623. br.has_content_length = true;
  5624. br.content_length = len;
  5625. br.payload_max_length = payload_max_length;
  5626. br.chunked = false;
  5627. br.bytes_read = 0;
  5628. br.last_error = Error::Success;
  5629. size_t r = 0;
  5630. while (r < len) {
  5631. auto read_len = static_cast<size_t>(len - r);
  5632. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  5633. auto n = detail::read_body_content(&strm, br, buf, to_read);
  5634. if (n <= 0) {
  5635. // Check if it was a payload size error
  5636. if (br.last_error == Error::ExceedMaxPayloadSize) {
  5637. return ReadContentResult::PayloadTooLarge;
  5638. }
  5639. return ReadContentResult::Error;
  5640. }
  5641. if (!out(buf, static_cast<size_t>(n), r, len)) {
  5642. return ReadContentResult::Error;
  5643. }
  5644. r += static_cast<size_t>(n);
  5645. if (progress) {
  5646. if (!progress(r, len)) { return ReadContentResult::Error; }
  5647. }
  5648. }
  5649. return ReadContentResult::Success;
  5650. }
  5651. inline ReadContentResult
  5652. read_content_without_length(Stream &strm, size_t payload_max_length,
  5653. ContentReceiverWithProgress out) {
  5654. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5655. size_t r = 0;
  5656. for (;;) {
  5657. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  5658. if (n == 0) { return ReadContentResult::Success; }
  5659. if (n < 0) { return ReadContentResult::Error; }
  5660. // Check if adding this data would exceed the payload limit
  5661. if (r > payload_max_length ||
  5662. payload_max_length - r < static_cast<size_t>(n)) {
  5663. return ReadContentResult::PayloadTooLarge;
  5664. }
  5665. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  5666. return ReadContentResult::Error;
  5667. }
  5668. r += static_cast<size_t>(n);
  5669. }
  5670. return ReadContentResult::Success;
  5671. }
  5672. template <typename T>
  5673. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  5674. size_t payload_max_length,
  5675. ContentReceiverWithProgress out) {
  5676. detail::ChunkedDecoder dec(strm);
  5677. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5678. size_t total_len = 0;
  5679. for (;;) {
  5680. size_t chunk_offset = 0;
  5681. size_t chunk_total = 0;
  5682. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  5683. if (n < 0) { return ReadContentResult::Error; }
  5684. if (n == 0) {
  5685. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  5686. return ReadContentResult::Error;
  5687. }
  5688. return ReadContentResult::Success;
  5689. }
  5690. if (total_len > payload_max_length ||
  5691. payload_max_length - total_len < static_cast<size_t>(n)) {
  5692. return ReadContentResult::PayloadTooLarge;
  5693. }
  5694. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  5695. return ReadContentResult::Error;
  5696. }
  5697. total_len += static_cast<size_t>(n);
  5698. }
  5699. }
  5700. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  5701. return case_ignore::equal(
  5702. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  5703. }
  5704. template <typename T, typename U>
  5705. bool prepare_content_receiver(T &x, int &status,
  5706. ContentReceiverWithProgress receiver,
  5707. bool decompress, U callback) {
  5708. if (decompress) {
  5709. std::string encoding = x.get_header_value("Content-Encoding");
  5710. std::unique_ptr<decompressor> decompressor;
  5711. if (!encoding.empty()) {
  5712. decompressor = detail::create_decompressor(encoding);
  5713. if (!decompressor) {
  5714. // Unsupported encoding or no support compiled in
  5715. status = StatusCode::UnsupportedMediaType_415;
  5716. return false;
  5717. }
  5718. }
  5719. if (decompressor) {
  5720. if (decompressor->is_valid()) {
  5721. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  5722. size_t off, size_t len) {
  5723. return decompressor->decompress(buf, n,
  5724. [&](const char *buf2, size_t n2) {
  5725. return receiver(buf2, n2, off, len);
  5726. });
  5727. };
  5728. return callback(std::move(out));
  5729. } else {
  5730. status = StatusCode::InternalServerError_500;
  5731. return false;
  5732. }
  5733. }
  5734. }
  5735. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  5736. size_t len) {
  5737. return receiver(buf, n, off, len);
  5738. };
  5739. return callback(std::move(out));
  5740. }
  5741. template <typename T>
  5742. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  5743. DownloadProgress progress,
  5744. ContentReceiverWithProgress receiver, bool decompress) {
  5745. return prepare_content_receiver(
  5746. x, status, std::move(receiver), decompress,
  5747. [&](const ContentReceiverWithProgress &out) {
  5748. auto ret = true;
  5749. auto exceed_payload_max_length = false;
  5750. if (is_chunked_transfer_encoding(x.headers)) {
  5751. auto result = read_content_chunked(strm, x, payload_max_length, out);
  5752. if (result == ReadContentResult::Success) {
  5753. ret = true;
  5754. } else if (result == ReadContentResult::PayloadTooLarge) {
  5755. exceed_payload_max_length = true;
  5756. ret = false;
  5757. } else {
  5758. ret = false;
  5759. }
  5760. } else if (!has_header(x.headers, "Content-Length")) {
  5761. auto result =
  5762. read_content_without_length(strm, payload_max_length, out);
  5763. if (result == ReadContentResult::Success) {
  5764. ret = true;
  5765. } else if (result == ReadContentResult::PayloadTooLarge) {
  5766. exceed_payload_max_length = true;
  5767. ret = false;
  5768. } else {
  5769. ret = false;
  5770. }
  5771. } else {
  5772. auto is_invalid_value = false;
  5773. auto len = get_header_value_u64(x.headers, "Content-Length",
  5774. (std::numeric_limits<size_t>::max)(),
  5775. 0, is_invalid_value);
  5776. if (is_invalid_value) {
  5777. ret = false;
  5778. } else if (len > 0) {
  5779. auto result = read_content_with_length(
  5780. strm, len, std::move(progress), out, payload_max_length);
  5781. ret = (result == ReadContentResult::Success);
  5782. if (result == ReadContentResult::PayloadTooLarge) {
  5783. exceed_payload_max_length = true;
  5784. }
  5785. }
  5786. }
  5787. if (!ret) {
  5788. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  5789. : StatusCode::BadRequest_400;
  5790. }
  5791. return ret;
  5792. });
  5793. }
  5794. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  5795. const std::string &path) {
  5796. std::string s = method;
  5797. s += ' ';
  5798. s += path;
  5799. s += " HTTP/1.1\r\n";
  5800. return strm.write(s.data(), s.size());
  5801. }
  5802. inline ssize_t write_response_line(Stream &strm, int status) {
  5803. std::string s = "HTTP/1.1 ";
  5804. s += std::to_string(status);
  5805. s += ' ';
  5806. s += httplib::status_message(status);
  5807. s += "\r\n";
  5808. return strm.write(s.data(), s.size());
  5809. }
  5810. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  5811. ssize_t write_len = 0;
  5812. for (const auto &x : headers) {
  5813. std::string s;
  5814. s = x.first;
  5815. s += ": ";
  5816. s += x.second;
  5817. s += "\r\n";
  5818. auto len = strm.write(s.data(), s.size());
  5819. if (len < 0) { return len; }
  5820. write_len += len;
  5821. }
  5822. auto len = strm.write("\r\n");
  5823. if (len < 0) { return len; }
  5824. write_len += len;
  5825. return write_len;
  5826. }
  5827. inline bool write_data(Stream &strm, const char *d, size_t l) {
  5828. size_t offset = 0;
  5829. while (offset < l) {
  5830. auto length = strm.write(d + offset, l - offset);
  5831. if (length < 0) { return false; }
  5832. offset += static_cast<size_t>(length);
  5833. }
  5834. return true;
  5835. }
  5836. template <typename T>
  5837. inline bool write_content_with_progress(Stream &strm,
  5838. const ContentProvider &content_provider,
  5839. size_t offset, size_t length,
  5840. T is_shutting_down,
  5841. const UploadProgress &upload_progress,
  5842. Error &error) {
  5843. size_t end_offset = offset + length;
  5844. size_t start_offset = offset;
  5845. auto ok = true;
  5846. DataSink data_sink;
  5847. data_sink.write = [&](const char *d, size_t l) -> bool {
  5848. if (ok) {
  5849. if (write_data(strm, d, l)) {
  5850. offset += l;
  5851. if (upload_progress && length > 0) {
  5852. size_t current_written = offset - start_offset;
  5853. if (!upload_progress(current_written, length)) {
  5854. ok = false;
  5855. return false;
  5856. }
  5857. }
  5858. } else {
  5859. ok = false;
  5860. }
  5861. }
  5862. return ok;
  5863. };
  5864. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5865. while (offset < end_offset && !is_shutting_down()) {
  5866. if (!strm.wait_writable()) {
  5867. error = Error::Write;
  5868. return false;
  5869. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  5870. error = Error::Canceled;
  5871. return false;
  5872. } else if (!ok) {
  5873. error = Error::Write;
  5874. return false;
  5875. }
  5876. }
  5877. error = Error::Success;
  5878. return true;
  5879. }
  5880. template <typename T>
  5881. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5882. size_t offset, size_t length, T is_shutting_down,
  5883. Error &error) {
  5884. return write_content_with_progress<T>(strm, content_provider, offset, length,
  5885. is_shutting_down, nullptr, error);
  5886. }
  5887. template <typename T>
  5888. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5889. size_t offset, size_t length,
  5890. const T &is_shutting_down) {
  5891. auto error = Error::Success;
  5892. return write_content(strm, content_provider, offset, length, is_shutting_down,
  5893. error);
  5894. }
  5895. template <typename T>
  5896. inline bool
  5897. write_content_without_length(Stream &strm,
  5898. const ContentProvider &content_provider,
  5899. const T &is_shutting_down) {
  5900. size_t offset = 0;
  5901. auto data_available = true;
  5902. auto ok = true;
  5903. DataSink data_sink;
  5904. data_sink.write = [&](const char *d, size_t l) -> bool {
  5905. if (ok) {
  5906. offset += l;
  5907. if (!write_data(strm, d, l)) { ok = false; }
  5908. }
  5909. return ok;
  5910. };
  5911. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5912. data_sink.done = [&](void) { data_available = false; };
  5913. while (data_available && !is_shutting_down()) {
  5914. if (!strm.wait_writable()) {
  5915. return false;
  5916. } else if (!content_provider(offset, 0, data_sink)) {
  5917. return false;
  5918. } else if (!ok) {
  5919. return false;
  5920. }
  5921. }
  5922. return true;
  5923. }
  5924. template <typename T, typename U>
  5925. inline bool
  5926. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  5927. const T &is_shutting_down, U &compressor, Error &error) {
  5928. size_t offset = 0;
  5929. auto data_available = true;
  5930. auto ok = true;
  5931. DataSink data_sink;
  5932. data_sink.write = [&](const char *d, size_t l) -> bool {
  5933. if (ok) {
  5934. data_available = l > 0;
  5935. offset += l;
  5936. std::string payload;
  5937. if (compressor.compress(d, l, false,
  5938. [&](const char *data, size_t data_len) {
  5939. payload.append(data, data_len);
  5940. return true;
  5941. })) {
  5942. if (!payload.empty()) {
  5943. // Emit chunked response header and footer for each chunk
  5944. auto chunk =
  5945. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5946. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  5947. }
  5948. } else {
  5949. ok = false;
  5950. }
  5951. }
  5952. return ok;
  5953. };
  5954. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5955. auto done_with_trailer = [&](const Headers *trailer) {
  5956. if (!ok) { return; }
  5957. data_available = false;
  5958. std::string payload;
  5959. if (!compressor.compress(nullptr, 0, true,
  5960. [&](const char *data, size_t data_len) {
  5961. payload.append(data, data_len);
  5962. return true;
  5963. })) {
  5964. ok = false;
  5965. return;
  5966. }
  5967. if (!payload.empty()) {
  5968. // Emit chunked response header and footer for each chunk
  5969. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5970. if (!write_data(strm, chunk.data(), chunk.size())) {
  5971. ok = false;
  5972. return;
  5973. }
  5974. }
  5975. constexpr const char done_marker[] = "0\r\n";
  5976. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  5977. // Trailer
  5978. if (trailer) {
  5979. for (const auto &kv : *trailer) {
  5980. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  5981. if (!write_data(strm, field_line.data(), field_line.size())) {
  5982. ok = false;
  5983. }
  5984. }
  5985. }
  5986. constexpr const char crlf[] = "\r\n";
  5987. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  5988. };
  5989. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  5990. data_sink.done_with_trailer = [&](const Headers &trailer) {
  5991. done_with_trailer(&trailer);
  5992. };
  5993. while (data_available && !is_shutting_down()) {
  5994. if (!strm.wait_writable()) {
  5995. error = Error::Write;
  5996. return false;
  5997. } else if (!content_provider(offset, 0, data_sink)) {
  5998. error = Error::Canceled;
  5999. return false;
  6000. } else if (!ok) {
  6001. error = Error::Write;
  6002. return false;
  6003. }
  6004. }
  6005. error = Error::Success;
  6006. return true;
  6007. }
  6008. template <typename T, typename U>
  6009. inline bool write_content_chunked(Stream &strm,
  6010. const ContentProvider &content_provider,
  6011. const T &is_shutting_down, U &compressor) {
  6012. auto error = Error::Success;
  6013. return write_content_chunked(strm, content_provider, is_shutting_down,
  6014. compressor, error);
  6015. }
  6016. template <typename T>
  6017. inline bool redirect(T &cli, Request &req, Response &res,
  6018. const std::string &path, const std::string &location,
  6019. Error &error) {
  6020. Request new_req = req;
  6021. new_req.path = path;
  6022. new_req.redirect_count_ -= 1;
  6023. if (res.status == StatusCode::SeeOther_303 &&
  6024. (req.method != "GET" && req.method != "HEAD")) {
  6025. new_req.method = "GET";
  6026. new_req.body.clear();
  6027. new_req.headers.clear();
  6028. }
  6029. Response new_res;
  6030. auto ret = cli.send(new_req, new_res, error);
  6031. if (ret) {
  6032. req = std::move(new_req);
  6033. res = std::move(new_res);
  6034. if (res.location.empty()) { res.location = location; }
  6035. }
  6036. return ret;
  6037. }
  6038. inline std::string params_to_query_str(const Params &params) {
  6039. std::string query;
  6040. for (auto it = params.begin(); it != params.end(); ++it) {
  6041. if (it != params.begin()) { query += '&'; }
  6042. query += encode_query_component(it->first);
  6043. query += '=';
  6044. query += encode_query_component(it->second);
  6045. }
  6046. return query;
  6047. }
  6048. inline void parse_query_text(const char *data, std::size_t size,
  6049. Params &params) {
  6050. std::set<std::string> cache;
  6051. split(data, data + size, '&', [&](const char *b, const char *e) {
  6052. std::string kv(b, e);
  6053. if (cache.find(kv) != cache.end()) { return; }
  6054. cache.insert(std::move(kv));
  6055. std::string key;
  6056. std::string val;
  6057. divide(b, static_cast<std::size_t>(e - b), '=',
  6058. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6059. std::size_t rhs_size) {
  6060. key.assign(lhs_data, lhs_size);
  6061. val.assign(rhs_data, rhs_size);
  6062. });
  6063. if (!key.empty()) {
  6064. params.emplace(decode_query_component(key), decode_query_component(val));
  6065. }
  6066. });
  6067. }
  6068. inline void parse_query_text(const std::string &s, Params &params) {
  6069. parse_query_text(s.data(), s.size(), params);
  6070. }
  6071. // Normalize a query string by decoding and re-encoding each key/value pair
  6072. // while preserving the original parameter order. This avoids double-encoding
  6073. // and ensures consistent encoding without reordering (unlike Params which
  6074. // uses std::multimap and sorts keys).
  6075. inline std::string normalize_query_string(const std::string &query) {
  6076. std::string result;
  6077. split(query.data(), query.data() + query.size(), '&',
  6078. [&](const char *b, const char *e) {
  6079. std::string key;
  6080. std::string val;
  6081. divide(b, static_cast<std::size_t>(e - b), '=',
  6082. [&](const char *lhs_data, std::size_t lhs_size,
  6083. const char *rhs_data, std::size_t rhs_size) {
  6084. key.assign(lhs_data, lhs_size);
  6085. val.assign(rhs_data, rhs_size);
  6086. });
  6087. if (!key.empty()) {
  6088. auto dec_key = decode_query_component(key);
  6089. auto dec_val = decode_query_component(val);
  6090. if (!result.empty()) { result += '&'; }
  6091. result += encode_query_component(dec_key);
  6092. if (!val.empty() || std::find(b, e, '=') != e) {
  6093. result += '=';
  6094. result += encode_query_component(dec_val);
  6095. }
  6096. }
  6097. });
  6098. return result;
  6099. }
  6100. inline bool parse_multipart_boundary(const std::string &content_type,
  6101. std::string &boundary) {
  6102. auto boundary_keyword = "boundary=";
  6103. auto pos = content_type.find(boundary_keyword);
  6104. if (pos == std::string::npos) { return false; }
  6105. auto end = content_type.find(';', pos);
  6106. auto beg = pos + strlen(boundary_keyword);
  6107. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  6108. return !boundary.empty();
  6109. }
  6110. inline void parse_disposition_params(const std::string &s, Params &params) {
  6111. std::set<std::string> cache;
  6112. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6113. std::string kv(b, e);
  6114. if (cache.find(kv) != cache.end()) { return; }
  6115. cache.insert(kv);
  6116. std::string key;
  6117. std::string val;
  6118. split(b, e, '=', [&](const char *b2, const char *e2) {
  6119. if (key.empty()) {
  6120. key.assign(b2, e2);
  6121. } else {
  6122. val.assign(b2, e2);
  6123. }
  6124. });
  6125. if (!key.empty()) {
  6126. params.emplace(trim_double_quotes_copy((key)),
  6127. trim_double_quotes_copy((val)));
  6128. }
  6129. });
  6130. }
  6131. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6132. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6133. #else
  6134. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6135. #endif
  6136. auto is_valid = [](const std::string &str) {
  6137. return std::all_of(str.cbegin(), str.cend(),
  6138. [](unsigned char c) { return std::isdigit(c); });
  6139. };
  6140. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6141. const auto pos = static_cast<size_t>(6);
  6142. const auto len = static_cast<size_t>(s.size() - 6);
  6143. auto all_valid_ranges = true;
  6144. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6145. if (!all_valid_ranges) { return; }
  6146. const auto it = std::find(b, e, '-');
  6147. if (it == e) {
  6148. all_valid_ranges = false;
  6149. return;
  6150. }
  6151. const auto lhs = std::string(b, it);
  6152. const auto rhs = std::string(it + 1, e);
  6153. if (!is_valid(lhs) || !is_valid(rhs)) {
  6154. all_valid_ranges = false;
  6155. return;
  6156. }
  6157. ssize_t first = -1;
  6158. if (!lhs.empty()) {
  6159. ssize_t v;
  6160. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6161. if (res.ec == std::errc{}) { first = v; }
  6162. }
  6163. ssize_t last = -1;
  6164. if (!rhs.empty()) {
  6165. ssize_t v;
  6166. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6167. if (res.ec == std::errc{}) { last = v; }
  6168. }
  6169. if ((first == -1 && last == -1) ||
  6170. (first != -1 && last != -1 && first > last)) {
  6171. all_valid_ranges = false;
  6172. return;
  6173. }
  6174. ranges.emplace_back(first, last);
  6175. });
  6176. return all_valid_ranges && !ranges.empty();
  6177. }
  6178. return false;
  6179. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6180. }
  6181. #else
  6182. } catch (...) { return false; }
  6183. #endif
  6184. inline bool parse_accept_header(const std::string &s,
  6185. std::vector<std::string> &content_types) {
  6186. content_types.clear();
  6187. // Empty string is considered valid (no preference)
  6188. if (s.empty()) { return true; }
  6189. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6190. if (s.front() == ',' || s.back() == ',' ||
  6191. s.find(",,") != std::string::npos) {
  6192. return false;
  6193. }
  6194. struct AcceptEntry {
  6195. std::string media_type;
  6196. double quality;
  6197. int order; // Original order in header
  6198. };
  6199. std::vector<AcceptEntry> entries;
  6200. int order = 0;
  6201. bool has_invalid_entry = false;
  6202. // Split by comma and parse each entry
  6203. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6204. std::string entry(b, e);
  6205. entry = trim_copy(entry);
  6206. if (entry.empty()) {
  6207. has_invalid_entry = true;
  6208. return;
  6209. }
  6210. AcceptEntry accept_entry;
  6211. accept_entry.quality = 1.0; // Default quality
  6212. accept_entry.order = order++;
  6213. // Find q= parameter
  6214. auto q_pos = entry.find(";q=");
  6215. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  6216. if (q_pos != std::string::npos) {
  6217. // Extract media type (before q parameter)
  6218. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  6219. // Extract quality value
  6220. auto q_start = entry.find('=', q_pos) + 1;
  6221. auto q_end = entry.find(';', q_start);
  6222. if (q_end == std::string::npos) { q_end = entry.length(); }
  6223. std::string quality_str =
  6224. trim_copy(entry.substr(q_start, q_end - q_start));
  6225. if (quality_str.empty()) {
  6226. has_invalid_entry = true;
  6227. return;
  6228. }
  6229. {
  6230. double v = 0.0;
  6231. auto res = detail::from_chars(
  6232. quality_str.data(), quality_str.data() + quality_str.size(), v);
  6233. if (res.ec == std::errc{}) {
  6234. accept_entry.quality = v;
  6235. } else {
  6236. has_invalid_entry = true;
  6237. return;
  6238. }
  6239. }
  6240. // Check if quality is in valid range [0.0, 1.0]
  6241. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  6242. has_invalid_entry = true;
  6243. return;
  6244. }
  6245. } else {
  6246. // No quality parameter, use entire entry as media type
  6247. accept_entry.media_type = entry;
  6248. }
  6249. // Remove additional parameters from media type
  6250. auto param_pos = accept_entry.media_type.find(';');
  6251. if (param_pos != std::string::npos) {
  6252. accept_entry.media_type =
  6253. trim_copy(accept_entry.media_type.substr(0, param_pos));
  6254. }
  6255. // Basic validation of media type format
  6256. if (accept_entry.media_type.empty()) {
  6257. has_invalid_entry = true;
  6258. return;
  6259. }
  6260. // Check for basic media type format (should contain '/' or be '*')
  6261. if (accept_entry.media_type != "*" &&
  6262. accept_entry.media_type.find('/') == std::string::npos) {
  6263. has_invalid_entry = true;
  6264. return;
  6265. }
  6266. entries.push_back(std::move(accept_entry));
  6267. });
  6268. // Return false if any invalid entry was found
  6269. if (has_invalid_entry) { return false; }
  6270. // Sort by quality (descending), then by original order (ascending)
  6271. std::sort(entries.begin(), entries.end(),
  6272. [](const AcceptEntry &a, const AcceptEntry &b) {
  6273. if (a.quality != b.quality) {
  6274. return a.quality > b.quality; // Higher quality first
  6275. }
  6276. return a.order < b.order; // Earlier order first for same quality
  6277. });
  6278. // Extract sorted media types
  6279. content_types.reserve(entries.size());
  6280. for (auto &entry : entries) {
  6281. content_types.push_back(std::move(entry.media_type));
  6282. }
  6283. return true;
  6284. }
  6285. class FormDataParser {
  6286. public:
  6287. FormDataParser() = default;
  6288. void set_boundary(std::string &&boundary) {
  6289. boundary_ = std::move(boundary);
  6290. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6291. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6292. }
  6293. bool is_valid() const { return is_valid_; }
  6294. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6295. const ContentReceiver &content_callback) {
  6296. buf_append(buf, n);
  6297. while (buf_size() > 0) {
  6298. switch (state_) {
  6299. case 0: { // Initial boundary
  6300. auto pos = buf_find(dash_boundary_crlf_);
  6301. if (pos == buf_size()) { return true; }
  6302. buf_erase(pos + dash_boundary_crlf_.size());
  6303. state_ = 1;
  6304. break;
  6305. }
  6306. case 1: { // New entry
  6307. clear_file_info();
  6308. state_ = 2;
  6309. break;
  6310. }
  6311. case 2: { // Headers
  6312. auto pos = buf_find(crlf_);
  6313. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6314. while (pos < buf_size()) {
  6315. // Empty line
  6316. if (pos == 0) {
  6317. if (!header_callback(file_)) {
  6318. is_valid_ = false;
  6319. return false;
  6320. }
  6321. buf_erase(crlf_.size());
  6322. state_ = 3;
  6323. break;
  6324. }
  6325. const auto header = buf_head(pos);
  6326. if (!parse_header(header.data(), header.data() + header.size(),
  6327. [&](const std::string &, const std::string &) {})) {
  6328. is_valid_ = false;
  6329. return false;
  6330. }
  6331. // Parse and emplace space trimmed headers into a map
  6332. if (!parse_header(
  6333. header.data(), header.data() + header.size(),
  6334. [&](const std::string &key, const std::string &val) {
  6335. file_.headers.emplace(key, val);
  6336. })) {
  6337. is_valid_ = false;
  6338. return false;
  6339. }
  6340. constexpr const char header_content_type[] = "Content-Type:";
  6341. if (start_with_case_ignore(header, header_content_type)) {
  6342. file_.content_type =
  6343. trim_copy(header.substr(str_len(header_content_type)));
  6344. } else {
  6345. thread_local const std::regex re_content_disposition(
  6346. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  6347. std::regex_constants::icase);
  6348. std::smatch m;
  6349. if (std::regex_match(header, m, re_content_disposition)) {
  6350. Params params;
  6351. parse_disposition_params(m[1], params);
  6352. auto it = params.find("name");
  6353. if (it != params.end()) {
  6354. file_.name = it->second;
  6355. } else {
  6356. is_valid_ = false;
  6357. return false;
  6358. }
  6359. it = params.find("filename");
  6360. if (it != params.end()) { file_.filename = it->second; }
  6361. it = params.find("filename*");
  6362. if (it != params.end()) {
  6363. // Only allow UTF-8 encoding...
  6364. thread_local const std::regex re_rfc5987_encoding(
  6365. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  6366. std::smatch m2;
  6367. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  6368. file_.filename = decode_path_component(m2[1]); // override...
  6369. } else {
  6370. is_valid_ = false;
  6371. return false;
  6372. }
  6373. }
  6374. }
  6375. }
  6376. buf_erase(pos + crlf_.size());
  6377. pos = buf_find(crlf_);
  6378. }
  6379. if (state_ != 3) { return true; }
  6380. break;
  6381. }
  6382. case 3: { // Body
  6383. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6384. auto pos = buf_find(crlf_dash_boundary_);
  6385. if (pos < buf_size()) {
  6386. if (!content_callback(buf_data(), pos)) {
  6387. is_valid_ = false;
  6388. return false;
  6389. }
  6390. buf_erase(pos + crlf_dash_boundary_.size());
  6391. state_ = 4;
  6392. } else {
  6393. auto len = buf_size() - crlf_dash_boundary_.size();
  6394. if (len > 0) {
  6395. if (!content_callback(buf_data(), len)) {
  6396. is_valid_ = false;
  6397. return false;
  6398. }
  6399. buf_erase(len);
  6400. }
  6401. return true;
  6402. }
  6403. break;
  6404. }
  6405. case 4: { // Boundary
  6406. if (crlf_.size() > buf_size()) { return true; }
  6407. if (buf_start_with(crlf_)) {
  6408. buf_erase(crlf_.size());
  6409. state_ = 1;
  6410. } else {
  6411. if (dash_.size() > buf_size()) { return true; }
  6412. if (buf_start_with(dash_)) {
  6413. buf_erase(dash_.size());
  6414. is_valid_ = true;
  6415. buf_erase(buf_size()); // Remove epilogue
  6416. } else {
  6417. return true;
  6418. }
  6419. }
  6420. break;
  6421. }
  6422. }
  6423. }
  6424. return true;
  6425. }
  6426. private:
  6427. void clear_file_info() {
  6428. file_.name.clear();
  6429. file_.filename.clear();
  6430. file_.content_type.clear();
  6431. file_.headers.clear();
  6432. }
  6433. bool start_with_case_ignore(const std::string &a, const char *b) const {
  6434. const auto b_len = strlen(b);
  6435. if (a.size() < b_len) { return false; }
  6436. for (size_t i = 0; i < b_len; i++) {
  6437. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  6438. return false;
  6439. }
  6440. }
  6441. return true;
  6442. }
  6443. const std::string dash_ = "--";
  6444. const std::string crlf_ = "\r\n";
  6445. std::string boundary_;
  6446. std::string dash_boundary_crlf_;
  6447. std::string crlf_dash_boundary_;
  6448. size_t state_ = 0;
  6449. bool is_valid_ = false;
  6450. FormData file_;
  6451. // Buffer
  6452. bool start_with(const std::string &a, size_t spos, size_t epos,
  6453. const std::string &b) const {
  6454. if (epos - spos < b.size()) { return false; }
  6455. for (size_t i = 0; i < b.size(); i++) {
  6456. if (a[i + spos] != b[i]) { return false; }
  6457. }
  6458. return true;
  6459. }
  6460. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6461. const char *buf_data() const { return &buf_[buf_spos_]; }
  6462. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6463. bool buf_start_with(const std::string &s) const {
  6464. return start_with(buf_, buf_spos_, buf_epos_, s);
  6465. }
  6466. size_t buf_find(const std::string &s) const {
  6467. auto c = s.front();
  6468. size_t off = buf_spos_;
  6469. while (off < buf_epos_) {
  6470. auto pos = off;
  6471. while (true) {
  6472. if (pos == buf_epos_) { return buf_size(); }
  6473. if (buf_[pos] == c) { break; }
  6474. pos++;
  6475. }
  6476. auto remaining_size = buf_epos_ - pos;
  6477. if (s.size() > remaining_size) { return buf_size(); }
  6478. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6479. off = pos + 1;
  6480. }
  6481. return buf_size();
  6482. }
  6483. void buf_append(const char *data, size_t n) {
  6484. auto remaining_size = buf_size();
  6485. if (remaining_size > 0 && buf_spos_ > 0) {
  6486. for (size_t i = 0; i < remaining_size; i++) {
  6487. buf_[i] = buf_[buf_spos_ + i];
  6488. }
  6489. }
  6490. buf_spos_ = 0;
  6491. buf_epos_ = remaining_size;
  6492. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6493. for (size_t i = 0; i < n; i++) {
  6494. buf_[buf_epos_ + i] = data[i];
  6495. }
  6496. buf_epos_ += n;
  6497. }
  6498. void buf_erase(size_t size) { buf_spos_ += size; }
  6499. std::string buf_;
  6500. size_t buf_spos_ = 0;
  6501. size_t buf_epos_ = 0;
  6502. };
  6503. inline std::string random_string(size_t length) {
  6504. constexpr const char data[] =
  6505. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6506. thread_local auto engine([]() {
  6507. // std::random_device might actually be deterministic on some
  6508. // platforms, but due to lack of support in the c++ standard library,
  6509. // doing better requires either some ugly hacks or breaking portability.
  6510. std::random_device seed_gen;
  6511. // Request 128 bits of entropy for initialization
  6512. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6513. return std::mt19937(seed_sequence);
  6514. }());
  6515. std::string result;
  6516. for (size_t i = 0; i < length; i++) {
  6517. result += data[engine() % (sizeof(data) - 1)];
  6518. }
  6519. return result;
  6520. }
  6521. inline std::string make_multipart_data_boundary() {
  6522. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6523. }
  6524. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6525. auto valid = true;
  6526. for (size_t i = 0; i < boundary.size(); i++) {
  6527. auto c = boundary[i];
  6528. if (!std::isalnum(c) && c != '-' && c != '_') {
  6529. valid = false;
  6530. break;
  6531. }
  6532. }
  6533. return valid;
  6534. }
  6535. template <typename T>
  6536. inline std::string
  6537. serialize_multipart_formdata_item_begin(const T &item,
  6538. const std::string &boundary) {
  6539. std::string body = "--" + boundary + "\r\n";
  6540. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6541. if (!item.filename.empty()) {
  6542. body += "; filename=\"" + item.filename + "\"";
  6543. }
  6544. body += "\r\n";
  6545. if (!item.content_type.empty()) {
  6546. body += "Content-Type: " + item.content_type + "\r\n";
  6547. }
  6548. body += "\r\n";
  6549. return body;
  6550. }
  6551. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  6552. inline std::string
  6553. serialize_multipart_formdata_finish(const std::string &boundary) {
  6554. return "--" + boundary + "--\r\n";
  6555. }
  6556. inline std::string
  6557. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  6558. return "multipart/form-data; boundary=" + boundary;
  6559. }
  6560. inline std::string
  6561. serialize_multipart_formdata(const UploadFormDataItems &items,
  6562. const std::string &boundary, bool finish = true) {
  6563. std::string body;
  6564. for (const auto &item : items) {
  6565. body += serialize_multipart_formdata_item_begin(item, boundary);
  6566. body += item.content + serialize_multipart_formdata_item_end();
  6567. }
  6568. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  6569. return body;
  6570. }
  6571. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  6572. const std::string &boundary) {
  6573. size_t total = 0;
  6574. for (const auto &item : items) {
  6575. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  6576. total += item.content.size();
  6577. total += serialize_multipart_formdata_item_end().size();
  6578. }
  6579. total += serialize_multipart_formdata_finish(boundary).size();
  6580. return total;
  6581. }
  6582. struct MultipartSegment {
  6583. const char *data;
  6584. size_t size;
  6585. };
  6586. // NOTE: items must outlive the returned ContentProvider
  6587. // (safe for synchronous use inside Post/Put/Patch)
  6588. inline ContentProvider
  6589. make_multipart_content_provider(const UploadFormDataItems &items,
  6590. const std::string &boundary) {
  6591. // Own the per-item header strings and the finish string
  6592. std::vector<std::string> owned;
  6593. owned.reserve(items.size() + 1);
  6594. for (const auto &item : items)
  6595. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  6596. owned.push_back(serialize_multipart_formdata_finish(boundary));
  6597. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  6598. std::vector<MultipartSegment> segs;
  6599. segs.reserve(items.size() * 3 + 1);
  6600. static const char crlf[] = "\r\n";
  6601. for (size_t i = 0; i < items.size(); i++) {
  6602. segs.push_back({owned[i].data(), owned[i].size()});
  6603. segs.push_back({items[i].content.data(), items[i].content.size()});
  6604. segs.push_back({crlf, 2});
  6605. }
  6606. segs.push_back({owned.back().data(), owned.back().size()});
  6607. struct MultipartState {
  6608. std::vector<std::string> owned;
  6609. std::vector<MultipartSegment> segs;
  6610. };
  6611. auto state = std::make_shared<MultipartState>();
  6612. state->owned = std::move(owned);
  6613. // `segs` holds raw pointers into owned strings; std::string move preserves
  6614. // the data pointer, so these pointers remain valid after the move above.
  6615. state->segs = std::move(segs);
  6616. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  6617. size_t pos = 0;
  6618. for (const auto &seg : state->segs) {
  6619. // Loop invariant: pos <= offset (proven by advancing pos only when
  6620. // offset - pos >= seg.size, i.e., the segment doesn't contain offset)
  6621. if (seg.size > 0 && offset - pos < seg.size) {
  6622. size_t seg_offset = offset - pos;
  6623. size_t available = seg.size - seg_offset;
  6624. size_t to_write = (std::min)(available, length);
  6625. return sink.write(seg.data + seg_offset, to_write);
  6626. }
  6627. pos += seg.size;
  6628. }
  6629. return true; // past end (shouldn't be reached when content_length is exact)
  6630. };
  6631. }
  6632. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  6633. if (ranges.size() <= 1) return;
  6634. // Sort ranges by start position
  6635. std::sort(ranges.begin(), ranges.end(),
  6636. [](const Range &a, const Range &b) { return a.first < b.first; });
  6637. Ranges coalesced;
  6638. coalesced.reserve(ranges.size());
  6639. for (auto &r : ranges) {
  6640. auto first_pos = r.first;
  6641. auto last_pos = r.second;
  6642. // Handle special cases like in range_error
  6643. if (first_pos == -1 && last_pos == -1) {
  6644. first_pos = 0;
  6645. last_pos = static_cast<ssize_t>(content_length);
  6646. }
  6647. if (first_pos == -1) {
  6648. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  6649. last_pos = static_cast<ssize_t>(content_length) - 1;
  6650. }
  6651. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  6652. last_pos = static_cast<ssize_t>(content_length) - 1;
  6653. }
  6654. // Skip invalid ranges
  6655. if (!(0 <= first_pos && first_pos <= last_pos &&
  6656. last_pos < static_cast<ssize_t>(content_length))) {
  6657. continue;
  6658. }
  6659. // Coalesce with previous range if overlapping or adjacent (but not
  6660. // identical)
  6661. if (!coalesced.empty()) {
  6662. auto &prev = coalesced.back();
  6663. // Check if current range overlaps or is adjacent to previous range
  6664. // but don't coalesce identical ranges (allow duplicates)
  6665. if (first_pos <= prev.second + 1 &&
  6666. !(first_pos == prev.first && last_pos == prev.second)) {
  6667. // Extend the previous range
  6668. prev.second = (std::max)(prev.second, last_pos);
  6669. continue;
  6670. }
  6671. }
  6672. // Add new range
  6673. coalesced.emplace_back(first_pos, last_pos);
  6674. }
  6675. ranges = std::move(coalesced);
  6676. }
  6677. inline bool range_error(Request &req, Response &res) {
  6678. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  6679. ssize_t content_len = static_cast<ssize_t>(
  6680. res.content_length_ ? res.content_length_ : res.body.size());
  6681. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  6682. size_t overwrapping_count = 0;
  6683. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  6684. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  6685. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  6686. // Too many ranges
  6687. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  6688. for (auto &r : req.ranges) {
  6689. auto &first_pos = r.first;
  6690. auto &last_pos = r.second;
  6691. if (first_pos == -1 && last_pos == -1) {
  6692. first_pos = 0;
  6693. last_pos = content_len;
  6694. }
  6695. if (first_pos == -1) {
  6696. first_pos = content_len - last_pos;
  6697. last_pos = content_len - 1;
  6698. }
  6699. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  6700. // A client can limit the number of bytes requested without knowing the
  6701. // size of the selected representation. If the last-pos value is absent,
  6702. // or if the value is greater than or equal to the current length of the
  6703. // representation data, the byte range is interpreted as the remainder of
  6704. // the representation (i.e., the server replaces the value of last-pos
  6705. // with a value that is one less than the current length of the selected
  6706. // representation).
  6707. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  6708. if (last_pos == -1 || last_pos >= content_len) {
  6709. last_pos = content_len - 1;
  6710. }
  6711. // Range must be within content length
  6712. if (!(0 <= first_pos && first_pos <= last_pos &&
  6713. last_pos <= content_len - 1)) {
  6714. return true;
  6715. }
  6716. // Request must not have more than two overlapping ranges
  6717. for (const auto &processed_range : processed_ranges) {
  6718. if (!(last_pos < processed_range.first ||
  6719. first_pos > processed_range.second)) {
  6720. overwrapping_count++;
  6721. if (overwrapping_count > 2) { return true; }
  6722. break; // Only count once per range
  6723. }
  6724. }
  6725. processed_ranges.emplace_back(first_pos, last_pos);
  6726. }
  6727. // After validation, coalesce overlapping ranges as per RFC 9110
  6728. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  6729. }
  6730. return false;
  6731. }
  6732. inline std::pair<size_t, size_t>
  6733. get_range_offset_and_length(Range r, size_t content_length) {
  6734. assert(r.first != -1 && r.second != -1);
  6735. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  6736. assert(r.first <= r.second &&
  6737. r.second < static_cast<ssize_t>(content_length));
  6738. (void)(content_length);
  6739. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  6740. }
  6741. inline std::string make_content_range_header_field(
  6742. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  6743. auto st = offset_and_length.first;
  6744. auto ed = st + offset_and_length.second - 1;
  6745. std::string field = "bytes ";
  6746. field += std::to_string(st);
  6747. field += '-';
  6748. field += std::to_string(ed);
  6749. field += '/';
  6750. field += std::to_string(content_length);
  6751. return field;
  6752. }
  6753. template <typename SToken, typename CToken, typename Content>
  6754. bool process_multipart_ranges_data(const Request &req,
  6755. const std::string &boundary,
  6756. const std::string &content_type,
  6757. size_t content_length, SToken stoken,
  6758. CToken ctoken, Content content) {
  6759. for (size_t i = 0; i < req.ranges.size(); i++) {
  6760. ctoken("--");
  6761. stoken(boundary);
  6762. ctoken("\r\n");
  6763. if (!content_type.empty()) {
  6764. ctoken("Content-Type: ");
  6765. stoken(content_type);
  6766. ctoken("\r\n");
  6767. }
  6768. auto offset_and_length =
  6769. get_range_offset_and_length(req.ranges[i], content_length);
  6770. ctoken("Content-Range: ");
  6771. stoken(make_content_range_header_field(offset_and_length, content_length));
  6772. ctoken("\r\n");
  6773. ctoken("\r\n");
  6774. if (!content(offset_and_length.first, offset_and_length.second)) {
  6775. return false;
  6776. }
  6777. ctoken("\r\n");
  6778. }
  6779. ctoken("--");
  6780. stoken(boundary);
  6781. ctoken("--");
  6782. return true;
  6783. }
  6784. inline void make_multipart_ranges_data(const Request &req, Response &res,
  6785. const std::string &boundary,
  6786. const std::string &content_type,
  6787. size_t content_length,
  6788. std::string &data) {
  6789. process_multipart_ranges_data(
  6790. req, boundary, content_type, content_length,
  6791. [&](const std::string &token) { data += token; },
  6792. [&](const std::string &token) { data += token; },
  6793. [&](size_t offset, size_t length) {
  6794. assert(offset + length <= content_length);
  6795. data += res.body.substr(offset, length);
  6796. return true;
  6797. });
  6798. }
  6799. inline size_t get_multipart_ranges_data_length(const Request &req,
  6800. const std::string &boundary,
  6801. const std::string &content_type,
  6802. size_t content_length) {
  6803. size_t data_length = 0;
  6804. process_multipart_ranges_data(
  6805. req, boundary, content_type, content_length,
  6806. [&](const std::string &token) { data_length += token.size(); },
  6807. [&](const std::string &token) { data_length += token.size(); },
  6808. [&](size_t /*offset*/, size_t length) {
  6809. data_length += length;
  6810. return true;
  6811. });
  6812. return data_length;
  6813. }
  6814. template <typename T>
  6815. inline bool
  6816. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  6817. const std::string &boundary,
  6818. const std::string &content_type,
  6819. size_t content_length, const T &is_shutting_down) {
  6820. return process_multipart_ranges_data(
  6821. req, boundary, content_type, content_length,
  6822. [&](const std::string &token) { strm.write(token); },
  6823. [&](const std::string &token) { strm.write(token); },
  6824. [&](size_t offset, size_t length) {
  6825. return write_content(strm, res.content_provider_, offset, length,
  6826. is_shutting_down);
  6827. });
  6828. }
  6829. inline bool expect_content(const Request &req) {
  6830. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  6831. req.method == "DELETE") {
  6832. return true;
  6833. }
  6834. if (req.has_header("Content-Length") &&
  6835. req.get_header_value_u64("Content-Length") > 0) {
  6836. return true;
  6837. }
  6838. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  6839. return false;
  6840. }
  6841. #ifdef _WIN32
  6842. class WSInit {
  6843. public:
  6844. WSInit() {
  6845. WSADATA wsaData;
  6846. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  6847. }
  6848. ~WSInit() {
  6849. if (is_valid_) WSACleanup();
  6850. }
  6851. bool is_valid_ = false;
  6852. };
  6853. static WSInit wsinit_;
  6854. #endif
  6855. inline bool parse_www_authenticate(const Response &res,
  6856. std::map<std::string, std::string> &auth,
  6857. bool is_proxy) {
  6858. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  6859. if (res.has_header(auth_key)) {
  6860. thread_local auto re =
  6861. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  6862. auto s = res.get_header_value(auth_key);
  6863. auto pos = s.find(' ');
  6864. if (pos != std::string::npos) {
  6865. auto type = s.substr(0, pos);
  6866. if (type == "Basic") {
  6867. return false;
  6868. } else if (type == "Digest") {
  6869. s = s.substr(pos + 1);
  6870. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  6871. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  6872. const auto &m = *i;
  6873. auto key = s.substr(static_cast<size_t>(m.position(1)),
  6874. static_cast<size_t>(m.length(1)));
  6875. auto val = m.length(2) > 0
  6876. ? s.substr(static_cast<size_t>(m.position(2)),
  6877. static_cast<size_t>(m.length(2)))
  6878. : s.substr(static_cast<size_t>(m.position(3)),
  6879. static_cast<size_t>(m.length(3)));
  6880. auth[std::move(key)] = std::move(val);
  6881. }
  6882. return true;
  6883. }
  6884. }
  6885. }
  6886. return false;
  6887. }
  6888. class ContentProviderAdapter {
  6889. public:
  6890. explicit ContentProviderAdapter(
  6891. ContentProviderWithoutLength &&content_provider)
  6892. : content_provider_(std::move(content_provider)) {}
  6893. bool operator()(size_t offset, size_t, DataSink &sink) {
  6894. return content_provider_(offset, sink);
  6895. }
  6896. private:
  6897. ContentProviderWithoutLength content_provider_;
  6898. };
  6899. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  6900. namespace fields {
  6901. inline bool is_token_char(char c) {
  6902. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  6903. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  6904. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  6905. }
  6906. inline bool is_token(const std::string &s) {
  6907. if (s.empty()) { return false; }
  6908. for (auto c : s) {
  6909. if (!is_token_char(c)) { return false; }
  6910. }
  6911. return true;
  6912. }
  6913. inline bool is_field_name(const std::string &s) { return is_token(s); }
  6914. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  6915. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  6916. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  6917. inline bool is_field_content(const std::string &s) {
  6918. if (s.empty()) { return true; }
  6919. if (s.size() == 1) {
  6920. return is_field_vchar(s[0]);
  6921. } else if (s.size() == 2) {
  6922. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  6923. } else {
  6924. size_t i = 0;
  6925. if (!is_field_vchar(s[i])) { return false; }
  6926. i++;
  6927. while (i < s.size() - 1) {
  6928. auto c = s[i++];
  6929. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  6930. } else {
  6931. return false;
  6932. }
  6933. }
  6934. return is_field_vchar(s[i]);
  6935. }
  6936. }
  6937. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  6938. } // namespace fields
  6939. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  6940. int port, const std::string &path,
  6941. const Headers &headers,
  6942. std::string &selected_subprotocol) {
  6943. // Validate path and host
  6944. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  6945. return false;
  6946. }
  6947. // Validate user-provided headers
  6948. for (const auto &h : headers) {
  6949. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  6950. return false;
  6951. }
  6952. }
  6953. // Generate random Sec-WebSocket-Key
  6954. thread_local std::mt19937 rng(std::random_device{}());
  6955. std::string key_bytes(16, '\0');
  6956. for (size_t i = 0; i < 16; i += 4) {
  6957. auto r = rng();
  6958. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  6959. }
  6960. auto client_key = base64_encode(key_bytes);
  6961. // Build upgrade request
  6962. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  6963. req_str += "Host: " + host + ":" + std::to_string(port) + "\r\n";
  6964. req_str += "Upgrade: websocket\r\n";
  6965. req_str += "Connection: Upgrade\r\n";
  6966. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  6967. req_str += "Sec-WebSocket-Version: 13\r\n";
  6968. for (const auto &h : headers) {
  6969. req_str += h.first + ": " + h.second + "\r\n";
  6970. }
  6971. req_str += "\r\n";
  6972. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  6973. // Verify 101 response and Sec-WebSocket-Accept header
  6974. auto expected_accept = websocket_accept_key(client_key);
  6975. return read_websocket_upgrade_response(strm, expected_accept,
  6976. selected_subprotocol);
  6977. }
  6978. } // namespace detail
  6979. /*
  6980. * Group 2: detail namespace - SSL common utilities
  6981. */
  6982. #ifdef CPPHTTPLIB_SSL_ENABLED
  6983. namespace detail {
  6984. class SSLSocketStream final : public Stream {
  6985. public:
  6986. SSLSocketStream(
  6987. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  6988. time_t read_timeout_usec, time_t write_timeout_sec,
  6989. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  6990. std::chrono::time_point<std::chrono::steady_clock> start_time =
  6991. (std::chrono::steady_clock::time_point::min)());
  6992. ~SSLSocketStream() override;
  6993. bool is_readable() const override;
  6994. bool wait_readable() const override;
  6995. bool wait_writable() const override;
  6996. ssize_t read(char *ptr, size_t size) override;
  6997. ssize_t write(const char *ptr, size_t size) override;
  6998. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  6999. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7000. socket_t socket() const override;
  7001. time_t duration() const override;
  7002. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7003. private:
  7004. socket_t sock_;
  7005. tls::session_t session_;
  7006. time_t read_timeout_sec_;
  7007. time_t read_timeout_usec_;
  7008. time_t write_timeout_sec_;
  7009. time_t write_timeout_usec_;
  7010. time_t max_timeout_msec_;
  7011. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7012. };
  7013. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7014. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7015. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7016. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7017. unsigned int hash_length = 0;
  7018. unsigned char hash[EVP_MAX_MD_SIZE];
  7019. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7020. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7021. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7022. std::stringstream ss;
  7023. for (auto i = 0u; i < hash_length; ++i) {
  7024. ss << std::hex << std::setw(2) << std::setfill('0')
  7025. << static_cast<unsigned int>(hash[i]);
  7026. }
  7027. return ss.str();
  7028. }
  7029. inline std::string MD5(const std::string &s) {
  7030. return message_digest(s, EVP_md5());
  7031. }
  7032. inline std::string SHA_256(const std::string &s) {
  7033. return message_digest(s, EVP_sha256());
  7034. }
  7035. inline std::string SHA_512(const std::string &s) {
  7036. return message_digest(s, EVP_sha512());
  7037. }
  7038. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7039. namespace {
  7040. template <size_t N>
  7041. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7042. std::stringstream ss;
  7043. for (size_t i = 0; i < N; ++i) {
  7044. ss << std::hex << std::setw(2) << std::setfill('0')
  7045. << static_cast<unsigned int>(hash[i]);
  7046. }
  7047. return ss.str();
  7048. }
  7049. } // namespace
  7050. inline std::string MD5(const std::string &s) {
  7051. unsigned char hash[16];
  7052. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7053. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7054. hash);
  7055. #else
  7056. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7057. hash);
  7058. #endif
  7059. return hash_to_hex(hash);
  7060. }
  7061. inline std::string SHA_256(const std::string &s) {
  7062. unsigned char hash[32];
  7063. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7064. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7065. hash, 0);
  7066. #else
  7067. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7068. s.size(), hash, 0);
  7069. #endif
  7070. return hash_to_hex(hash);
  7071. }
  7072. inline std::string SHA_512(const std::string &s) {
  7073. unsigned char hash[64];
  7074. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7075. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7076. hash, 0);
  7077. #else
  7078. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7079. s.size(), hash, 0);
  7080. #endif
  7081. return hash_to_hex(hash);
  7082. }
  7083. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7084. namespace {
  7085. template <size_t N>
  7086. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7087. std::stringstream ss;
  7088. for (size_t i = 0; i < N; ++i) {
  7089. ss << std::hex << std::setw(2) << std::setfill('0')
  7090. << static_cast<unsigned int>(hash[i]);
  7091. }
  7092. return ss.str();
  7093. }
  7094. } // namespace
  7095. inline std::string MD5(const std::string &s) {
  7096. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7097. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7098. static_cast<word32>(s.size()), hash);
  7099. return hash_to_hex(hash);
  7100. }
  7101. inline std::string SHA_256(const std::string &s) {
  7102. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7103. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7104. static_cast<word32>(s.size()), hash);
  7105. return hash_to_hex(hash);
  7106. }
  7107. inline std::string SHA_512(const std::string &s) {
  7108. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7109. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7110. static_cast<word32>(s.size()), hash);
  7111. return hash_to_hex(hash);
  7112. }
  7113. #endif
  7114. inline bool is_ip_address(const std::string &host) {
  7115. struct in_addr addr4;
  7116. struct in6_addr addr6;
  7117. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7118. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7119. }
  7120. template <typename T>
  7121. inline bool process_server_socket_ssl(
  7122. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7123. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7124. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7125. time_t write_timeout_usec, T callback) {
  7126. return process_server_socket_core(
  7127. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7128. [&](bool close_connection, bool &connection_closed) {
  7129. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7130. write_timeout_sec, write_timeout_usec);
  7131. return callback(strm, close_connection, connection_closed);
  7132. });
  7133. }
  7134. template <typename T>
  7135. inline bool process_client_socket_ssl(
  7136. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7137. time_t read_timeout_usec, time_t write_timeout_sec,
  7138. time_t write_timeout_usec, time_t max_timeout_msec,
  7139. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7140. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7141. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7142. start_time);
  7143. return callback(strm);
  7144. }
  7145. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7146. const Request &req, const std::map<std::string, std::string> &auth,
  7147. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7148. const std::string &password, bool is_proxy = false) {
  7149. std::string nc;
  7150. {
  7151. std::stringstream ss;
  7152. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7153. nc = ss.str();
  7154. }
  7155. std::string qop;
  7156. if (auth.find("qop") != auth.end()) {
  7157. qop = auth.at("qop");
  7158. if (qop.find("auth-int") != std::string::npos) {
  7159. qop = "auth-int";
  7160. } else if (qop.find("auth") != std::string::npos) {
  7161. qop = "auth";
  7162. } else {
  7163. qop.clear();
  7164. }
  7165. }
  7166. std::string algo = "MD5";
  7167. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7168. std::string response;
  7169. {
  7170. auto H = algo == "SHA-256" ? detail::SHA_256
  7171. : algo == "SHA-512" ? detail::SHA_512
  7172. : detail::MD5;
  7173. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7174. auto A2 = req.method + ":" + req.path;
  7175. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7176. if (qop.empty()) {
  7177. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7178. } else {
  7179. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7180. ":" + qop + ":" + H(A2));
  7181. }
  7182. }
  7183. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7184. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7185. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7186. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7187. (qop.empty() ? ", response=\""
  7188. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7189. cnonce + "\", response=\"") +
  7190. response + "\"" +
  7191. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7192. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7193. return std::make_pair(key, field);
  7194. }
  7195. inline bool match_hostname(const std::string &pattern,
  7196. const std::string &hostname) {
  7197. // Exact match (case-insensitive)
  7198. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7199. // Split both pattern and hostname into components by '.'
  7200. std::vector<std::string> pattern_components;
  7201. if (!pattern.empty()) {
  7202. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7203. [&](const char *b, const char *e) {
  7204. pattern_components.emplace_back(b, e);
  7205. });
  7206. }
  7207. std::vector<std::string> host_components;
  7208. if (!hostname.empty()) {
  7209. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7210. [&](const char *b, const char *e) {
  7211. host_components.emplace_back(b, e);
  7212. });
  7213. }
  7214. // Component count must match
  7215. if (host_components.size() != pattern_components.size()) { return false; }
  7216. // Compare each component with wildcard support
  7217. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7218. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7219. auto itr = pattern_components.begin();
  7220. for (const auto &h : host_components) {
  7221. auto &p = *itr;
  7222. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7223. bool partial_match = false;
  7224. if (!p.empty() && p[p.size() - 1] == '*') {
  7225. const auto prefix_length = p.size() - 1;
  7226. if (prefix_length == 0) {
  7227. partial_match = true;
  7228. } else if (h.size() >= prefix_length) {
  7229. partial_match =
  7230. std::equal(p.begin(),
  7231. p.begin() + static_cast<std::string::difference_type>(
  7232. prefix_length),
  7233. h.begin(), [](const char ca, const char cb) {
  7234. return detail::case_ignore::to_lower(ca) ==
  7235. detail::case_ignore::to_lower(cb);
  7236. });
  7237. }
  7238. }
  7239. if (!partial_match) { return false; }
  7240. }
  7241. ++itr;
  7242. }
  7243. return true;
  7244. }
  7245. #ifdef _WIN32
  7246. // Verify certificate using Windows CertGetCertificateChain API.
  7247. // This provides real-time certificate validation with Windows Update
  7248. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7249. inline bool verify_cert_with_windows_schannel(
  7250. const std::vector<unsigned char> &der_cert, const std::string &hostname,
  7251. bool verify_hostname, unsigned long &out_error) {
  7252. if (der_cert.empty()) { return false; }
  7253. out_error = 0;
  7254. // Create Windows certificate context from DER data
  7255. auto cert_context = CertCreateCertificateContext(
  7256. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7257. static_cast<DWORD>(der_cert.size()));
  7258. if (!cert_context) {
  7259. out_error = GetLastError();
  7260. return false;
  7261. }
  7262. auto cert_guard =
  7263. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7264. // Setup chain parameters
  7265. CERT_CHAIN_PARA chain_para = {};
  7266. chain_para.cbSize = sizeof(chain_para);
  7267. // Build certificate chain with revocation checking
  7268. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7269. auto chain_result = CertGetCertificateChain(
  7270. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7271. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7272. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7273. nullptr, &chain_context);
  7274. if (!chain_result || !chain_context) {
  7275. out_error = GetLastError();
  7276. return false;
  7277. }
  7278. auto chain_guard =
  7279. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7280. // Check if chain has errors
  7281. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7282. out_error = chain_context->TrustStatus.dwErrorStatus;
  7283. return false;
  7284. }
  7285. // Verify SSL policy
  7286. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7287. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7288. #ifdef AUTHTYPE_SERVER
  7289. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7290. #endif
  7291. std::wstring whost;
  7292. if (verify_hostname) {
  7293. whost = u8string_to_wstring(hostname.c_str());
  7294. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7295. }
  7296. CERT_CHAIN_POLICY_PARA policy_para = {};
  7297. policy_para.cbSize = sizeof(policy_para);
  7298. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7299. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7300. #else
  7301. policy_para.dwFlags = 0;
  7302. #endif
  7303. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7304. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7305. policy_status.cbSize = sizeof(policy_status);
  7306. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7307. &policy_para, &policy_status)) {
  7308. out_error = GetLastError();
  7309. return false;
  7310. }
  7311. if (policy_status.dwError != 0) {
  7312. out_error = policy_status.dwError;
  7313. return false;
  7314. }
  7315. return true;
  7316. }
  7317. #endif // _WIN32
  7318. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t &ctx,
  7319. tls::session_t &session, socket_t sock,
  7320. bool server_certificate_verification,
  7321. const std::string &ca_cert_file_path,
  7322. tls::ca_store_t ca_cert_store,
  7323. time_t timeout_sec, time_t timeout_usec) {
  7324. using namespace tls;
  7325. ctx = create_client_context();
  7326. if (!ctx) { return false; }
  7327. if (server_certificate_verification) {
  7328. if (!ca_cert_file_path.empty()) {
  7329. load_ca_file(ctx, ca_cert_file_path.c_str());
  7330. }
  7331. if (ca_cert_store) { set_ca_store(ctx, ca_cert_store); }
  7332. load_system_certs(ctx);
  7333. }
  7334. bool is_ip = is_ip_address(host);
  7335. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  7336. if (is_ip && server_certificate_verification) {
  7337. set_verify_client(ctx, false);
  7338. } else {
  7339. set_verify_client(ctx, server_certificate_verification);
  7340. }
  7341. #endif
  7342. session = create_session(ctx, sock);
  7343. if (!session) { return false; }
  7344. // RFC 6066: SNI must not be set for IP addresses
  7345. if (!is_ip) { set_sni(session, host.c_str()); }
  7346. if (server_certificate_verification) { set_hostname(session, host.c_str()); }
  7347. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7348. return false;
  7349. }
  7350. if (server_certificate_verification) {
  7351. if (get_verify_result(session) != 0) { return false; }
  7352. }
  7353. return true;
  7354. }
  7355. } // namespace detail
  7356. #endif // CPPHTTPLIB_SSL_ENABLED
  7357. /*
  7358. * Group 3: httplib namespace - Non-SSL public API implementations
  7359. */
  7360. inline void default_socket_options(socket_t sock) {
  7361. detail::set_socket_opt(sock, SOL_SOCKET,
  7362. #ifdef SO_REUSEPORT
  7363. SO_REUSEPORT,
  7364. #else
  7365. SO_REUSEADDR,
  7366. #endif
  7367. 1);
  7368. }
  7369. inline std::string get_bearer_token_auth(const Request &req) {
  7370. if (req.has_header("Authorization")) {
  7371. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7372. return req.get_header_value("Authorization")
  7373. .substr(bearer_header_prefix_len);
  7374. }
  7375. return "";
  7376. }
  7377. inline const char *status_message(int status) {
  7378. switch (status) {
  7379. case StatusCode::Continue_100: return "Continue";
  7380. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7381. case StatusCode::Processing_102: return "Processing";
  7382. case StatusCode::EarlyHints_103: return "Early Hints";
  7383. case StatusCode::OK_200: return "OK";
  7384. case StatusCode::Created_201: return "Created";
  7385. case StatusCode::Accepted_202: return "Accepted";
  7386. case StatusCode::NonAuthoritativeInformation_203:
  7387. return "Non-Authoritative Information";
  7388. case StatusCode::NoContent_204: return "No Content";
  7389. case StatusCode::ResetContent_205: return "Reset Content";
  7390. case StatusCode::PartialContent_206: return "Partial Content";
  7391. case StatusCode::MultiStatus_207: return "Multi-Status";
  7392. case StatusCode::AlreadyReported_208: return "Already Reported";
  7393. case StatusCode::IMUsed_226: return "IM Used";
  7394. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7395. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7396. case StatusCode::Found_302: return "Found";
  7397. case StatusCode::SeeOther_303: return "See Other";
  7398. case StatusCode::NotModified_304: return "Not Modified";
  7399. case StatusCode::UseProxy_305: return "Use Proxy";
  7400. case StatusCode::unused_306: return "unused";
  7401. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7402. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7403. case StatusCode::BadRequest_400: return "Bad Request";
  7404. case StatusCode::Unauthorized_401: return "Unauthorized";
  7405. case StatusCode::PaymentRequired_402: return "Payment Required";
  7406. case StatusCode::Forbidden_403: return "Forbidden";
  7407. case StatusCode::NotFound_404: return "Not Found";
  7408. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7409. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7410. case StatusCode::ProxyAuthenticationRequired_407:
  7411. return "Proxy Authentication Required";
  7412. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7413. case StatusCode::Conflict_409: return "Conflict";
  7414. case StatusCode::Gone_410: return "Gone";
  7415. case StatusCode::LengthRequired_411: return "Length Required";
  7416. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7417. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7418. case StatusCode::UriTooLong_414: return "URI Too Long";
  7419. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7420. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7421. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7422. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7423. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7424. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7425. case StatusCode::Locked_423: return "Locked";
  7426. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7427. case StatusCode::TooEarly_425: return "Too Early";
  7428. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7429. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7430. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7431. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7432. return "Request Header Fields Too Large";
  7433. case StatusCode::UnavailableForLegalReasons_451:
  7434. return "Unavailable For Legal Reasons";
  7435. case StatusCode::NotImplemented_501: return "Not Implemented";
  7436. case StatusCode::BadGateway_502: return "Bad Gateway";
  7437. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  7438. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  7439. case StatusCode::HttpVersionNotSupported_505:
  7440. return "HTTP Version Not Supported";
  7441. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  7442. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  7443. case StatusCode::LoopDetected_508: return "Loop Detected";
  7444. case StatusCode::NotExtended_510: return "Not Extended";
  7445. case StatusCode::NetworkAuthenticationRequired_511:
  7446. return "Network Authentication Required";
  7447. default:
  7448. case StatusCode::InternalServerError_500: return "Internal Server Error";
  7449. }
  7450. }
  7451. inline std::string to_string(const Error error) {
  7452. switch (error) {
  7453. case Error::Success: return "Success (no error)";
  7454. case Error::Unknown: return "Unknown";
  7455. case Error::Connection: return "Could not establish connection";
  7456. case Error::BindIPAddress: return "Failed to bind IP address";
  7457. case Error::Read: return "Failed to read connection";
  7458. case Error::Write: return "Failed to write connection";
  7459. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  7460. case Error::Canceled: return "Connection handling canceled";
  7461. case Error::SSLConnection: return "SSL connection failed";
  7462. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  7463. case Error::SSLServerVerification: return "SSL server verification failed";
  7464. case Error::SSLServerHostnameVerification:
  7465. return "SSL server hostname verification failed";
  7466. case Error::UnsupportedMultipartBoundaryChars:
  7467. return "Unsupported HTTP multipart boundary characters";
  7468. case Error::Compression: return "Compression failed";
  7469. case Error::ConnectionTimeout: return "Connection timed out";
  7470. case Error::ProxyConnection: return "Proxy connection failed";
  7471. case Error::ConnectionClosed: return "Connection closed by server";
  7472. case Error::Timeout: return "Read timeout";
  7473. case Error::ResourceExhaustion: return "Resource exhaustion";
  7474. case Error::TooManyFormDataFiles: return "Too many form data files";
  7475. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  7476. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  7477. case Error::ExceedMaxSocketDescriptorCount:
  7478. return "Exceeded maximum socket descriptor count";
  7479. case Error::InvalidRequestLine: return "Invalid request line";
  7480. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  7481. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  7482. case Error::InvalidHeaders: return "Invalid headers";
  7483. case Error::MultipartParsing: return "Multipart parsing failed";
  7484. case Error::OpenFile: return "Failed to open file";
  7485. case Error::Listen: return "Failed to listen on socket";
  7486. case Error::GetSockName: return "Failed to get socket name";
  7487. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  7488. case Error::HTTPParsing: return "HTTP parsing failed";
  7489. case Error::InvalidRangeHeader: return "Invalid Range header";
  7490. default: break;
  7491. }
  7492. return "Invalid";
  7493. }
  7494. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  7495. os << to_string(obj);
  7496. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  7497. return os;
  7498. }
  7499. inline std::string hosted_at(const std::string &hostname) {
  7500. std::vector<std::string> addrs;
  7501. hosted_at(hostname, addrs);
  7502. if (addrs.empty()) { return std::string(); }
  7503. return addrs[0];
  7504. }
  7505. inline void hosted_at(const std::string &hostname,
  7506. std::vector<std::string> &addrs) {
  7507. struct addrinfo hints;
  7508. struct addrinfo *result;
  7509. memset(&hints, 0, sizeof(struct addrinfo));
  7510. hints.ai_family = AF_UNSPEC;
  7511. hints.ai_socktype = SOCK_STREAM;
  7512. hints.ai_protocol = 0;
  7513. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  7514. &result, 0)) {
  7515. #if defined __linux__ && !defined __ANDROID__
  7516. res_init();
  7517. #endif
  7518. return;
  7519. }
  7520. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  7521. for (auto rp = result; rp; rp = rp->ai_next) {
  7522. const auto &addr =
  7523. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  7524. std::string ip;
  7525. auto dummy = -1;
  7526. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  7527. dummy)) {
  7528. addrs.emplace_back(std::move(ip));
  7529. }
  7530. }
  7531. }
  7532. inline std::string encode_uri_component(const std::string &value) {
  7533. std::ostringstream escaped;
  7534. escaped.fill('0');
  7535. escaped << std::hex;
  7536. for (auto c : value) {
  7537. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  7538. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  7539. c == ')') {
  7540. escaped << c;
  7541. } else {
  7542. escaped << std::uppercase;
  7543. escaped << '%' << std::setw(2)
  7544. << static_cast<int>(static_cast<unsigned char>(c));
  7545. escaped << std::nouppercase;
  7546. }
  7547. }
  7548. return escaped.str();
  7549. }
  7550. inline std::string encode_uri(const std::string &value) {
  7551. std::ostringstream escaped;
  7552. escaped.fill('0');
  7553. escaped << std::hex;
  7554. for (auto c : value) {
  7555. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  7556. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  7557. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  7558. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  7559. escaped << c;
  7560. } else {
  7561. escaped << std::uppercase;
  7562. escaped << '%' << std::setw(2)
  7563. << static_cast<int>(static_cast<unsigned char>(c));
  7564. escaped << std::nouppercase;
  7565. }
  7566. }
  7567. return escaped.str();
  7568. }
  7569. inline std::string decode_uri_component(const std::string &value) {
  7570. std::string result;
  7571. for (size_t i = 0; i < value.size(); i++) {
  7572. if (value[i] == '%' && i + 2 < value.size()) {
  7573. auto val = 0;
  7574. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  7575. result += static_cast<char>(val);
  7576. i += 2;
  7577. } else {
  7578. result += value[i];
  7579. }
  7580. } else {
  7581. result += value[i];
  7582. }
  7583. }
  7584. return result;
  7585. }
  7586. inline std::string decode_uri(const std::string &value) {
  7587. std::string result;
  7588. for (size_t i = 0; i < value.size(); i++) {
  7589. if (value[i] == '%' && i + 2 < value.size()) {
  7590. auto val = 0;
  7591. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  7592. result += static_cast<char>(val);
  7593. i += 2;
  7594. } else {
  7595. result += value[i];
  7596. }
  7597. } else {
  7598. result += value[i];
  7599. }
  7600. }
  7601. return result;
  7602. }
  7603. inline std::string encode_path_component(const std::string &component) {
  7604. std::string result;
  7605. result.reserve(component.size() * 3);
  7606. for (size_t i = 0; i < component.size(); i++) {
  7607. auto c = static_cast<unsigned char>(component[i]);
  7608. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  7609. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  7610. result += static_cast<char>(c);
  7611. }
  7612. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  7613. // "," / ";" / "="
  7614. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  7615. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  7616. c == '=') {
  7617. result += static_cast<char>(c);
  7618. }
  7619. // Colon is allowed in path segments except first segment
  7620. else if (c == ':') {
  7621. result += static_cast<char>(c);
  7622. }
  7623. // @ is allowed in path
  7624. else if (c == '@') {
  7625. result += static_cast<char>(c);
  7626. } else {
  7627. result += '%';
  7628. char hex[3];
  7629. snprintf(hex, sizeof(hex), "%02X", c);
  7630. result.append(hex, 2);
  7631. }
  7632. }
  7633. return result;
  7634. }
  7635. inline std::string decode_path_component(const std::string &component) {
  7636. std::string result;
  7637. result.reserve(component.size());
  7638. for (size_t i = 0; i < component.size(); i++) {
  7639. if (component[i] == '%' && i + 1 < component.size()) {
  7640. if (component[i + 1] == 'u') {
  7641. // Unicode %uXXXX encoding
  7642. auto val = 0;
  7643. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  7644. // 4 digits Unicode codes
  7645. char buff[4];
  7646. size_t len = detail::to_utf8(val, buff);
  7647. if (len > 0) { result.append(buff, len); }
  7648. i += 5; // 'u0000'
  7649. } else {
  7650. result += component[i];
  7651. }
  7652. } else {
  7653. // Standard %XX encoding
  7654. auto val = 0;
  7655. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  7656. // 2 digits hex codes
  7657. result += static_cast<char>(val);
  7658. i += 2; // 'XX'
  7659. } else {
  7660. result += component[i];
  7661. }
  7662. }
  7663. } else {
  7664. result += component[i];
  7665. }
  7666. }
  7667. return result;
  7668. }
  7669. inline std::string encode_query_component(const std::string &component,
  7670. bool space_as_plus) {
  7671. std::string result;
  7672. result.reserve(component.size() * 3);
  7673. for (size_t i = 0; i < component.size(); i++) {
  7674. auto c = static_cast<unsigned char>(component[i]);
  7675. // Unreserved characters per RFC 3986
  7676. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  7677. result += static_cast<char>(c);
  7678. }
  7679. // Space handling
  7680. else if (c == ' ') {
  7681. if (space_as_plus) {
  7682. result += '+';
  7683. } else {
  7684. result += "%20";
  7685. }
  7686. }
  7687. // Plus sign handling
  7688. else if (c == '+') {
  7689. if (space_as_plus) {
  7690. result += "%2B";
  7691. } else {
  7692. result += static_cast<char>(c);
  7693. }
  7694. }
  7695. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  7696. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  7697. c == '*' || c == ',' || c == ';') {
  7698. result += static_cast<char>(c);
  7699. }
  7700. // Colon and @ are allowed in query
  7701. else if (c == ':' || c == '@') {
  7702. result += static_cast<char>(c);
  7703. }
  7704. // Forward slash is allowed in query values
  7705. else if (c == '/') {
  7706. result += static_cast<char>(c);
  7707. }
  7708. // Question mark is allowed in query values (after first ?)
  7709. else if (c == '?') {
  7710. result += static_cast<char>(c);
  7711. } else {
  7712. result += '%';
  7713. char hex[3];
  7714. snprintf(hex, sizeof(hex), "%02X", c);
  7715. result.append(hex, 2);
  7716. }
  7717. }
  7718. return result;
  7719. }
  7720. inline std::string decode_query_component(const std::string &component,
  7721. bool plus_as_space) {
  7722. std::string result;
  7723. result.reserve(component.size());
  7724. for (size_t i = 0; i < component.size(); i++) {
  7725. if (component[i] == '%' && i + 2 < component.size()) {
  7726. std::string hex = component.substr(i + 1, 2);
  7727. char *end;
  7728. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  7729. if (end == hex.c_str() + 2) {
  7730. result += static_cast<char>(value);
  7731. i += 2;
  7732. } else {
  7733. result += component[i];
  7734. }
  7735. } else if (component[i] == '+' && plus_as_space) {
  7736. result += ' '; // + becomes space in form-urlencoded
  7737. } else {
  7738. result += component[i];
  7739. }
  7740. }
  7741. return result;
  7742. }
  7743. inline std::string append_query_params(const std::string &path,
  7744. const Params &params) {
  7745. std::string path_with_query = path;
  7746. thread_local const std::regex re("[^?]+\\?.*");
  7747. auto delm = std::regex_match(path, re) ? '&' : '?';
  7748. path_with_query += delm + detail::params_to_query_str(params);
  7749. return path_with_query;
  7750. }
  7751. // Header utilities
  7752. inline std::pair<std::string, std::string>
  7753. make_range_header(const Ranges &ranges) {
  7754. std::string field = "bytes=";
  7755. auto i = 0;
  7756. for (const auto &r : ranges) {
  7757. if (i != 0) { field += ", "; }
  7758. if (r.first != -1) { field += std::to_string(r.first); }
  7759. field += '-';
  7760. if (r.second != -1) { field += std::to_string(r.second); }
  7761. i++;
  7762. }
  7763. return std::make_pair("Range", std::move(field));
  7764. }
  7765. inline std::pair<std::string, std::string>
  7766. make_basic_authentication_header(const std::string &username,
  7767. const std::string &password, bool is_proxy) {
  7768. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  7769. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7770. return std::make_pair(key, std::move(field));
  7771. }
  7772. inline std::pair<std::string, std::string>
  7773. make_bearer_token_authentication_header(const std::string &token,
  7774. bool is_proxy = false) {
  7775. auto field = "Bearer " + token;
  7776. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7777. return std::make_pair(key, std::move(field));
  7778. }
  7779. // Request implementation
  7780. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  7781. size_t id) const {
  7782. return detail::get_header_value_u64(headers, key, def, id);
  7783. }
  7784. inline bool Request::has_header(const std::string &key) const {
  7785. return detail::has_header(headers, key);
  7786. }
  7787. inline std::string Request::get_header_value(const std::string &key,
  7788. const char *def, size_t id) const {
  7789. return detail::get_header_value(headers, key, def, id);
  7790. }
  7791. inline size_t Request::get_header_value_count(const std::string &key) const {
  7792. auto r = headers.equal_range(key);
  7793. return static_cast<size_t>(std::distance(r.first, r.second));
  7794. }
  7795. inline void Request::set_header(const std::string &key,
  7796. const std::string &val) {
  7797. if (detail::fields::is_field_name(key) &&
  7798. detail::fields::is_field_value(val)) {
  7799. headers.emplace(key, val);
  7800. }
  7801. }
  7802. inline bool Request::has_trailer(const std::string &key) const {
  7803. return trailers.find(key) != trailers.end();
  7804. }
  7805. inline std::string Request::get_trailer_value(const std::string &key,
  7806. size_t id) const {
  7807. auto rng = trailers.equal_range(key);
  7808. auto it = rng.first;
  7809. std::advance(it, static_cast<ssize_t>(id));
  7810. if (it != rng.second) { return it->second; }
  7811. return std::string();
  7812. }
  7813. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  7814. auto r = trailers.equal_range(key);
  7815. return static_cast<size_t>(std::distance(r.first, r.second));
  7816. }
  7817. inline bool Request::has_param(const std::string &key) const {
  7818. return params.find(key) != params.end();
  7819. }
  7820. inline std::string Request::get_param_value(const std::string &key,
  7821. size_t id) const {
  7822. auto rng = params.equal_range(key);
  7823. auto it = rng.first;
  7824. std::advance(it, static_cast<ssize_t>(id));
  7825. if (it != rng.second) { return it->second; }
  7826. return std::string();
  7827. }
  7828. inline size_t Request::get_param_value_count(const std::string &key) const {
  7829. auto r = params.equal_range(key);
  7830. return static_cast<size_t>(std::distance(r.first, r.second));
  7831. }
  7832. inline bool Request::is_multipart_form_data() const {
  7833. const auto &content_type = get_header_value("Content-Type");
  7834. return !content_type.rfind("multipart/form-data", 0);
  7835. }
  7836. // Multipart FormData implementation
  7837. inline std::string MultipartFormData::get_field(const std::string &key,
  7838. size_t id) const {
  7839. auto rng = fields.equal_range(key);
  7840. auto it = rng.first;
  7841. std::advance(it, static_cast<ssize_t>(id));
  7842. if (it != rng.second) { return it->second.content; }
  7843. return std::string();
  7844. }
  7845. inline std::vector<std::string>
  7846. MultipartFormData::get_fields(const std::string &key) const {
  7847. std::vector<std::string> values;
  7848. auto rng = fields.equal_range(key);
  7849. for (auto it = rng.first; it != rng.second; it++) {
  7850. values.push_back(it->second.content);
  7851. }
  7852. return values;
  7853. }
  7854. inline bool MultipartFormData::has_field(const std::string &key) const {
  7855. return fields.find(key) != fields.end();
  7856. }
  7857. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  7858. auto r = fields.equal_range(key);
  7859. return static_cast<size_t>(std::distance(r.first, r.second));
  7860. }
  7861. inline FormData MultipartFormData::get_file(const std::string &key,
  7862. size_t id) const {
  7863. auto rng = files.equal_range(key);
  7864. auto it = rng.first;
  7865. std::advance(it, static_cast<ssize_t>(id));
  7866. if (it != rng.second) { return it->second; }
  7867. return FormData();
  7868. }
  7869. inline std::vector<FormData>
  7870. MultipartFormData::get_files(const std::string &key) const {
  7871. std::vector<FormData> values;
  7872. auto rng = files.equal_range(key);
  7873. for (auto it = rng.first; it != rng.second; it++) {
  7874. values.push_back(it->second);
  7875. }
  7876. return values;
  7877. }
  7878. inline bool MultipartFormData::has_file(const std::string &key) const {
  7879. return files.find(key) != files.end();
  7880. }
  7881. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  7882. auto r = files.equal_range(key);
  7883. return static_cast<size_t>(std::distance(r.first, r.second));
  7884. }
  7885. // Response implementation
  7886. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  7887. size_t id) const {
  7888. return detail::get_header_value_u64(headers, key, def, id);
  7889. }
  7890. inline bool Response::has_header(const std::string &key) const {
  7891. return headers.find(key) != headers.end();
  7892. }
  7893. inline std::string Response::get_header_value(const std::string &key,
  7894. const char *def,
  7895. size_t id) const {
  7896. return detail::get_header_value(headers, key, def, id);
  7897. }
  7898. inline size_t Response::get_header_value_count(const std::string &key) const {
  7899. auto r = headers.equal_range(key);
  7900. return static_cast<size_t>(std::distance(r.first, r.second));
  7901. }
  7902. inline void Response::set_header(const std::string &key,
  7903. const std::string &val) {
  7904. if (detail::fields::is_field_name(key) &&
  7905. detail::fields::is_field_value(val)) {
  7906. headers.emplace(key, val);
  7907. }
  7908. }
  7909. inline bool Response::has_trailer(const std::string &key) const {
  7910. return trailers.find(key) != trailers.end();
  7911. }
  7912. inline std::string Response::get_trailer_value(const std::string &key,
  7913. size_t id) const {
  7914. auto rng = trailers.equal_range(key);
  7915. auto it = rng.first;
  7916. std::advance(it, static_cast<ssize_t>(id));
  7917. if (it != rng.second) { return it->second; }
  7918. return std::string();
  7919. }
  7920. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  7921. auto r = trailers.equal_range(key);
  7922. return static_cast<size_t>(std::distance(r.first, r.second));
  7923. }
  7924. inline void Response::set_redirect(const std::string &url, int stat) {
  7925. if (detail::fields::is_field_value(url)) {
  7926. set_header("Location", url);
  7927. if (300 <= stat && stat < 400) {
  7928. this->status = stat;
  7929. } else {
  7930. this->status = StatusCode::Found_302;
  7931. }
  7932. }
  7933. }
  7934. inline void Response::set_content(const char *s, size_t n,
  7935. const std::string &content_type) {
  7936. body.assign(s, n);
  7937. auto rng = headers.equal_range("Content-Type");
  7938. headers.erase(rng.first, rng.second);
  7939. set_header("Content-Type", content_type);
  7940. }
  7941. inline void Response::set_content(const std::string &s,
  7942. const std::string &content_type) {
  7943. set_content(s.data(), s.size(), content_type);
  7944. }
  7945. inline void Response::set_content(std::string &&s,
  7946. const std::string &content_type) {
  7947. body = std::move(s);
  7948. auto rng = headers.equal_range("Content-Type");
  7949. headers.erase(rng.first, rng.second);
  7950. set_header("Content-Type", content_type);
  7951. }
  7952. inline void Response::set_content_provider(
  7953. size_t in_length, const std::string &content_type, ContentProvider provider,
  7954. ContentProviderResourceReleaser resource_releaser) {
  7955. set_header("Content-Type", content_type);
  7956. content_length_ = in_length;
  7957. if (in_length > 0) { content_provider_ = std::move(provider); }
  7958. content_provider_resource_releaser_ = std::move(resource_releaser);
  7959. is_chunked_content_provider_ = false;
  7960. }
  7961. inline void Response::set_content_provider(
  7962. const std::string &content_type, ContentProviderWithoutLength provider,
  7963. ContentProviderResourceReleaser resource_releaser) {
  7964. set_header("Content-Type", content_type);
  7965. content_length_ = 0;
  7966. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  7967. content_provider_resource_releaser_ = std::move(resource_releaser);
  7968. is_chunked_content_provider_ = false;
  7969. }
  7970. inline void Response::set_chunked_content_provider(
  7971. const std::string &content_type, ContentProviderWithoutLength provider,
  7972. ContentProviderResourceReleaser resource_releaser) {
  7973. set_header("Content-Type", content_type);
  7974. content_length_ = 0;
  7975. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  7976. content_provider_resource_releaser_ = std::move(resource_releaser);
  7977. is_chunked_content_provider_ = true;
  7978. }
  7979. inline void Response::set_file_content(const std::string &path,
  7980. const std::string &content_type) {
  7981. file_content_path_ = path;
  7982. file_content_content_type_ = content_type;
  7983. }
  7984. inline void Response::set_file_content(const std::string &path) {
  7985. file_content_path_ = path;
  7986. }
  7987. // Result implementation
  7988. inline size_t Result::get_request_header_value_u64(const std::string &key,
  7989. size_t def,
  7990. size_t id) const {
  7991. return detail::get_header_value_u64(request_headers_, key, def, id);
  7992. }
  7993. inline bool Result::has_request_header(const std::string &key) const {
  7994. return request_headers_.find(key) != request_headers_.end();
  7995. }
  7996. inline std::string Result::get_request_header_value(const std::string &key,
  7997. const char *def,
  7998. size_t id) const {
  7999. return detail::get_header_value(request_headers_, key, def, id);
  8000. }
  8001. inline size_t
  8002. Result::get_request_header_value_count(const std::string &key) const {
  8003. auto r = request_headers_.equal_range(key);
  8004. return static_cast<size_t>(std::distance(r.first, r.second));
  8005. }
  8006. // Stream implementation
  8007. inline ssize_t Stream::write(const char *ptr) {
  8008. return write(ptr, strlen(ptr));
  8009. }
  8010. inline ssize_t Stream::write(const std::string &s) {
  8011. return write(s.data(), s.size());
  8012. }
  8013. // BodyReader implementation
  8014. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8015. if (!stream) {
  8016. last_error = Error::Connection;
  8017. return -1;
  8018. }
  8019. if (eof) { return 0; }
  8020. if (!chunked) {
  8021. // Content-Length based reading
  8022. if (has_content_length && bytes_read >= content_length) {
  8023. eof = true;
  8024. return 0;
  8025. }
  8026. auto to_read = len;
  8027. if (has_content_length) {
  8028. auto remaining = content_length - bytes_read;
  8029. to_read = (std::min)(len, remaining);
  8030. }
  8031. auto n = stream->read(buf, to_read);
  8032. if (n < 0) {
  8033. last_error = stream->get_error();
  8034. if (last_error == Error::Success) { last_error = Error::Read; }
  8035. eof = true;
  8036. return n;
  8037. }
  8038. if (n == 0) {
  8039. // Unexpected EOF before content_length
  8040. last_error = stream->get_error();
  8041. if (last_error == Error::Success) { last_error = Error::Read; }
  8042. eof = true;
  8043. return 0;
  8044. }
  8045. bytes_read += static_cast<size_t>(n);
  8046. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8047. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8048. last_error = Error::ExceedMaxPayloadSize;
  8049. eof = true;
  8050. return -1;
  8051. }
  8052. return n;
  8053. }
  8054. // Chunked transfer encoding: delegate to shared decoder instance.
  8055. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8056. size_t chunk_offset = 0;
  8057. size_t chunk_total = 0;
  8058. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8059. if (n < 0) {
  8060. last_error = stream->get_error();
  8061. if (last_error == Error::Success) { last_error = Error::Read; }
  8062. eof = true;
  8063. return n;
  8064. }
  8065. if (n == 0) {
  8066. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8067. eof = true;
  8068. return 0;
  8069. }
  8070. bytes_read += static_cast<size_t>(n);
  8071. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8072. last_error = Error::ExceedMaxPayloadSize;
  8073. eof = true;
  8074. return -1;
  8075. }
  8076. return n;
  8077. }
  8078. // ThreadPool implementation
  8079. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr)
  8080. : base_thread_count_(n), max_queued_requests_(mqr), idle_thread_count_(0),
  8081. shutdown_(false) {
  8082. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8083. if (max_n != 0 && max_n < n) {
  8084. std::string msg = "max_threads must be >= base_threads";
  8085. throw std::invalid_argument(msg);
  8086. }
  8087. #endif
  8088. max_thread_count_ = max_n == 0 ? n : max_n;
  8089. threads_.reserve(base_thread_count_);
  8090. for (size_t i = 0; i < base_thread_count_; i++) {
  8091. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8092. }
  8093. }
  8094. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8095. {
  8096. std::unique_lock<std::mutex> lock(mutex_);
  8097. if (shutdown_) { return false; }
  8098. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8099. return false;
  8100. }
  8101. jobs_.push_back(std::move(fn));
  8102. // Spawn a dynamic thread if no idle threads and under max
  8103. if (idle_thread_count_ == 0 &&
  8104. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8105. cleanup_finished_threads();
  8106. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8107. }
  8108. }
  8109. cond_.notify_one();
  8110. return true;
  8111. }
  8112. inline void ThreadPool::shutdown() {
  8113. {
  8114. std::unique_lock<std::mutex> lock(mutex_);
  8115. shutdown_ = true;
  8116. }
  8117. cond_.notify_all();
  8118. for (auto &t : threads_) {
  8119. if (t.joinable()) { t.join(); }
  8120. }
  8121. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8122. // with worker threads that call move_to_finished() concurrently.
  8123. std::list<std::thread> remaining_dynamic;
  8124. {
  8125. std::unique_lock<std::mutex> lock(mutex_);
  8126. remaining_dynamic = std::move(dynamic_threads_);
  8127. }
  8128. for (auto &t : remaining_dynamic) {
  8129. if (t.joinable()) { t.join(); }
  8130. }
  8131. std::unique_lock<std::mutex> lock(mutex_);
  8132. cleanup_finished_threads();
  8133. }
  8134. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8135. // Must be called with mutex_ held
  8136. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8137. if (it->get_id() == id) {
  8138. finished_threads_.push_back(std::move(*it));
  8139. dynamic_threads_.erase(it);
  8140. return;
  8141. }
  8142. }
  8143. }
  8144. inline void ThreadPool::cleanup_finished_threads() {
  8145. // Must be called with mutex_ held
  8146. for (auto &t : finished_threads_) {
  8147. if (t.joinable()) { t.join(); }
  8148. }
  8149. finished_threads_.clear();
  8150. }
  8151. inline void ThreadPool::worker(bool is_dynamic) {
  8152. for (;;) {
  8153. std::function<void()> fn;
  8154. {
  8155. std::unique_lock<std::mutex> lock(mutex_);
  8156. idle_thread_count_++;
  8157. if (is_dynamic) {
  8158. auto has_work = cond_.wait_for(
  8159. lock, std::chrono::seconds(CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT),
  8160. [&] { return !jobs_.empty() || shutdown_; });
  8161. if (!has_work) {
  8162. // Timed out with no work - exit this dynamic thread
  8163. idle_thread_count_--;
  8164. move_to_finished(std::this_thread::get_id());
  8165. break;
  8166. }
  8167. } else {
  8168. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8169. }
  8170. idle_thread_count_--;
  8171. if (shutdown_ && jobs_.empty()) { break; }
  8172. fn = std::move(jobs_.front());
  8173. jobs_.pop_front();
  8174. }
  8175. assert(true == static_cast<bool>(fn));
  8176. fn();
  8177. // Dynamic thread: exit if queue is empty after task completion
  8178. if (is_dynamic) {
  8179. std::unique_lock<std::mutex> lock(mutex_);
  8180. if (jobs_.empty()) {
  8181. move_to_finished(std::this_thread::get_id());
  8182. break;
  8183. }
  8184. }
  8185. }
  8186. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8187. !defined(LIBRESSL_VERSION_NUMBER)
  8188. OPENSSL_thread_stop();
  8189. #endif
  8190. }
  8191. /*
  8192. * Group 1 (continued): detail namespace - Stream implementations
  8193. */
  8194. namespace detail {
  8195. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8196. time_t timeout_sec, time_t timeout_usec,
  8197. time_t &actual_timeout_sec,
  8198. time_t &actual_timeout_usec) {
  8199. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8200. auto actual_timeout_msec =
  8201. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8202. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8203. actual_timeout_sec = actual_timeout_msec / 1000;
  8204. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8205. }
  8206. // Socket stream implementation
  8207. inline SocketStream::SocketStream(
  8208. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8209. time_t write_timeout_sec, time_t write_timeout_usec,
  8210. time_t max_timeout_msec,
  8211. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8212. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8213. read_timeout_usec_(read_timeout_usec),
  8214. write_timeout_sec_(write_timeout_sec),
  8215. write_timeout_usec_(write_timeout_usec),
  8216. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8217. read_buff_(read_buff_size_, 0) {}
  8218. inline SocketStream::~SocketStream() = default;
  8219. inline bool SocketStream::is_readable() const {
  8220. return read_buff_off_ < read_buff_content_size_;
  8221. }
  8222. inline bool SocketStream::wait_readable() const {
  8223. if (max_timeout_msec_ <= 0) {
  8224. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8225. }
  8226. time_t read_timeout_sec;
  8227. time_t read_timeout_usec;
  8228. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8229. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8230. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8231. }
  8232. inline bool SocketStream::wait_writable() const {
  8233. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8234. }
  8235. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8236. #ifdef _WIN32
  8237. size =
  8238. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8239. #else
  8240. size = (std::min)(size,
  8241. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8242. #endif
  8243. if (read_buff_off_ < read_buff_content_size_) {
  8244. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8245. if (size <= remaining_size) {
  8246. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8247. read_buff_off_ += size;
  8248. return static_cast<ssize_t>(size);
  8249. } else {
  8250. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8251. read_buff_off_ += remaining_size;
  8252. return static_cast<ssize_t>(remaining_size);
  8253. }
  8254. }
  8255. if (!wait_readable()) {
  8256. error_ = Error::Timeout;
  8257. return -1;
  8258. }
  8259. read_buff_off_ = 0;
  8260. read_buff_content_size_ = 0;
  8261. if (size < read_buff_size_) {
  8262. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8263. CPPHTTPLIB_RECV_FLAGS);
  8264. if (n <= 0) {
  8265. if (n == 0) {
  8266. error_ = Error::ConnectionClosed;
  8267. } else {
  8268. error_ = Error::Read;
  8269. }
  8270. return n;
  8271. } else if (n <= static_cast<ssize_t>(size)) {
  8272. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8273. return n;
  8274. } else {
  8275. memcpy(ptr, read_buff_.data(), size);
  8276. read_buff_off_ = size;
  8277. read_buff_content_size_ = static_cast<size_t>(n);
  8278. return static_cast<ssize_t>(size);
  8279. }
  8280. } else {
  8281. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8282. if (n <= 0) {
  8283. if (n == 0) {
  8284. error_ = Error::ConnectionClosed;
  8285. } else {
  8286. error_ = Error::Read;
  8287. }
  8288. }
  8289. return n;
  8290. }
  8291. }
  8292. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8293. if (!wait_writable()) { return -1; }
  8294. #if defined(_WIN32) && !defined(_WIN64)
  8295. size =
  8296. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8297. #endif
  8298. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8299. }
  8300. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8301. int &port) const {
  8302. return detail::get_remote_ip_and_port(sock_, ip, port);
  8303. }
  8304. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8305. int &port) const {
  8306. return detail::get_local_ip_and_port(sock_, ip, port);
  8307. }
  8308. inline socket_t SocketStream::socket() const { return sock_; }
  8309. inline time_t SocketStream::duration() const {
  8310. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8311. std::chrono::steady_clock::now() - start_time_)
  8312. .count();
  8313. }
  8314. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8315. read_timeout_sec_ = sec;
  8316. read_timeout_usec_ = usec;
  8317. }
  8318. // Buffer stream implementation
  8319. inline bool BufferStream::is_readable() const { return true; }
  8320. inline bool BufferStream::wait_readable() const { return true; }
  8321. inline bool BufferStream::wait_writable() const { return true; }
  8322. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8323. #if defined(_MSC_VER) && _MSC_VER < 1910
  8324. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8325. #else
  8326. auto len_read = buffer.copy(ptr, size, position);
  8327. #endif
  8328. position += static_cast<size_t>(len_read);
  8329. return static_cast<ssize_t>(len_read);
  8330. }
  8331. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8332. buffer.append(ptr, size);
  8333. return static_cast<ssize_t>(size);
  8334. }
  8335. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8336. int & /*port*/) const {}
  8337. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8338. int & /*port*/) const {}
  8339. inline socket_t BufferStream::socket() const { return 0; }
  8340. inline time_t BufferStream::duration() const { return 0; }
  8341. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8342. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8343. : MatcherBase(pattern) {
  8344. constexpr const char marker[] = "/:";
  8345. // One past the last ending position of a path param substring
  8346. std::size_t last_param_end = 0;
  8347. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8348. // Needed to ensure that parameter names are unique during matcher
  8349. // construction
  8350. // If exceptions are disabled, only last duplicate path
  8351. // parameter will be set
  8352. std::unordered_set<std::string> param_name_set;
  8353. #endif
  8354. while (true) {
  8355. const auto marker_pos = pattern.find(
  8356. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8357. if (marker_pos == std::string::npos) { break; }
  8358. static_fragments_.push_back(
  8359. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8360. const auto param_name_start = marker_pos + str_len(marker);
  8361. auto sep_pos = pattern.find(separator, param_name_start);
  8362. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8363. auto param_name =
  8364. pattern.substr(param_name_start, sep_pos - param_name_start);
  8365. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8366. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8367. std::string msg = "Encountered path parameter '" + param_name +
  8368. "' multiple times in route pattern '" + pattern + "'.";
  8369. throw std::invalid_argument(msg);
  8370. }
  8371. #endif
  8372. param_names_.push_back(std::move(param_name));
  8373. last_param_end = sep_pos + 1;
  8374. }
  8375. if (last_param_end < pattern.length()) {
  8376. static_fragments_.push_back(pattern.substr(last_param_end));
  8377. }
  8378. }
  8379. inline bool PathParamsMatcher::match(Request &request) const {
  8380. request.matches = std::smatch();
  8381. request.path_params.clear();
  8382. request.path_params.reserve(param_names_.size());
  8383. // One past the position at which the path matched the pattern last time
  8384. std::size_t starting_pos = 0;
  8385. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  8386. const auto &fragment = static_fragments_[i];
  8387. if (starting_pos + fragment.length() > request.path.length()) {
  8388. return false;
  8389. }
  8390. // Avoid unnecessary allocation by using strncmp instead of substr +
  8391. // comparison
  8392. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  8393. fragment.length()) != 0) {
  8394. return false;
  8395. }
  8396. starting_pos += fragment.length();
  8397. // Should only happen when we have a static fragment after a param
  8398. // Example: '/users/:id/subscriptions'
  8399. // The 'subscriptions' fragment here does not have a corresponding param
  8400. if (i >= param_names_.size()) { continue; }
  8401. auto sep_pos = request.path.find(separator, starting_pos);
  8402. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  8403. const auto &param_name = param_names_[i];
  8404. request.path_params.emplace(
  8405. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  8406. // Mark everything up to '/' as matched
  8407. starting_pos = sep_pos + 1;
  8408. }
  8409. // Returns false if the path is longer than the pattern
  8410. return starting_pos >= request.path.length();
  8411. }
  8412. inline bool RegexMatcher::match(Request &request) const {
  8413. request.path_params.clear();
  8414. return std::regex_match(request.path, request.matches, regex_);
  8415. }
  8416. // Enclose IPv6 address in brackets if needed
  8417. inline std::string prepare_host_string(const std::string &host) {
  8418. // Enclose IPv6 address in brackets (but not if already enclosed)
  8419. if (host.find(':') == std::string::npos ||
  8420. (!host.empty() && host[0] == '[')) {
  8421. // IPv4, hostname, or already bracketed IPv6
  8422. return host;
  8423. } else {
  8424. // IPv6 address without brackets
  8425. return "[" + host + "]";
  8426. }
  8427. }
  8428. inline std::string make_host_and_port_string(const std::string &host, int port,
  8429. bool is_ssl) {
  8430. auto result = prepare_host_string(host);
  8431. // Append port if not default
  8432. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  8433. ; // do nothing
  8434. } else {
  8435. result += ":" + std::to_string(port);
  8436. }
  8437. return result;
  8438. }
  8439. // Create "host:port" string always including port number (for CONNECT method)
  8440. inline std::string
  8441. make_host_and_port_string_always_port(const std::string &host, int port) {
  8442. return prepare_host_string(host) + ":" + std::to_string(port);
  8443. }
  8444. template <typename T>
  8445. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  8446. T header_writer, Error &error) {
  8447. for (const auto &h : headers) {
  8448. if (!detail::fields::is_field_name(h.first) ||
  8449. !detail::fields::is_field_value(h.second)) {
  8450. error = Error::InvalidHeaders;
  8451. return false;
  8452. }
  8453. }
  8454. if (header_writer(strm, headers) <= 0) {
  8455. error = Error::Write;
  8456. return false;
  8457. }
  8458. return true;
  8459. }
  8460. } // namespace detail
  8461. /*
  8462. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  8463. */
  8464. #ifdef CPPHTTPLIB_SSL_ENABLED
  8465. namespace detail {
  8466. // SSL socket stream implementation
  8467. inline SSLSocketStream::SSLSocketStream(
  8468. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  8469. time_t read_timeout_usec, time_t write_timeout_sec,
  8470. time_t write_timeout_usec, time_t max_timeout_msec,
  8471. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8472. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  8473. read_timeout_usec_(read_timeout_usec),
  8474. write_timeout_sec_(write_timeout_sec),
  8475. write_timeout_usec_(write_timeout_usec),
  8476. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  8477. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8478. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  8479. // Note: create_session() also clears this, but SSLClient currently
  8480. // uses ssl_new() which does not. Until full TLS API migration is complete,
  8481. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  8482. // SSL session was created.
  8483. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  8484. #endif
  8485. }
  8486. inline SSLSocketStream::~SSLSocketStream() = default;
  8487. inline bool SSLSocketStream::is_readable() const {
  8488. return tls::pending(session_) > 0;
  8489. }
  8490. inline bool SSLSocketStream::wait_readable() const {
  8491. if (max_timeout_msec_ <= 0) {
  8492. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8493. }
  8494. time_t read_timeout_sec;
  8495. time_t read_timeout_usec;
  8496. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8497. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8498. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8499. }
  8500. inline bool SSLSocketStream::wait_writable() const {
  8501. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  8502. !tls::is_peer_closed(session_, sock_);
  8503. }
  8504. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  8505. if (tls::pending(session_) > 0) {
  8506. tls::TlsError err;
  8507. auto ret = tls::read(session_, ptr, size, err);
  8508. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  8509. error_ = Error::ConnectionClosed;
  8510. }
  8511. return ret;
  8512. } else if (wait_readable()) {
  8513. tls::TlsError err;
  8514. auto ret = tls::read(session_, ptr, size, err);
  8515. if (ret < 0) {
  8516. auto n = 1000;
  8517. #ifdef _WIN32
  8518. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  8519. (err.code == tls::ErrorCode::SyscallError &&
  8520. WSAGetLastError() == WSAETIMEDOUT))) {
  8521. #else
  8522. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  8523. #endif
  8524. if (tls::pending(session_) > 0) {
  8525. return tls::read(session_, ptr, size, err);
  8526. } else if (wait_readable()) {
  8527. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8528. ret = tls::read(session_, ptr, size, err);
  8529. if (ret >= 0) { return ret; }
  8530. } else {
  8531. break;
  8532. }
  8533. }
  8534. assert(ret < 0);
  8535. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  8536. error_ = Error::ConnectionClosed;
  8537. }
  8538. return ret;
  8539. } else {
  8540. error_ = Error::Timeout;
  8541. return -1;
  8542. }
  8543. }
  8544. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  8545. if (wait_writable()) {
  8546. auto handle_size =
  8547. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  8548. tls::TlsError err;
  8549. auto ret = tls::write(session_, ptr, handle_size, err);
  8550. if (ret < 0) {
  8551. auto n = 1000;
  8552. #ifdef _WIN32
  8553. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  8554. (err.code == tls::ErrorCode::SyscallError &&
  8555. WSAGetLastError() == WSAETIMEDOUT))) {
  8556. #else
  8557. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  8558. #endif
  8559. if (wait_writable()) {
  8560. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8561. ret = tls::write(session_, ptr, handle_size, err);
  8562. if (ret >= 0) { return ret; }
  8563. } else {
  8564. break;
  8565. }
  8566. }
  8567. assert(ret < 0);
  8568. }
  8569. return ret;
  8570. }
  8571. return -1;
  8572. }
  8573. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  8574. int &port) const {
  8575. detail::get_remote_ip_and_port(sock_, ip, port);
  8576. }
  8577. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  8578. int &port) const {
  8579. detail::get_local_ip_and_port(sock_, ip, port);
  8580. }
  8581. inline socket_t SSLSocketStream::socket() const { return sock_; }
  8582. inline time_t SSLSocketStream::duration() const {
  8583. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8584. std::chrono::steady_clock::now() - start_time_)
  8585. .count();
  8586. }
  8587. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  8588. read_timeout_sec_ = sec;
  8589. read_timeout_usec_ = usec;
  8590. }
  8591. } // namespace detail
  8592. #endif // CPPHTTPLIB_SSL_ENABLED
  8593. /*
  8594. * Group 4: Server implementation
  8595. */
  8596. // HTTP server implementation
  8597. inline Server::Server()
  8598. : new_task_queue([] {
  8599. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  8600. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  8601. }) {
  8602. #ifndef _WIN32
  8603. signal(SIGPIPE, SIG_IGN);
  8604. #endif
  8605. }
  8606. inline Server::~Server() = default;
  8607. inline std::unique_ptr<detail::MatcherBase>
  8608. Server::make_matcher(const std::string &pattern) {
  8609. if (pattern.find("/:") != std::string::npos) {
  8610. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  8611. } else {
  8612. return detail::make_unique<detail::RegexMatcher>(pattern);
  8613. }
  8614. }
  8615. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  8616. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8617. return *this;
  8618. }
  8619. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  8620. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8621. return *this;
  8622. }
  8623. inline Server &Server::Post(const std::string &pattern,
  8624. HandlerWithContentReader handler) {
  8625. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8626. std::move(handler));
  8627. return *this;
  8628. }
  8629. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  8630. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8631. return *this;
  8632. }
  8633. inline Server &Server::Put(const std::string &pattern,
  8634. HandlerWithContentReader handler) {
  8635. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8636. std::move(handler));
  8637. return *this;
  8638. }
  8639. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  8640. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8641. return *this;
  8642. }
  8643. inline Server &Server::Patch(const std::string &pattern,
  8644. HandlerWithContentReader handler) {
  8645. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8646. std::move(handler));
  8647. return *this;
  8648. }
  8649. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  8650. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8651. return *this;
  8652. }
  8653. inline Server &Server::Delete(const std::string &pattern,
  8654. HandlerWithContentReader handler) {
  8655. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  8656. std::move(handler));
  8657. return *this;
  8658. }
  8659. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  8660. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  8661. return *this;
  8662. }
  8663. inline Server &Server::WebSocket(const std::string &pattern,
  8664. WebSocketHandler handler) {
  8665. websocket_handlers_.push_back(
  8666. {make_matcher(pattern), std::move(handler), nullptr});
  8667. return *this;
  8668. }
  8669. inline Server &Server::WebSocket(const std::string &pattern,
  8670. WebSocketHandler handler,
  8671. SubProtocolSelector sub_protocol_selector) {
  8672. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  8673. std::move(sub_protocol_selector)});
  8674. return *this;
  8675. }
  8676. inline bool Server::set_base_dir(const std::string &dir,
  8677. const std::string &mount_point) {
  8678. return set_mount_point(mount_point, dir);
  8679. }
  8680. inline bool Server::set_mount_point(const std::string &mount_point,
  8681. const std::string &dir, Headers headers) {
  8682. detail::FileStat stat(dir);
  8683. if (stat.is_dir()) {
  8684. std::string mnt = !mount_point.empty() ? mount_point : "/";
  8685. if (!mnt.empty() && mnt[0] == '/') {
  8686. base_dirs_.push_back({std::move(mnt), dir, std::move(headers)});
  8687. return true;
  8688. }
  8689. }
  8690. return false;
  8691. }
  8692. inline bool Server::remove_mount_point(const std::string &mount_point) {
  8693. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  8694. if (it->mount_point == mount_point) {
  8695. base_dirs_.erase(it);
  8696. return true;
  8697. }
  8698. }
  8699. return false;
  8700. }
  8701. inline Server &
  8702. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  8703. const std::string &mime) {
  8704. file_extension_and_mimetype_map_[ext] = mime;
  8705. return *this;
  8706. }
  8707. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  8708. default_file_mimetype_ = mime;
  8709. return *this;
  8710. }
  8711. inline Server &Server::set_file_request_handler(Handler handler) {
  8712. file_request_handler_ = std::move(handler);
  8713. return *this;
  8714. }
  8715. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  8716. std::true_type) {
  8717. error_handler_ = std::move(handler);
  8718. return *this;
  8719. }
  8720. inline Server &Server::set_error_handler_core(Handler handler,
  8721. std::false_type) {
  8722. error_handler_ = [handler](const Request &req, Response &res) {
  8723. handler(req, res);
  8724. return HandlerResponse::Handled;
  8725. };
  8726. return *this;
  8727. }
  8728. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  8729. exception_handler_ = std::move(handler);
  8730. return *this;
  8731. }
  8732. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  8733. pre_routing_handler_ = std::move(handler);
  8734. return *this;
  8735. }
  8736. inline Server &Server::set_post_routing_handler(Handler handler) {
  8737. post_routing_handler_ = std::move(handler);
  8738. return *this;
  8739. }
  8740. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  8741. pre_request_handler_ = std::move(handler);
  8742. return *this;
  8743. }
  8744. inline Server &Server::set_logger(Logger logger) {
  8745. logger_ = std::move(logger);
  8746. return *this;
  8747. }
  8748. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  8749. error_logger_ = std::move(error_logger);
  8750. return *this;
  8751. }
  8752. inline Server &Server::set_pre_compression_logger(Logger logger) {
  8753. pre_compression_logger_ = std::move(logger);
  8754. return *this;
  8755. }
  8756. inline Server &
  8757. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  8758. expect_100_continue_handler_ = std::move(handler);
  8759. return *this;
  8760. }
  8761. inline Server &Server::set_address_family(int family) {
  8762. address_family_ = family;
  8763. return *this;
  8764. }
  8765. inline Server &Server::set_tcp_nodelay(bool on) {
  8766. tcp_nodelay_ = on;
  8767. return *this;
  8768. }
  8769. inline Server &Server::set_ipv6_v6only(bool on) {
  8770. ipv6_v6only_ = on;
  8771. return *this;
  8772. }
  8773. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  8774. socket_options_ = std::move(socket_options);
  8775. return *this;
  8776. }
  8777. inline Server &Server::set_default_headers(Headers headers) {
  8778. default_headers_ = std::move(headers);
  8779. return *this;
  8780. }
  8781. inline Server &Server::set_header_writer(
  8782. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  8783. header_writer_ = writer;
  8784. return *this;
  8785. }
  8786. inline Server &
  8787. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  8788. trusted_proxies_ = proxies;
  8789. return *this;
  8790. }
  8791. inline Server &Server::set_keep_alive_max_count(size_t count) {
  8792. keep_alive_max_count_ = count;
  8793. return *this;
  8794. }
  8795. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  8796. keep_alive_timeout_sec_ = sec;
  8797. return *this;
  8798. }
  8799. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  8800. read_timeout_sec_ = sec;
  8801. read_timeout_usec_ = usec;
  8802. return *this;
  8803. }
  8804. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  8805. write_timeout_sec_ = sec;
  8806. write_timeout_usec_ = usec;
  8807. return *this;
  8808. }
  8809. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  8810. idle_interval_sec_ = sec;
  8811. idle_interval_usec_ = usec;
  8812. return *this;
  8813. }
  8814. inline Server &Server::set_payload_max_length(size_t length) {
  8815. payload_max_length_ = length;
  8816. return *this;
  8817. }
  8818. inline bool Server::bind_to_port(const std::string &host, int port,
  8819. int socket_flags) {
  8820. auto ret = bind_internal(host, port, socket_flags);
  8821. if (ret == -1) { is_decommissioned = true; }
  8822. return ret >= 0;
  8823. }
  8824. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  8825. auto ret = bind_internal(host, 0, socket_flags);
  8826. if (ret == -1) { is_decommissioned = true; }
  8827. return ret;
  8828. }
  8829. inline bool Server::listen_after_bind() { return listen_internal(); }
  8830. inline bool Server::listen(const std::string &host, int port,
  8831. int socket_flags) {
  8832. return bind_to_port(host, port, socket_flags) && listen_internal();
  8833. }
  8834. inline bool Server::is_running() const { return is_running_; }
  8835. inline void Server::wait_until_ready() const {
  8836. while (!is_running_ && !is_decommissioned) {
  8837. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  8838. }
  8839. }
  8840. inline void Server::stop() {
  8841. if (is_running_) {
  8842. assert(svr_sock_ != INVALID_SOCKET);
  8843. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  8844. detail::shutdown_socket(sock);
  8845. detail::close_socket(sock);
  8846. }
  8847. is_decommissioned = false;
  8848. }
  8849. inline void Server::decommission() { is_decommissioned = true; }
  8850. inline bool Server::parse_request_line(const char *s, Request &req) const {
  8851. auto len = strlen(s);
  8852. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  8853. len -= 2;
  8854. {
  8855. size_t count = 0;
  8856. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  8857. switch (count) {
  8858. case 0: req.method = std::string(b, e); break;
  8859. case 1: req.target = std::string(b, e); break;
  8860. case 2: req.version = std::string(b, e); break;
  8861. default: break;
  8862. }
  8863. count++;
  8864. });
  8865. if (count != 3) { return false; }
  8866. }
  8867. thread_local const std::set<std::string> methods{
  8868. "GET", "HEAD", "POST", "PUT", "DELETE",
  8869. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8870. if (methods.find(req.method) == methods.end()) {
  8871. output_error_log(Error::InvalidHTTPMethod, &req);
  8872. return false;
  8873. }
  8874. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  8875. output_error_log(Error::InvalidHTTPVersion, &req);
  8876. return false;
  8877. }
  8878. {
  8879. // Skip URL fragment
  8880. for (size_t i = 0; i < req.target.size(); i++) {
  8881. if (req.target[i] == '#') {
  8882. req.target.erase(i);
  8883. break;
  8884. }
  8885. }
  8886. detail::divide(req.target, '?',
  8887. [&](const char *lhs_data, std::size_t lhs_size,
  8888. const char *rhs_data, std::size_t rhs_size) {
  8889. req.path =
  8890. decode_path_component(std::string(lhs_data, lhs_size));
  8891. detail::parse_query_text(rhs_data, rhs_size, req.params);
  8892. });
  8893. }
  8894. return true;
  8895. }
  8896. inline bool Server::write_response(Stream &strm, bool close_connection,
  8897. Request &req, Response &res) {
  8898. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  8899. // incorrectly to the error content.
  8900. req.ranges.clear();
  8901. return write_response_core(strm, close_connection, req, res, false);
  8902. }
  8903. inline bool Server::write_response_with_content(Stream &strm,
  8904. bool close_connection,
  8905. const Request &req,
  8906. Response &res) {
  8907. return write_response_core(strm, close_connection, req, res, true);
  8908. }
  8909. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  8910. const Request &req, Response &res,
  8911. bool need_apply_ranges) {
  8912. assert(res.status != -1);
  8913. if (400 <= res.status && error_handler_ &&
  8914. error_handler_(req, res) == HandlerResponse::Handled) {
  8915. need_apply_ranges = true;
  8916. }
  8917. std::string content_type;
  8918. std::string boundary;
  8919. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  8920. // Prepare additional headers
  8921. if (close_connection || req.get_header_value("Connection") == "close" ||
  8922. 400 <= res.status) { // Don't leave connections open after errors
  8923. res.set_header("Connection", "close");
  8924. } else {
  8925. std::string s = "timeout=";
  8926. s += std::to_string(keep_alive_timeout_sec_);
  8927. s += ", max=";
  8928. s += std::to_string(keep_alive_max_count_);
  8929. res.set_header("Keep-Alive", s);
  8930. }
  8931. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  8932. !res.has_header("Content-Type")) {
  8933. res.set_header("Content-Type", "text/plain");
  8934. }
  8935. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  8936. !res.has_header("Content-Length")) {
  8937. res.set_header("Content-Length", "0");
  8938. }
  8939. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  8940. res.set_header("Accept-Ranges", "bytes");
  8941. }
  8942. if (post_routing_handler_) { post_routing_handler_(req, res); }
  8943. // Response line and headers
  8944. detail::BufferStream bstrm;
  8945. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  8946. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  8947. // Combine small body with headers to reduce write syscalls
  8948. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  8949. bstrm.write(res.body.data(), res.body.size());
  8950. }
  8951. // Flush buffer
  8952. auto &data = bstrm.get_buffer();
  8953. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  8954. // Streaming body
  8955. auto ret = true;
  8956. if (req.method != "HEAD" && res.content_provider_) {
  8957. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  8958. res.content_provider_success_ = true;
  8959. } else {
  8960. ret = false;
  8961. }
  8962. }
  8963. // Log
  8964. output_log(req, res);
  8965. return ret;
  8966. }
  8967. inline bool
  8968. Server::write_content_with_provider(Stream &strm, const Request &req,
  8969. Response &res, const std::string &boundary,
  8970. const std::string &content_type) {
  8971. auto is_shutting_down = [this]() {
  8972. return this->svr_sock_ == INVALID_SOCKET;
  8973. };
  8974. if (res.content_length_ > 0) {
  8975. if (req.ranges.empty()) {
  8976. return detail::write_content(strm, res.content_provider_, 0,
  8977. res.content_length_, is_shutting_down);
  8978. } else if (req.ranges.size() == 1) {
  8979. auto offset_and_length = detail::get_range_offset_and_length(
  8980. req.ranges[0], res.content_length_);
  8981. return detail::write_content(strm, res.content_provider_,
  8982. offset_and_length.first,
  8983. offset_and_length.second, is_shutting_down);
  8984. } else {
  8985. return detail::write_multipart_ranges_data(
  8986. strm, req, res, boundary, content_type, res.content_length_,
  8987. is_shutting_down);
  8988. }
  8989. } else {
  8990. if (res.is_chunked_content_provider_) {
  8991. auto type = detail::encoding_type(req, res);
  8992. std::unique_ptr<detail::compressor> compressor;
  8993. if (type == detail::EncodingType::Gzip) {
  8994. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8995. compressor = detail::make_unique<detail::gzip_compressor>();
  8996. #endif
  8997. } else if (type == detail::EncodingType::Brotli) {
  8998. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8999. compressor = detail::make_unique<detail::brotli_compressor>();
  9000. #endif
  9001. } else if (type == detail::EncodingType::Zstd) {
  9002. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9003. compressor = detail::make_unique<detail::zstd_compressor>();
  9004. #endif
  9005. } else {
  9006. compressor = detail::make_unique<detail::nocompressor>();
  9007. }
  9008. assert(compressor != nullptr);
  9009. return detail::write_content_chunked(strm, res.content_provider_,
  9010. is_shutting_down, *compressor);
  9011. } else {
  9012. return detail::write_content_without_length(strm, res.content_provider_,
  9013. is_shutting_down);
  9014. }
  9015. }
  9016. }
  9017. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9018. FormFields::iterator cur_field;
  9019. FormFiles::iterator cur_file;
  9020. auto is_text_field = false;
  9021. size_t count = 0;
  9022. if (read_content_core(
  9023. strm, req, res,
  9024. // Regular
  9025. [&](const char *buf, size_t n) {
  9026. // Prevent arithmetic overflow when checking sizes.
  9027. // Avoid computing (req.body.size() + n) directly because
  9028. // adding two unsigned `size_t` values can wrap around and
  9029. // produce a small result instead of indicating overflow.
  9030. // Instead, check using subtraction: ensure `n` does not
  9031. // exceed the remaining capacity `max_size() - size()`.
  9032. if (req.body.size() >= req.body.max_size() ||
  9033. n > req.body.max_size() - req.body.size()) {
  9034. return false;
  9035. }
  9036. // Limit decompressed body size to payload_max_length_ to protect
  9037. // against "zip bomb" attacks where a small compressed payload
  9038. // decompresses to a massive size.
  9039. if (payload_max_length_ > 0 &&
  9040. (req.body.size() >= payload_max_length_ ||
  9041. n > payload_max_length_ - req.body.size())) {
  9042. return false;
  9043. }
  9044. req.body.append(buf, n);
  9045. return true;
  9046. },
  9047. // Multipart FormData
  9048. [&](const FormData &file) {
  9049. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9050. output_error_log(Error::TooManyFormDataFiles, &req);
  9051. return false;
  9052. }
  9053. if (file.filename.empty()) {
  9054. cur_field = req.form.fields.emplace(
  9055. file.name, FormField{file.name, file.content, file.headers});
  9056. is_text_field = true;
  9057. } else {
  9058. cur_file = req.form.files.emplace(file.name, file);
  9059. is_text_field = false;
  9060. }
  9061. return true;
  9062. },
  9063. [&](const char *buf, size_t n) {
  9064. if (is_text_field) {
  9065. auto &content = cur_field->second.content;
  9066. if (content.size() + n > content.max_size()) { return false; }
  9067. content.append(buf, n);
  9068. } else {
  9069. auto &content = cur_file->second.content;
  9070. if (content.size() + n > content.max_size()) { return false; }
  9071. content.append(buf, n);
  9072. }
  9073. return true;
  9074. })) {
  9075. const auto &content_type = req.get_header_value("Content-Type");
  9076. if (!content_type.find("application/x-www-form-urlencoded")) {
  9077. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9078. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9079. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9080. return false;
  9081. }
  9082. detail::parse_query_text(req.body, req.params);
  9083. }
  9084. return true;
  9085. }
  9086. return false;
  9087. }
  9088. inline bool Server::read_content_with_content_receiver(
  9089. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9090. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9091. return read_content_core(strm, req, res, std::move(receiver),
  9092. std::move(multipart_header),
  9093. std::move(multipart_receiver));
  9094. }
  9095. inline bool Server::read_content_core(
  9096. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9097. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9098. detail::FormDataParser multipart_form_data_parser;
  9099. ContentReceiverWithProgress out;
  9100. if (req.is_multipart_form_data()) {
  9101. const auto &content_type = req.get_header_value("Content-Type");
  9102. std::string boundary;
  9103. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9104. res.status = StatusCode::BadRequest_400;
  9105. output_error_log(Error::MultipartParsing, &req);
  9106. return false;
  9107. }
  9108. multipart_form_data_parser.set_boundary(std::move(boundary));
  9109. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9110. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9111. multipart_receiver);
  9112. };
  9113. } else {
  9114. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9115. size_t /*len*/) { return receiver(buf, n); };
  9116. }
  9117. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  9118. // are true (no Transfer-Encoding and no Content-Length), then the message
  9119. // body length is zero (no message body is present).
  9120. //
  9121. // For non-SSL builds, detect clients that send a body without a
  9122. // Content-Length header (raw HTTP over TCP). Check both the stream's
  9123. // internal read buffer (data already read from the socket during header
  9124. // parsing) and the socket itself for pending data. If data is found and
  9125. // exceeds the configured payload limit, reject with 413.
  9126. // For SSL builds we cannot reliably peek the decrypted application bytes,
  9127. // so keep the original behaviour.
  9128. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9129. if (!req.has_header("Content-Length") &&
  9130. !detail::is_chunked_transfer_encoding(req.headers)) {
  9131. // Only check if payload_max_length is set to a finite value
  9132. if (payload_max_length_ > 0 &&
  9133. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9134. // Check if there is data already buffered in the stream (read during
  9135. // header parsing) or pending on the socket. Use a non-blocking socket
  9136. // check to avoid deadlock when the client sends no body.
  9137. bool has_data = strm.is_readable();
  9138. if (!has_data) {
  9139. socket_t s = strm.socket();
  9140. if (s != INVALID_SOCKET) {
  9141. has_data = detail::select_read(s, 0, 0) > 0;
  9142. }
  9143. }
  9144. if (has_data) {
  9145. auto result =
  9146. detail::read_content_without_length(strm, payload_max_length_, out);
  9147. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9148. res.status = StatusCode::PayloadTooLarge_413;
  9149. return false;
  9150. } else if (result != detail::ReadContentResult::Success) {
  9151. return false;
  9152. }
  9153. return true;
  9154. }
  9155. }
  9156. return true;
  9157. }
  9158. #else
  9159. if (!req.has_header("Content-Length") &&
  9160. !detail::is_chunked_transfer_encoding(req.headers)) {
  9161. return true;
  9162. }
  9163. #endif
  9164. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9165. out, true)) {
  9166. return false;
  9167. }
  9168. if (req.is_multipart_form_data()) {
  9169. if (!multipart_form_data_parser.is_valid()) {
  9170. res.status = StatusCode::BadRequest_400;
  9171. output_error_log(Error::MultipartParsing, &req);
  9172. return false;
  9173. }
  9174. }
  9175. return true;
  9176. }
  9177. inline bool Server::handle_file_request(Request &req, Response &res) {
  9178. for (const auto &entry : base_dirs_) {
  9179. // Prefix match
  9180. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9181. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9182. if (detail::is_valid_path(sub_path)) {
  9183. auto path = entry.base_dir + sub_path;
  9184. if (path.back() == '/') { path += "index.html"; }
  9185. detail::FileStat stat(path);
  9186. if (stat.is_dir()) {
  9187. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9188. return true;
  9189. }
  9190. if (stat.is_file()) {
  9191. for (const auto &kv : entry.headers) {
  9192. res.set_header(kv.first, kv.second);
  9193. }
  9194. auto etag = detail::compute_etag(stat);
  9195. if (!etag.empty()) { res.set_header("ETag", etag); }
  9196. auto mtime = stat.mtime();
  9197. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9198. if (!last_modified.empty()) {
  9199. res.set_header("Last-Modified", last_modified);
  9200. }
  9201. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9202. check_if_range(req, etag, mtime);
  9203. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9204. if (!mm->is_open()) {
  9205. output_error_log(Error::OpenFile, &req);
  9206. return false;
  9207. }
  9208. res.set_content_provider(
  9209. mm->size(),
  9210. detail::find_content_type(path, file_extension_and_mimetype_map_,
  9211. default_file_mimetype_),
  9212. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9213. sink.write(mm->data() + offset, length);
  9214. return true;
  9215. });
  9216. if (req.method != "HEAD" && file_request_handler_) {
  9217. file_request_handler_(req, res);
  9218. }
  9219. return true;
  9220. } else {
  9221. output_error_log(Error::OpenFile, &req);
  9222. }
  9223. }
  9224. }
  9225. }
  9226. return false;
  9227. }
  9228. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  9229. const std::string &etag,
  9230. time_t mtime) const {
  9231. // Handle conditional GET:
  9232. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  9233. // 2. If-Modified-Since is checked only when If-None-Match is absent
  9234. if (req.has_header("If-None-Match")) {
  9235. if (!etag.empty()) {
  9236. auto val = req.get_header_value("If-None-Match");
  9237. // NOTE: We use exact string matching here. This works correctly
  9238. // because our server always generates weak ETags (W/"..."), and
  9239. // clients typically send back the same ETag they received.
  9240. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  9241. // If-None-Match, where W/"x" and "x" would match, but this
  9242. // simplified implementation requires exact matches.
  9243. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  9244. [&](const char *b, const char *e) {
  9245. auto seg_len = static_cast<size_t>(e - b);
  9246. return (seg_len == 1 && *b == '*') ||
  9247. (seg_len == etag.size() &&
  9248. std::equal(b, e, etag.begin()));
  9249. });
  9250. if (ret) {
  9251. res.status = StatusCode::NotModified_304;
  9252. return true;
  9253. }
  9254. }
  9255. } else if (req.has_header("If-Modified-Since")) {
  9256. auto val = req.get_header_value("If-Modified-Since");
  9257. auto t = detail::parse_http_date(val);
  9258. if (t != static_cast<time_t>(-1) && mtime <= t) {
  9259. res.status = StatusCode::NotModified_304;
  9260. return true;
  9261. }
  9262. }
  9263. return false;
  9264. }
  9265. inline bool Server::check_if_range(Request &req, const std::string &etag,
  9266. time_t mtime) const {
  9267. // Handle If-Range for partial content requests (RFC 9110
  9268. // Section 13.1.5). If-Range is only evaluated when Range header is
  9269. // present. If the validator matches, serve partial content; otherwise
  9270. // serve full content.
  9271. if (!req.ranges.empty() && req.has_header("If-Range")) {
  9272. auto val = req.get_header_value("If-Range");
  9273. auto is_valid_range = [&]() {
  9274. if (detail::is_strong_etag(val)) {
  9275. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  9276. // comparison.
  9277. return (!etag.empty() && val == etag);
  9278. } else if (detail::is_weak_etag(val)) {
  9279. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  9280. return false;
  9281. } else {
  9282. // HTTP-date comparison
  9283. auto t = detail::parse_http_date(val);
  9284. return (t != static_cast<time_t>(-1) && mtime <= t);
  9285. }
  9286. };
  9287. if (!is_valid_range()) {
  9288. // Validator doesn't match: ignore Range and serve full content
  9289. req.ranges.clear();
  9290. return false;
  9291. }
  9292. }
  9293. return true;
  9294. }
  9295. inline socket_t
  9296. Server::create_server_socket(const std::string &host, int port,
  9297. int socket_flags,
  9298. SocketOptions socket_options) const {
  9299. return detail::create_socket(
  9300. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  9301. ipv6_v6only_, std::move(socket_options),
  9302. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  9303. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  9304. output_error_log(Error::BindIPAddress, nullptr);
  9305. return false;
  9306. }
  9307. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  9308. output_error_log(Error::Listen, nullptr);
  9309. return false;
  9310. }
  9311. return true;
  9312. });
  9313. }
  9314. inline int Server::bind_internal(const std::string &host, int port,
  9315. int socket_flags) {
  9316. if (is_decommissioned) { return -1; }
  9317. if (!is_valid()) { return -1; }
  9318. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  9319. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  9320. if (port == 0) {
  9321. struct sockaddr_storage addr;
  9322. socklen_t addr_len = sizeof(addr);
  9323. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  9324. &addr_len) == -1) {
  9325. output_error_log(Error::GetSockName, nullptr);
  9326. return -1;
  9327. }
  9328. if (addr.ss_family == AF_INET) {
  9329. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  9330. } else if (addr.ss_family == AF_INET6) {
  9331. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  9332. } else {
  9333. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  9334. return -1;
  9335. }
  9336. } else {
  9337. return port;
  9338. }
  9339. }
  9340. inline bool Server::listen_internal() {
  9341. if (is_decommissioned) { return false; }
  9342. auto ret = true;
  9343. is_running_ = true;
  9344. auto se = detail::scope_exit([&]() { is_running_ = false; });
  9345. {
  9346. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  9347. while (svr_sock_ != INVALID_SOCKET) {
  9348. #ifndef _WIN32
  9349. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  9350. #endif
  9351. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  9352. idle_interval_usec_);
  9353. if (val == 0) { // Timeout
  9354. task_queue->on_idle();
  9355. continue;
  9356. }
  9357. #ifndef _WIN32
  9358. }
  9359. #endif
  9360. #if defined _WIN32
  9361. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  9362. // OVERLAPPED
  9363. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  9364. #elif defined SOCK_CLOEXEC
  9365. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  9366. #else
  9367. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  9368. #endif
  9369. if (sock == INVALID_SOCKET) {
  9370. if (errno == EMFILE) {
  9371. // The per-process limit of open file descriptors has been reached.
  9372. // Try to accept new connections after a short sleep.
  9373. std::this_thread::sleep_for(std::chrono::microseconds{1});
  9374. continue;
  9375. } else if (errno == EINTR || errno == EAGAIN) {
  9376. continue;
  9377. }
  9378. if (svr_sock_ != INVALID_SOCKET) {
  9379. detail::close_socket(svr_sock_);
  9380. ret = false;
  9381. output_error_log(Error::Connection, nullptr);
  9382. } else {
  9383. ; // The server socket was closed by user.
  9384. }
  9385. break;
  9386. }
  9387. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  9388. read_timeout_sec_, read_timeout_usec_);
  9389. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  9390. write_timeout_sec_, write_timeout_usec_);
  9391. if (!task_queue->enqueue(
  9392. [this, sock]() { process_and_close_socket(sock); })) {
  9393. output_error_log(Error::ResourceExhaustion, nullptr);
  9394. detail::shutdown_socket(sock);
  9395. detail::close_socket(sock);
  9396. }
  9397. }
  9398. task_queue->shutdown();
  9399. }
  9400. is_decommissioned = !ret;
  9401. return ret;
  9402. }
  9403. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  9404. if (pre_routing_handler_ &&
  9405. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  9406. return true;
  9407. }
  9408. // File handler
  9409. if ((req.method == "GET" || req.method == "HEAD") &&
  9410. handle_file_request(req, res)) {
  9411. return true;
  9412. }
  9413. if (detail::expect_content(req)) {
  9414. // Content reader handler
  9415. {
  9416. ContentReader reader(
  9417. [&](ContentReceiver receiver) {
  9418. auto result = read_content_with_content_receiver(
  9419. strm, req, res, std::move(receiver), nullptr, nullptr);
  9420. if (!result) { output_error_log(Error::Read, &req); }
  9421. return result;
  9422. },
  9423. [&](FormDataHeader header, ContentReceiver receiver) {
  9424. auto result = read_content_with_content_receiver(
  9425. strm, req, res, nullptr, std::move(header),
  9426. std::move(receiver));
  9427. if (!result) { output_error_log(Error::Read, &req); }
  9428. return result;
  9429. });
  9430. if (req.method == "POST") {
  9431. if (dispatch_request_for_content_reader(
  9432. req, res, std::move(reader),
  9433. post_handlers_for_content_reader_)) {
  9434. return true;
  9435. }
  9436. } else if (req.method == "PUT") {
  9437. if (dispatch_request_for_content_reader(
  9438. req, res, std::move(reader),
  9439. put_handlers_for_content_reader_)) {
  9440. return true;
  9441. }
  9442. } else if (req.method == "PATCH") {
  9443. if (dispatch_request_for_content_reader(
  9444. req, res, std::move(reader),
  9445. patch_handlers_for_content_reader_)) {
  9446. return true;
  9447. }
  9448. } else if (req.method == "DELETE") {
  9449. if (dispatch_request_for_content_reader(
  9450. req, res, std::move(reader),
  9451. delete_handlers_for_content_reader_)) {
  9452. return true;
  9453. }
  9454. }
  9455. }
  9456. // Read content into `req.body`
  9457. if (!read_content(strm, req, res)) {
  9458. output_error_log(Error::Read, &req);
  9459. return false;
  9460. }
  9461. }
  9462. // Regular handler
  9463. if (req.method == "GET" || req.method == "HEAD") {
  9464. return dispatch_request(req, res, get_handlers_);
  9465. } else if (req.method == "POST") {
  9466. return dispatch_request(req, res, post_handlers_);
  9467. } else if (req.method == "PUT") {
  9468. return dispatch_request(req, res, put_handlers_);
  9469. } else if (req.method == "DELETE") {
  9470. return dispatch_request(req, res, delete_handlers_);
  9471. } else if (req.method == "OPTIONS") {
  9472. return dispatch_request(req, res, options_handlers_);
  9473. } else if (req.method == "PATCH") {
  9474. return dispatch_request(req, res, patch_handlers_);
  9475. }
  9476. res.status = StatusCode::BadRequest_400;
  9477. return false;
  9478. }
  9479. inline bool Server::dispatch_request(Request &req, Response &res,
  9480. const Handlers &handlers) const {
  9481. for (const auto &x : handlers) {
  9482. const auto &matcher = x.first;
  9483. const auto &handler = x.second;
  9484. if (matcher->match(req)) {
  9485. req.matched_route = matcher->pattern();
  9486. if (!pre_request_handler_ ||
  9487. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  9488. handler(req, res);
  9489. }
  9490. return true;
  9491. }
  9492. }
  9493. return false;
  9494. }
  9495. inline void Server::apply_ranges(const Request &req, Response &res,
  9496. std::string &content_type,
  9497. std::string &boundary) const {
  9498. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  9499. auto it = res.headers.find("Content-Type");
  9500. if (it != res.headers.end()) {
  9501. content_type = it->second;
  9502. res.headers.erase(it);
  9503. }
  9504. boundary = detail::make_multipart_data_boundary();
  9505. res.set_header("Content-Type",
  9506. "multipart/byteranges; boundary=" + boundary);
  9507. }
  9508. auto type = detail::encoding_type(req, res);
  9509. if (res.body.empty()) {
  9510. if (res.content_length_ > 0) {
  9511. size_t length = 0;
  9512. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  9513. length = res.content_length_;
  9514. } else if (req.ranges.size() == 1) {
  9515. auto offset_and_length = detail::get_range_offset_and_length(
  9516. req.ranges[0], res.content_length_);
  9517. length = offset_and_length.second;
  9518. auto content_range = detail::make_content_range_header_field(
  9519. offset_and_length, res.content_length_);
  9520. res.set_header("Content-Range", content_range);
  9521. } else {
  9522. length = detail::get_multipart_ranges_data_length(
  9523. req, boundary, content_type, res.content_length_);
  9524. }
  9525. res.set_header("Content-Length", std::to_string(length));
  9526. } else {
  9527. if (res.content_provider_) {
  9528. if (res.is_chunked_content_provider_) {
  9529. res.set_header("Transfer-Encoding", "chunked");
  9530. if (type == detail::EncodingType::Gzip) {
  9531. res.set_header("Content-Encoding", "gzip");
  9532. res.set_header("Vary", "Accept-Encoding");
  9533. } else if (type == detail::EncodingType::Brotli) {
  9534. res.set_header("Content-Encoding", "br");
  9535. res.set_header("Vary", "Accept-Encoding");
  9536. } else if (type == detail::EncodingType::Zstd) {
  9537. res.set_header("Content-Encoding", "zstd");
  9538. res.set_header("Vary", "Accept-Encoding");
  9539. }
  9540. }
  9541. }
  9542. }
  9543. } else {
  9544. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  9545. ;
  9546. } else if (req.ranges.size() == 1) {
  9547. auto offset_and_length =
  9548. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  9549. auto offset = offset_and_length.first;
  9550. auto length = offset_and_length.second;
  9551. auto content_range = detail::make_content_range_header_field(
  9552. offset_and_length, res.body.size());
  9553. res.set_header("Content-Range", content_range);
  9554. assert(offset + length <= res.body.size());
  9555. res.body = res.body.substr(offset, length);
  9556. } else {
  9557. std::string data;
  9558. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  9559. res.body.size(), data);
  9560. res.body.swap(data);
  9561. }
  9562. if (type != detail::EncodingType::None) {
  9563. output_pre_compression_log(req, res);
  9564. std::unique_ptr<detail::compressor> compressor;
  9565. std::string content_encoding;
  9566. if (type == detail::EncodingType::Gzip) {
  9567. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9568. compressor = detail::make_unique<detail::gzip_compressor>();
  9569. content_encoding = "gzip";
  9570. #endif
  9571. } else if (type == detail::EncodingType::Brotli) {
  9572. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9573. compressor = detail::make_unique<detail::brotli_compressor>();
  9574. content_encoding = "br";
  9575. #endif
  9576. } else if (type == detail::EncodingType::Zstd) {
  9577. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9578. compressor = detail::make_unique<detail::zstd_compressor>();
  9579. content_encoding = "zstd";
  9580. #endif
  9581. }
  9582. if (compressor) {
  9583. std::string compressed;
  9584. if (compressor->compress(res.body.data(), res.body.size(), true,
  9585. [&](const char *data, size_t data_len) {
  9586. compressed.append(data, data_len);
  9587. return true;
  9588. })) {
  9589. res.body.swap(compressed);
  9590. res.set_header("Content-Encoding", content_encoding);
  9591. res.set_header("Vary", "Accept-Encoding");
  9592. }
  9593. }
  9594. }
  9595. auto length = std::to_string(res.body.size());
  9596. res.set_header("Content-Length", length);
  9597. }
  9598. }
  9599. inline bool Server::dispatch_request_for_content_reader(
  9600. Request &req, Response &res, ContentReader content_reader,
  9601. const HandlersForContentReader &handlers) const {
  9602. for (const auto &x : handlers) {
  9603. const auto &matcher = x.first;
  9604. const auto &handler = x.second;
  9605. if (matcher->match(req)) {
  9606. req.matched_route = matcher->pattern();
  9607. if (!pre_request_handler_ ||
  9608. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  9609. handler(req, res, content_reader);
  9610. }
  9611. return true;
  9612. }
  9613. }
  9614. return false;
  9615. }
  9616. inline std::string
  9617. get_client_ip(const std::string &x_forwarded_for,
  9618. const std::vector<std::string> &trusted_proxies) {
  9619. // X-Forwarded-For is a comma-separated list per RFC 7239
  9620. std::vector<std::string> ip_list;
  9621. detail::split(x_forwarded_for.data(),
  9622. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  9623. [&](const char *b, const char *e) {
  9624. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  9625. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  9626. });
  9627. for (size_t i = 0; i < ip_list.size(); ++i) {
  9628. auto ip = ip_list[i];
  9629. auto is_trusted_proxy =
  9630. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  9631. [&](const std::string &proxy) { return ip == proxy; });
  9632. if (is_trusted_proxy) {
  9633. if (i == 0) {
  9634. // If the trusted proxy is the first IP, there's no preceding client IP
  9635. return ip;
  9636. } else {
  9637. // Return the IP immediately before the trusted proxy
  9638. return ip_list[i - 1];
  9639. }
  9640. }
  9641. }
  9642. // If no trusted proxy is found, return the first IP in the list
  9643. return ip_list.front();
  9644. }
  9645. inline bool
  9646. Server::process_request(Stream &strm, const std::string &remote_addr,
  9647. int remote_port, const std::string &local_addr,
  9648. int local_port, bool close_connection,
  9649. bool &connection_closed,
  9650. const std::function<void(Request &)> &setup_request,
  9651. bool *websocket_upgraded) {
  9652. std::array<char, 2048> buf{};
  9653. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  9654. // Connection has been closed on client
  9655. if (!line_reader.getline()) { return false; }
  9656. Request req;
  9657. req.start_time_ = std::chrono::steady_clock::now();
  9658. req.remote_addr = remote_addr;
  9659. req.remote_port = remote_port;
  9660. req.local_addr = local_addr;
  9661. req.local_port = local_port;
  9662. Response res;
  9663. res.version = "HTTP/1.1";
  9664. res.headers = default_headers_;
  9665. // Request line and headers
  9666. if (!parse_request_line(line_reader.ptr(), req)) {
  9667. res.status = StatusCode::BadRequest_400;
  9668. output_error_log(Error::InvalidRequestLine, &req);
  9669. return write_response(strm, close_connection, req, res);
  9670. }
  9671. // Request headers
  9672. if (!detail::read_headers(strm, req.headers)) {
  9673. res.status = StatusCode::BadRequest_400;
  9674. output_error_log(Error::InvalidHeaders, &req);
  9675. return write_response(strm, close_connection, req, res);
  9676. }
  9677. // Check if the request URI doesn't exceed the limit
  9678. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  9679. res.status = StatusCode::UriTooLong_414;
  9680. output_error_log(Error::ExceedUriMaxLength, &req);
  9681. return write_response(strm, close_connection, req, res);
  9682. }
  9683. if (req.get_header_value("Connection") == "close") {
  9684. connection_closed = true;
  9685. }
  9686. if (req.version == "HTTP/1.0" &&
  9687. req.get_header_value("Connection") != "Keep-Alive") {
  9688. connection_closed = true;
  9689. }
  9690. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  9691. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  9692. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  9693. } else {
  9694. req.remote_addr = remote_addr;
  9695. }
  9696. req.remote_port = remote_port;
  9697. req.local_addr = local_addr;
  9698. req.local_port = local_port;
  9699. if (req.has_header("Accept")) {
  9700. const auto &accept_header = req.get_header_value("Accept");
  9701. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  9702. res.status = StatusCode::BadRequest_400;
  9703. output_error_log(Error::HTTPParsing, &req);
  9704. return write_response(strm, close_connection, req, res);
  9705. }
  9706. }
  9707. if (req.has_header("Range")) {
  9708. const auto &range_header_value = req.get_header_value("Range");
  9709. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  9710. res.status = StatusCode::RangeNotSatisfiable_416;
  9711. output_error_log(Error::InvalidRangeHeader, &req);
  9712. return write_response(strm, close_connection, req, res);
  9713. }
  9714. }
  9715. if (setup_request) { setup_request(req); }
  9716. if (req.get_header_value("Expect") == "100-continue") {
  9717. int status = StatusCode::Continue_100;
  9718. if (expect_100_continue_handler_) {
  9719. status = expect_100_continue_handler_(req, res);
  9720. }
  9721. switch (status) {
  9722. case StatusCode::Continue_100:
  9723. case StatusCode::ExpectationFailed_417:
  9724. detail::write_response_line(strm, status);
  9725. strm.write("\r\n");
  9726. break;
  9727. default:
  9728. connection_closed = true;
  9729. return write_response(strm, true, req, res);
  9730. }
  9731. }
  9732. // Setup `is_connection_closed` method
  9733. auto sock = strm.socket();
  9734. req.is_connection_closed = [sock]() {
  9735. return !detail::is_socket_alive(sock);
  9736. };
  9737. // WebSocket upgrade
  9738. // Check pre_routing_handler_ before upgrading so that authentication
  9739. // and other middleware can reject the request with an HTTP response
  9740. // (e.g., 401) before the protocol switches.
  9741. if (detail::is_websocket_upgrade(req)) {
  9742. if (pre_routing_handler_ &&
  9743. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  9744. if (res.status == -1) { res.status = StatusCode::OK_200; }
  9745. return write_response(strm, close_connection, req, res);
  9746. }
  9747. // Find matching WebSocket handler
  9748. for (const auto &entry : websocket_handlers_) {
  9749. if (entry.matcher->match(req)) {
  9750. // Compute accept key
  9751. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  9752. auto accept_key = detail::websocket_accept_key(client_key);
  9753. // Negotiate subprotocol
  9754. std::string selected_subprotocol;
  9755. if (entry.sub_protocol_selector) {
  9756. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  9757. if (!protocol_header.empty()) {
  9758. std::vector<std::string> protocols;
  9759. std::istringstream iss(protocol_header);
  9760. std::string token;
  9761. while (std::getline(iss, token, ',')) {
  9762. // Trim whitespace
  9763. auto start = token.find_first_not_of(' ');
  9764. auto end = token.find_last_not_of(' ');
  9765. if (start != std::string::npos) {
  9766. protocols.push_back(token.substr(start, end - start + 1));
  9767. }
  9768. }
  9769. selected_subprotocol = entry.sub_protocol_selector(protocols);
  9770. }
  9771. }
  9772. // Send 101 Switching Protocols
  9773. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  9774. "Upgrade: websocket\r\n"
  9775. "Connection: Upgrade\r\n"
  9776. "Sec-WebSocket-Accept: " +
  9777. accept_key + "\r\n";
  9778. if (!selected_subprotocol.empty()) {
  9779. if (!detail::fields::is_field_value(selected_subprotocol)) {
  9780. return false;
  9781. }
  9782. handshake_response +=
  9783. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  9784. }
  9785. handshake_response += "\r\n";
  9786. if (strm.write(handshake_response.data(), handshake_response.size()) <
  9787. 0) {
  9788. return false;
  9789. }
  9790. connection_closed = true;
  9791. if (websocket_upgraded) { *websocket_upgraded = true; }
  9792. {
  9793. // Use WebSocket-specific read timeout instead of HTTP timeout
  9794. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  9795. ws::WebSocket ws(strm, req, true);
  9796. entry.handler(req, ws);
  9797. }
  9798. return true;
  9799. }
  9800. }
  9801. // No matching handler - fall through to 404
  9802. }
  9803. // Routing
  9804. auto routed = false;
  9805. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9806. routed = routing(req, res, strm);
  9807. #else
  9808. try {
  9809. routed = routing(req, res, strm);
  9810. } catch (std::exception &e) {
  9811. if (exception_handler_) {
  9812. auto ep = std::current_exception();
  9813. exception_handler_(req, res, ep);
  9814. routed = true;
  9815. } else {
  9816. res.status = StatusCode::InternalServerError_500;
  9817. std::string val;
  9818. auto s = e.what();
  9819. for (size_t i = 0; s[i]; i++) {
  9820. switch (s[i]) {
  9821. case '\r': val += "\\r"; break;
  9822. case '\n': val += "\\n"; break;
  9823. default: val += s[i]; break;
  9824. }
  9825. }
  9826. res.set_header("EXCEPTION_WHAT", val);
  9827. }
  9828. } catch (...) {
  9829. if (exception_handler_) {
  9830. auto ep = std::current_exception();
  9831. exception_handler_(req, res, ep);
  9832. routed = true;
  9833. } else {
  9834. res.status = StatusCode::InternalServerError_500;
  9835. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  9836. }
  9837. }
  9838. #endif
  9839. if (routed) {
  9840. if (res.status == -1) {
  9841. res.status = req.ranges.empty() ? StatusCode::OK_200
  9842. : StatusCode::PartialContent_206;
  9843. }
  9844. // Serve file content by using a content provider
  9845. if (!res.file_content_path_.empty()) {
  9846. const auto &path = res.file_content_path_;
  9847. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9848. if (!mm->is_open()) {
  9849. res.body.clear();
  9850. res.content_length_ = 0;
  9851. res.content_provider_ = nullptr;
  9852. res.status = StatusCode::NotFound_404;
  9853. output_error_log(Error::OpenFile, &req);
  9854. return write_response(strm, close_connection, req, res);
  9855. }
  9856. auto content_type = res.file_content_content_type_;
  9857. if (content_type.empty()) {
  9858. content_type = detail::find_content_type(
  9859. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  9860. }
  9861. res.set_content_provider(
  9862. mm->size(), content_type,
  9863. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9864. sink.write(mm->data() + offset, length);
  9865. return true;
  9866. });
  9867. }
  9868. if (detail::range_error(req, res)) {
  9869. res.body.clear();
  9870. res.content_length_ = 0;
  9871. res.content_provider_ = nullptr;
  9872. res.status = StatusCode::RangeNotSatisfiable_416;
  9873. return write_response(strm, close_connection, req, res);
  9874. }
  9875. return write_response_with_content(strm, close_connection, req, res);
  9876. } else {
  9877. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  9878. return write_response(strm, close_connection, req, res);
  9879. }
  9880. }
  9881. inline bool Server::is_valid() const { return true; }
  9882. inline bool Server::process_and_close_socket(socket_t sock) {
  9883. std::string remote_addr;
  9884. int remote_port = 0;
  9885. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  9886. std::string local_addr;
  9887. int local_port = 0;
  9888. detail::get_local_ip_and_port(sock, local_addr, local_port);
  9889. bool websocket_upgraded = false;
  9890. auto ret = detail::process_server_socket(
  9891. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  9892. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9893. write_timeout_usec_,
  9894. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  9895. return process_request(strm, remote_addr, remote_port, local_addr,
  9896. local_port, close_connection, connection_closed,
  9897. nullptr, &websocket_upgraded);
  9898. });
  9899. detail::shutdown_socket(sock);
  9900. detail::close_socket(sock);
  9901. return ret;
  9902. }
  9903. inline void Server::output_log(const Request &req, const Response &res) const {
  9904. if (logger_) {
  9905. std::lock_guard<std::mutex> guard(logger_mutex_);
  9906. logger_(req, res);
  9907. }
  9908. }
  9909. inline void Server::output_pre_compression_log(const Request &req,
  9910. const Response &res) const {
  9911. if (pre_compression_logger_) {
  9912. std::lock_guard<std::mutex> guard(logger_mutex_);
  9913. pre_compression_logger_(req, res);
  9914. }
  9915. }
  9916. inline void Server::output_error_log(const Error &err,
  9917. const Request *req) const {
  9918. if (error_logger_) {
  9919. std::lock_guard<std::mutex> guard(logger_mutex_);
  9920. error_logger_(err, req);
  9921. }
  9922. }
  9923. /*
  9924. * Group 5: ClientImpl and Client (Universal) implementation
  9925. */
  9926. // HTTP client implementation
  9927. inline ClientImpl::ClientImpl(const std::string &host)
  9928. : ClientImpl(host, 80, std::string(), std::string()) {}
  9929. inline ClientImpl::ClientImpl(const std::string &host, int port)
  9930. : ClientImpl(host, port, std::string(), std::string()) {}
  9931. inline ClientImpl::ClientImpl(const std::string &host, int port,
  9932. const std::string &client_cert_path,
  9933. const std::string &client_key_path)
  9934. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  9935. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  9936. inline ClientImpl::~ClientImpl() {
  9937. // Wait until all the requests in flight are handled.
  9938. size_t retry_count = 10;
  9939. while (retry_count-- > 0) {
  9940. {
  9941. std::lock_guard<std::mutex> guard(socket_mutex_);
  9942. if (socket_requests_in_flight_ == 0) { break; }
  9943. }
  9944. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9945. }
  9946. std::lock_guard<std::mutex> guard(socket_mutex_);
  9947. shutdown_socket(socket_);
  9948. close_socket(socket_);
  9949. }
  9950. inline bool ClientImpl::is_valid() const { return true; }
  9951. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  9952. client_cert_path_ = rhs.client_cert_path_;
  9953. client_key_path_ = rhs.client_key_path_;
  9954. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  9955. read_timeout_sec_ = rhs.read_timeout_sec_;
  9956. read_timeout_usec_ = rhs.read_timeout_usec_;
  9957. write_timeout_sec_ = rhs.write_timeout_sec_;
  9958. write_timeout_usec_ = rhs.write_timeout_usec_;
  9959. max_timeout_msec_ = rhs.max_timeout_msec_;
  9960. basic_auth_username_ = rhs.basic_auth_username_;
  9961. basic_auth_password_ = rhs.basic_auth_password_;
  9962. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  9963. keep_alive_ = rhs.keep_alive_;
  9964. follow_location_ = rhs.follow_location_;
  9965. path_encode_ = rhs.path_encode_;
  9966. address_family_ = rhs.address_family_;
  9967. tcp_nodelay_ = rhs.tcp_nodelay_;
  9968. ipv6_v6only_ = rhs.ipv6_v6only_;
  9969. socket_options_ = rhs.socket_options_;
  9970. compress_ = rhs.compress_;
  9971. decompress_ = rhs.decompress_;
  9972. payload_max_length_ = rhs.payload_max_length_;
  9973. has_payload_max_length_ = rhs.has_payload_max_length_;
  9974. interface_ = rhs.interface_;
  9975. proxy_host_ = rhs.proxy_host_;
  9976. proxy_port_ = rhs.proxy_port_;
  9977. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  9978. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  9979. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  9980. logger_ = rhs.logger_;
  9981. error_logger_ = rhs.error_logger_;
  9982. #ifdef CPPHTTPLIB_SSL_ENABLED
  9983. digest_auth_username_ = rhs.digest_auth_username_;
  9984. digest_auth_password_ = rhs.digest_auth_password_;
  9985. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  9986. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  9987. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  9988. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  9989. server_certificate_verification_ = rhs.server_certificate_verification_;
  9990. server_hostname_verification_ = rhs.server_hostname_verification_;
  9991. #endif
  9992. }
  9993. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  9994. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9995. return detail::create_client_socket(
  9996. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  9997. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  9998. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  9999. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10000. }
  10001. // Check is custom IP specified for host_
  10002. std::string ip;
  10003. auto it = addr_map_.find(host_);
  10004. if (it != addr_map_.end()) { ip = it->second; }
  10005. return detail::create_client_socket(
  10006. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10007. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10008. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10009. write_timeout_usec_, interface_, error);
  10010. }
  10011. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10012. Error &error) {
  10013. auto sock = create_client_socket(error);
  10014. if (sock == INVALID_SOCKET) { return false; }
  10015. socket.sock = sock;
  10016. return true;
  10017. }
  10018. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10019. return create_and_connect_socket(socket, error);
  10020. }
  10021. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10022. bool /*shutdown_gracefully*/) {
  10023. // If there are any requests in flight from threads other than us, then it's
  10024. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10025. assert(socket_requests_in_flight_ == 0 ||
  10026. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10027. }
  10028. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10029. if (socket.sock == INVALID_SOCKET) { return; }
  10030. detail::shutdown_socket(socket.sock);
  10031. }
  10032. inline void ClientImpl::close_socket(Socket &socket) {
  10033. // If there are requests in flight in another thread, usually closing
  10034. // the socket will be fine and they will simply receive an error when
  10035. // using the closed socket, but it is still a bug since rarely the OS
  10036. // may reassign the socket id to be used for a new socket, and then
  10037. // suddenly they will be operating on a live socket that is different
  10038. // than the one they intended!
  10039. assert(socket_requests_in_flight_ == 0 ||
  10040. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10041. // It is also a bug if this happens while SSL is still active
  10042. #ifdef CPPHTTPLIB_SSL_ENABLED
  10043. assert(socket.ssl == nullptr);
  10044. #endif
  10045. if (socket.sock == INVALID_SOCKET) { return; }
  10046. detail::close_socket(socket.sock);
  10047. socket.sock = INVALID_SOCKET;
  10048. }
  10049. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10050. Response &res,
  10051. bool skip_100_continue) const {
  10052. std::array<char, 2048> buf{};
  10053. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10054. if (!line_reader.getline()) { return false; }
  10055. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10056. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10057. #else
  10058. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10059. #endif
  10060. std::cmatch m;
  10061. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10062. return req.method == "CONNECT";
  10063. }
  10064. res.version = std::string(m[1]);
  10065. res.status = std::stoi(std::string(m[2]));
  10066. res.reason = std::string(m[3]);
  10067. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10068. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10069. if (!line_reader.getline()) { return false; } // CRLF
  10070. if (!line_reader.getline()) { return false; } // next response line
  10071. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10072. res.version = std::string(m[1]);
  10073. res.status = std::stoi(std::string(m[2]));
  10074. res.reason = std::string(m[3]);
  10075. }
  10076. return true;
  10077. }
  10078. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10079. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10080. auto ret = send_(req, res, error);
  10081. if (error == Error::SSLPeerCouldBeClosed_) {
  10082. assert(!ret);
  10083. ret = send_(req, res, error);
  10084. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10085. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10086. }
  10087. return ret;
  10088. }
  10089. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10090. {
  10091. std::lock_guard<std::mutex> guard(socket_mutex_);
  10092. // Set this to false immediately - if it ever gets set to true by the end
  10093. // of the request, we know another thread instructed us to close the
  10094. // socket.
  10095. socket_should_be_closed_when_request_is_done_ = false;
  10096. auto is_alive = false;
  10097. if (socket_.is_open()) {
  10098. is_alive = detail::is_socket_alive(socket_.sock);
  10099. #ifdef CPPHTTPLIB_SSL_ENABLED
  10100. if (is_alive && is_ssl()) {
  10101. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10102. is_alive = false;
  10103. }
  10104. }
  10105. #endif
  10106. if (!is_alive) {
  10107. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  10108. // seems like the other side has already closed the connection Also,
  10109. // there cannot be any requests in flight from other threads since we
  10110. // locked request_mutex_, so safe to close everything immediately
  10111. const bool shutdown_gracefully = false;
  10112. shutdown_ssl(socket_, shutdown_gracefully);
  10113. shutdown_socket(socket_);
  10114. close_socket(socket_);
  10115. }
  10116. }
  10117. if (!is_alive) {
  10118. if (!ensure_socket_connection(socket_, error)) {
  10119. output_error_log(error, &req);
  10120. return false;
  10121. }
  10122. #ifdef CPPHTTPLIB_SSL_ENABLED
  10123. // TODO: refactoring
  10124. if (is_ssl()) {
  10125. auto &scli = static_cast<SSLClient &>(*this);
  10126. if (!proxy_host_.empty() && proxy_port_ != -1) {
  10127. auto success = false;
  10128. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  10129. error)) {
  10130. if (!success) { output_error_log(error, &req); }
  10131. return success;
  10132. }
  10133. }
  10134. if (!proxy_host_.empty() && proxy_port_ != -1) {
  10135. if (!scli.initialize_ssl(socket_, error)) {
  10136. output_error_log(error, &req);
  10137. return false;
  10138. }
  10139. }
  10140. }
  10141. #endif
  10142. }
  10143. // Mark the current socket as being in use so that it cannot be closed by
  10144. // anyone else while this request is ongoing, even though we will be
  10145. // releasing the mutex.
  10146. if (socket_requests_in_flight_ > 1) {
  10147. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10148. }
  10149. socket_requests_in_flight_ += 1;
  10150. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10151. }
  10152. for (const auto &header : default_headers_) {
  10153. if (req.headers.find(header.first) == req.headers.end()) {
  10154. req.headers.insert(header);
  10155. }
  10156. }
  10157. auto ret = false;
  10158. auto close_connection = !keep_alive_;
  10159. auto se = detail::scope_exit([&]() {
  10160. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10161. std::lock_guard<std::mutex> guard(socket_mutex_);
  10162. socket_requests_in_flight_ -= 1;
  10163. if (socket_requests_in_flight_ <= 0) {
  10164. assert(socket_requests_in_flight_ == 0);
  10165. socket_requests_are_from_thread_ = std::thread::id();
  10166. }
  10167. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10168. !ret) {
  10169. shutdown_ssl(socket_, true);
  10170. shutdown_socket(socket_);
  10171. close_socket(socket_);
  10172. }
  10173. });
  10174. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  10175. return handle_request(strm, req, res, close_connection, error);
  10176. });
  10177. if (!ret) {
  10178. if (error == Error::Success) {
  10179. error = Error::Unknown;
  10180. output_error_log(error, &req);
  10181. }
  10182. }
  10183. return ret;
  10184. }
  10185. inline Result ClientImpl::send(const Request &req) {
  10186. auto req2 = req;
  10187. return send_(std::move(req2));
  10188. }
  10189. inline Result ClientImpl::send_(Request &&req) {
  10190. auto res = detail::make_unique<Response>();
  10191. auto error = Error::Success;
  10192. auto ret = send(req, *res, error);
  10193. #ifdef CPPHTTPLIB_SSL_ENABLED
  10194. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  10195. last_ssl_error_, last_backend_error_};
  10196. #else
  10197. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  10198. #endif
  10199. }
  10200. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  10201. const std::string &ct) {
  10202. (void)for_stream;
  10203. for (const auto &header : default_headers_) {
  10204. if (!r.has_header(header.first)) { r.headers.insert(header); }
  10205. }
  10206. if (!r.has_header("Host")) {
  10207. if (address_family_ == AF_UNIX) {
  10208. r.headers.emplace("Host", "localhost");
  10209. } else {
  10210. r.headers.emplace(
  10211. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  10212. }
  10213. }
  10214. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  10215. if (!r.content_receiver) {
  10216. if (!r.has_header("Accept-Encoding")) {
  10217. std::string accept_encoding;
  10218. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10219. accept_encoding = "br";
  10220. #endif
  10221. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10222. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10223. accept_encoding += "gzip, deflate";
  10224. #endif
  10225. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10226. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10227. accept_encoding += "zstd";
  10228. #endif
  10229. r.set_header("Accept-Encoding", accept_encoding);
  10230. }
  10231. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  10232. if (!r.has_header("User-Agent")) {
  10233. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  10234. r.set_header("User-Agent", agent);
  10235. }
  10236. #endif
  10237. }
  10238. if (!r.body.empty()) {
  10239. if (!ct.empty() && !r.has_header("Content-Type")) {
  10240. r.headers.emplace("Content-Type", ct);
  10241. }
  10242. if (!r.has_header("Content-Length")) {
  10243. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  10244. }
  10245. }
  10246. }
  10247. inline ClientImpl::StreamHandle
  10248. ClientImpl::open_stream(const std::string &method, const std::string &path,
  10249. const Params &params, const Headers &headers,
  10250. const std::string &body,
  10251. const std::string &content_type) {
  10252. StreamHandle handle;
  10253. handle.response = detail::make_unique<Response>();
  10254. handle.error = Error::Success;
  10255. auto query_path = params.empty() ? path : append_query_params(path, params);
  10256. handle.connection_ = detail::make_unique<ClientConnection>();
  10257. {
  10258. std::lock_guard<std::mutex> guard(socket_mutex_);
  10259. auto is_alive = false;
  10260. if (socket_.is_open()) {
  10261. is_alive = detail::is_socket_alive(socket_.sock);
  10262. #ifdef CPPHTTPLIB_SSL_ENABLED
  10263. if (is_alive && is_ssl()) {
  10264. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10265. is_alive = false;
  10266. }
  10267. }
  10268. #endif
  10269. if (!is_alive) {
  10270. shutdown_ssl(socket_, false);
  10271. shutdown_socket(socket_);
  10272. close_socket(socket_);
  10273. }
  10274. }
  10275. if (!is_alive) {
  10276. if (!ensure_socket_connection(socket_, handle.error)) {
  10277. handle.response.reset();
  10278. return handle;
  10279. }
  10280. #ifdef CPPHTTPLIB_SSL_ENABLED
  10281. if (is_ssl()) {
  10282. auto &scli = static_cast<SSLClient &>(*this);
  10283. if (!proxy_host_.empty() && proxy_port_ != -1) {
  10284. if (!scli.initialize_ssl(socket_, handle.error)) {
  10285. handle.response.reset();
  10286. return handle;
  10287. }
  10288. }
  10289. }
  10290. #endif
  10291. }
  10292. transfer_socket_ownership_to_handle(handle);
  10293. }
  10294. #ifdef CPPHTTPLIB_SSL_ENABLED
  10295. if (is_ssl() && handle.connection_->session) {
  10296. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  10297. handle.connection_->sock, handle.connection_->session,
  10298. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10299. write_timeout_usec_);
  10300. } else {
  10301. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  10302. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  10303. write_timeout_sec_, write_timeout_usec_);
  10304. }
  10305. #else
  10306. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  10307. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  10308. write_timeout_sec_, write_timeout_usec_);
  10309. #endif
  10310. handle.stream_ = handle.socket_stream_.get();
  10311. Request req;
  10312. req.method = method;
  10313. req.path = query_path;
  10314. req.headers = headers;
  10315. req.body = body;
  10316. prepare_default_headers(req, true, content_type);
  10317. auto &strm = *handle.stream_;
  10318. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  10319. handle.error = Error::Write;
  10320. handle.response.reset();
  10321. return handle;
  10322. }
  10323. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  10324. handle.error)) {
  10325. handle.response.reset();
  10326. return handle;
  10327. }
  10328. if (!body.empty()) {
  10329. if (strm.write(body.data(), body.size()) < 0) {
  10330. handle.error = Error::Write;
  10331. handle.response.reset();
  10332. return handle;
  10333. }
  10334. }
  10335. if (!read_response_line(strm, req, *handle.response) ||
  10336. !detail::read_headers(strm, handle.response->headers)) {
  10337. handle.error = Error::Read;
  10338. handle.response.reset();
  10339. return handle;
  10340. }
  10341. handle.body_reader_.stream = handle.stream_;
  10342. handle.body_reader_.payload_max_length = payload_max_length_;
  10343. auto content_length_str = handle.response->get_header_value("Content-Length");
  10344. if (!content_length_str.empty()) {
  10345. handle.body_reader_.has_content_length = true;
  10346. handle.body_reader_.content_length =
  10347. static_cast<size_t>(std::stoull(content_length_str));
  10348. }
  10349. auto transfer_encoding =
  10350. handle.response->get_header_value("Transfer-Encoding");
  10351. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  10352. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  10353. if (!content_encoding.empty()) {
  10354. handle.decompressor_ = detail::create_decompressor(content_encoding);
  10355. }
  10356. return handle;
  10357. }
  10358. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  10359. if (!is_valid() || !response) { return -1; }
  10360. if (decompressor_) { return read_with_decompression(buf, len); }
  10361. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  10362. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  10363. trailers_parsed_ = true;
  10364. if (body_reader_.chunked_decoder) {
  10365. if (!body_reader_.chunked_decoder->parse_trailers_into(
  10366. response->trailers, response->headers)) {
  10367. return n;
  10368. }
  10369. } else {
  10370. detail::ChunkedDecoder dec(*stream_);
  10371. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  10372. return n;
  10373. }
  10374. }
  10375. }
  10376. return n;
  10377. }
  10378. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  10379. size_t len) {
  10380. if (decompress_offset_ < decompress_buffer_.size()) {
  10381. auto available = decompress_buffer_.size() - decompress_offset_;
  10382. auto to_copy = (std::min)(len, available);
  10383. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  10384. decompress_offset_ += to_copy;
  10385. decompressed_bytes_read_ += to_copy;
  10386. return static_cast<ssize_t>(to_copy);
  10387. }
  10388. decompress_buffer_.clear();
  10389. decompress_offset_ = 0;
  10390. constexpr size_t kDecompressionBufferSize = 8192;
  10391. char compressed_buf[kDecompressionBufferSize];
  10392. while (true) {
  10393. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  10394. sizeof(compressed_buf));
  10395. if (n <= 0) { return n; }
  10396. bool decompress_ok = decompressor_->decompress(
  10397. compressed_buf, static_cast<size_t>(n),
  10398. [this](const char *data, size_t data_len) {
  10399. decompress_buffer_.append(data, data_len);
  10400. auto limit = body_reader_.payload_max_length;
  10401. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  10402. return false;
  10403. }
  10404. return true;
  10405. });
  10406. if (!decompress_ok) {
  10407. body_reader_.last_error = Error::Read;
  10408. return -1;
  10409. }
  10410. if (!decompress_buffer_.empty()) { break; }
  10411. }
  10412. auto to_copy = (std::min)(len, decompress_buffer_.size());
  10413. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  10414. decompress_offset_ = to_copy;
  10415. decompressed_bytes_read_ += to_copy;
  10416. return static_cast<ssize_t>(to_copy);
  10417. }
  10418. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  10419. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  10420. return;
  10421. }
  10422. trailers_parsed_ = true;
  10423. const auto bufsiz = 128;
  10424. char line_buf[bufsiz];
  10425. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  10426. if (!line_reader.getline()) { return; }
  10427. if (!detail::parse_trailers(line_reader, response->trailers,
  10428. response->headers)) {
  10429. return;
  10430. }
  10431. }
  10432. namespace detail {
  10433. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  10434. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  10435. size_t &out_chunk_offset,
  10436. size_t &out_chunk_total) {
  10437. if (finished) { return 0; }
  10438. if (chunk_remaining == 0) {
  10439. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10440. if (!lr.getline()) { return -1; }
  10441. char *endptr = nullptr;
  10442. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  10443. if (endptr == lr.ptr()) { return -1; }
  10444. if (chunk_len == ULONG_MAX) { return -1; }
  10445. if (chunk_len == 0) {
  10446. chunk_remaining = 0;
  10447. finished = true;
  10448. out_chunk_offset = 0;
  10449. out_chunk_total = 0;
  10450. return 0;
  10451. }
  10452. chunk_remaining = static_cast<size_t>(chunk_len);
  10453. last_chunk_total = chunk_remaining;
  10454. last_chunk_offset = 0;
  10455. }
  10456. auto to_read = (std::min)(chunk_remaining, len);
  10457. auto n = strm.read(buf, to_read);
  10458. if (n <= 0) { return -1; }
  10459. auto offset_before = last_chunk_offset;
  10460. last_chunk_offset += static_cast<size_t>(n);
  10461. chunk_remaining -= static_cast<size_t>(n);
  10462. out_chunk_offset = offset_before;
  10463. out_chunk_total = last_chunk_total;
  10464. if (chunk_remaining == 0) {
  10465. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10466. if (!lr.getline()) { return -1; }
  10467. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  10468. }
  10469. return n;
  10470. }
  10471. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  10472. const Headers &src_headers) {
  10473. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10474. if (!lr.getline()) { return false; }
  10475. return parse_trailers(lr, dest, src_headers);
  10476. }
  10477. } // namespace detail
  10478. inline void
  10479. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  10480. handle.connection_->sock = socket_.sock;
  10481. #ifdef CPPHTTPLIB_SSL_ENABLED
  10482. handle.connection_->session = socket_.ssl;
  10483. socket_.ssl = nullptr;
  10484. #endif
  10485. socket_.sock = INVALID_SOCKET;
  10486. }
  10487. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  10488. Response &res, bool close_connection,
  10489. Error &error) {
  10490. if (req.path.empty()) {
  10491. error = Error::Connection;
  10492. output_error_log(error, &req);
  10493. return false;
  10494. }
  10495. auto req_save = req;
  10496. bool ret;
  10497. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  10498. auto req2 = req;
  10499. req2.path = "http://" +
  10500. detail::make_host_and_port_string(host_, port_, false) +
  10501. req.path;
  10502. ret = process_request(strm, req2, res, close_connection, error);
  10503. req = std::move(req2);
  10504. req.path = req_save.path;
  10505. } else {
  10506. ret = process_request(strm, req, res, close_connection, error);
  10507. }
  10508. if (!ret) { return false; }
  10509. if (res.get_header_value("Connection") == "close" ||
  10510. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  10511. // TODO this requires a not-entirely-obvious chain of calls to be correct
  10512. // for this to be safe.
  10513. // This is safe to call because handle_request is only called by send_
  10514. // which locks the request mutex during the process. It would be a bug
  10515. // to call it from a different thread since it's a thread-safety issue
  10516. // to do these things to the socket if another thread is using the socket.
  10517. std::lock_guard<std::mutex> guard(socket_mutex_);
  10518. shutdown_ssl(socket_, true);
  10519. shutdown_socket(socket_);
  10520. close_socket(socket_);
  10521. }
  10522. if (300 < res.status && res.status < 400 && follow_location_) {
  10523. req = std::move(req_save);
  10524. ret = redirect(req, res, error);
  10525. }
  10526. #ifdef CPPHTTPLIB_SSL_ENABLED
  10527. if ((res.status == StatusCode::Unauthorized_401 ||
  10528. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  10529. req.authorization_count_ < 5) {
  10530. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  10531. const auto &username =
  10532. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  10533. const auto &password =
  10534. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  10535. if (!username.empty() && !password.empty()) {
  10536. std::map<std::string, std::string> auth;
  10537. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  10538. Request new_req = req;
  10539. new_req.authorization_count_ += 1;
  10540. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  10541. : "Authorization");
  10542. new_req.headers.insert(detail::make_digest_authentication_header(
  10543. req, auth, new_req.authorization_count_, detail::random_string(10),
  10544. username, password, is_proxy));
  10545. Response new_res;
  10546. ret = send(new_req, new_res, error);
  10547. if (ret) { res = std::move(new_res); }
  10548. }
  10549. }
  10550. }
  10551. #endif
  10552. return ret;
  10553. }
  10554. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  10555. if (req.redirect_count_ == 0) {
  10556. error = Error::ExceedRedirectCount;
  10557. output_error_log(error, &req);
  10558. return false;
  10559. }
  10560. auto location = res.get_header_value("location");
  10561. if (location.empty()) { return false; }
  10562. thread_local const std::regex re(
  10563. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  10564. std::smatch m;
  10565. if (!std::regex_match(location, m, re)) { return false; }
  10566. auto scheme = is_ssl() ? "https" : "http";
  10567. auto next_scheme = m[1].str();
  10568. auto next_host = m[2].str();
  10569. if (next_host.empty()) { next_host = m[3].str(); }
  10570. auto port_str = m[4].str();
  10571. auto next_path = m[5].str();
  10572. auto next_query = m[6].str();
  10573. auto next_port = port_;
  10574. if (!port_str.empty()) {
  10575. next_port = std::stoi(port_str);
  10576. } else if (!next_scheme.empty()) {
  10577. next_port = next_scheme == "https" ? 443 : 80;
  10578. }
  10579. if (next_scheme.empty()) { next_scheme = scheme; }
  10580. if (next_host.empty()) { next_host = host_; }
  10581. if (next_path.empty()) { next_path = "/"; }
  10582. auto path = decode_query_component(next_path, true) + next_query;
  10583. // Same host redirect - use current client
  10584. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  10585. return detail::redirect(*this, req, res, path, location, error);
  10586. }
  10587. // Cross-host/scheme redirect - create new client with robust setup
  10588. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  10589. path, location, error);
  10590. }
  10591. // New method for robust redirect client creation
  10592. inline bool ClientImpl::create_redirect_client(
  10593. const std::string &scheme, const std::string &host, int port, Request &req,
  10594. Response &res, const std::string &path, const std::string &location,
  10595. Error &error) {
  10596. // Determine if we need SSL
  10597. auto need_ssl = (scheme == "https");
  10598. // Clean up request headers that are host/client specific
  10599. // Remove headers that should not be carried over to new host
  10600. auto headers_to_remove =
  10601. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  10602. for (const auto &header_name : headers_to_remove) {
  10603. auto it = req.headers.find(header_name);
  10604. while (it != req.headers.end()) {
  10605. it = req.headers.erase(it);
  10606. it = req.headers.find(header_name);
  10607. }
  10608. }
  10609. // Create appropriate client type and handle redirect
  10610. if (need_ssl) {
  10611. #ifdef CPPHTTPLIB_SSL_ENABLED
  10612. // Create SSL client for HTTPS redirect
  10613. SSLClient redirect_client(host, port);
  10614. // Setup basic client configuration first
  10615. setup_redirect_client(redirect_client);
  10616. // SSL-specific configuration for proxy environments
  10617. if (!proxy_host_.empty() && proxy_port_ != -1) {
  10618. // Critical: Disable SSL verification for proxy environments
  10619. redirect_client.enable_server_certificate_verification(false);
  10620. redirect_client.enable_server_hostname_verification(false);
  10621. } else {
  10622. // For direct SSL connections, copy SSL verification settings
  10623. redirect_client.enable_server_certificate_verification(
  10624. server_certificate_verification_);
  10625. redirect_client.enable_server_hostname_verification(
  10626. server_hostname_verification_);
  10627. }
  10628. // Transfer CA certificate to redirect client
  10629. if (!ca_cert_pem_.empty()) {
  10630. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  10631. ca_cert_pem_.size());
  10632. }
  10633. if (!ca_cert_file_path_.empty()) {
  10634. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  10635. }
  10636. // Client certificates are set through constructor for SSLClient
  10637. // NOTE: SSLClient constructor already takes client_cert_path and
  10638. // client_key_path so we need to create it properly if client certs are
  10639. // needed
  10640. // Execute the redirect
  10641. return detail::redirect(redirect_client, req, res, path, location, error);
  10642. #else
  10643. // SSL not supported - set appropriate error
  10644. error = Error::SSLConnection;
  10645. output_error_log(error, &req);
  10646. return false;
  10647. #endif
  10648. } else {
  10649. // HTTP redirect
  10650. ClientImpl redirect_client(host, port);
  10651. // Setup client with robust configuration
  10652. setup_redirect_client(redirect_client);
  10653. // Execute the redirect
  10654. return detail::redirect(redirect_client, req, res, path, location, error);
  10655. }
  10656. }
  10657. // New method for robust client setup (based on basic_manual_redirect.cpp
  10658. // logic)
  10659. template <typename ClientType>
  10660. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  10661. // Copy basic settings first
  10662. client.set_connection_timeout(connection_timeout_sec_);
  10663. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  10664. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  10665. client.set_keep_alive(keep_alive_);
  10666. client.set_follow_location(
  10667. true); // Enable redirects to handle multi-step redirects
  10668. client.set_path_encode(path_encode_);
  10669. client.set_compress(compress_);
  10670. client.set_decompress(decompress_);
  10671. // Copy authentication settings BEFORE proxy setup
  10672. if (!basic_auth_username_.empty()) {
  10673. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  10674. }
  10675. if (!bearer_token_auth_token_.empty()) {
  10676. client.set_bearer_token_auth(bearer_token_auth_token_);
  10677. }
  10678. #ifdef CPPHTTPLIB_SSL_ENABLED
  10679. if (!digest_auth_username_.empty()) {
  10680. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  10681. }
  10682. #endif
  10683. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  10684. // before proxy auth)
  10685. if (!proxy_host_.empty() && proxy_port_ != -1) {
  10686. // First set proxy host and port
  10687. client.set_proxy(proxy_host_, proxy_port_);
  10688. // Then set proxy authentication (order matters!)
  10689. if (!proxy_basic_auth_username_.empty()) {
  10690. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  10691. proxy_basic_auth_password_);
  10692. }
  10693. if (!proxy_bearer_token_auth_token_.empty()) {
  10694. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  10695. }
  10696. #ifdef CPPHTTPLIB_SSL_ENABLED
  10697. if (!proxy_digest_auth_username_.empty()) {
  10698. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  10699. proxy_digest_auth_password_);
  10700. }
  10701. #endif
  10702. }
  10703. // Copy network and socket settings
  10704. client.set_address_family(address_family_);
  10705. client.set_tcp_nodelay(tcp_nodelay_);
  10706. client.set_ipv6_v6only(ipv6_v6only_);
  10707. if (socket_options_) { client.set_socket_options(socket_options_); }
  10708. if (!interface_.empty()) { client.set_interface(interface_); }
  10709. // Copy logging and headers
  10710. if (logger_) { client.set_logger(logger_); }
  10711. if (error_logger_) { client.set_error_logger(error_logger_); }
  10712. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  10713. // Each new client should generate its own headers based on its target host
  10714. }
  10715. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  10716. const Request &req,
  10717. Error &error) const {
  10718. auto is_shutting_down = []() { return false; };
  10719. if (req.is_chunked_content_provider_) {
  10720. // TODO: Brotli support
  10721. std::unique_ptr<detail::compressor> compressor;
  10722. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10723. if (compress_) {
  10724. compressor = detail::make_unique<detail::gzip_compressor>();
  10725. } else
  10726. #endif
  10727. {
  10728. compressor = detail::make_unique<detail::nocompressor>();
  10729. }
  10730. return detail::write_content_chunked(strm, req.content_provider_,
  10731. is_shutting_down, *compressor, error);
  10732. } else {
  10733. return detail::write_content_with_progress(
  10734. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  10735. req.upload_progress, error);
  10736. }
  10737. }
  10738. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  10739. bool close_connection, Error &error,
  10740. bool skip_body) {
  10741. // Prepare additional headers
  10742. if (close_connection) {
  10743. if (!req.has_header("Connection")) {
  10744. req.set_header("Connection", "close");
  10745. }
  10746. }
  10747. std::string ct_for_defaults;
  10748. if (!req.has_header("Content-Type") && !req.body.empty()) {
  10749. ct_for_defaults = "text/plain";
  10750. }
  10751. prepare_default_headers(req, false, ct_for_defaults);
  10752. if (req.body.empty()) {
  10753. if (req.content_provider_) {
  10754. if (!req.is_chunked_content_provider_) {
  10755. if (!req.has_header("Content-Length")) {
  10756. auto length = std::to_string(req.content_length_);
  10757. req.set_header("Content-Length", length);
  10758. }
  10759. }
  10760. } else {
  10761. if (req.method == "POST" || req.method == "PUT" ||
  10762. req.method == "PATCH") {
  10763. req.set_header("Content-Length", "0");
  10764. }
  10765. }
  10766. }
  10767. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  10768. if (!req.has_header("Authorization")) {
  10769. req.headers.insert(make_basic_authentication_header(
  10770. basic_auth_username_, basic_auth_password_, false));
  10771. }
  10772. }
  10773. if (!proxy_basic_auth_username_.empty() &&
  10774. !proxy_basic_auth_password_.empty()) {
  10775. if (!req.has_header("Proxy-Authorization")) {
  10776. req.headers.insert(make_basic_authentication_header(
  10777. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  10778. }
  10779. }
  10780. if (!bearer_token_auth_token_.empty()) {
  10781. if (!req.has_header("Authorization")) {
  10782. req.headers.insert(make_bearer_token_authentication_header(
  10783. bearer_token_auth_token_, false));
  10784. }
  10785. }
  10786. if (!proxy_bearer_token_auth_token_.empty()) {
  10787. if (!req.has_header("Proxy-Authorization")) {
  10788. req.headers.insert(make_bearer_token_authentication_header(
  10789. proxy_bearer_token_auth_token_, true));
  10790. }
  10791. }
  10792. // Request line and headers
  10793. {
  10794. detail::BufferStream bstrm;
  10795. // Extract path and query from req.path
  10796. std::string path_part, query_part;
  10797. auto query_pos = req.path.find('?');
  10798. if (query_pos != std::string::npos) {
  10799. path_part = req.path.substr(0, query_pos);
  10800. query_part = req.path.substr(query_pos + 1);
  10801. } else {
  10802. path_part = req.path;
  10803. query_part = "";
  10804. }
  10805. // Encode path part. If the original `req.path` already contained a
  10806. // query component, preserve its raw query string (including parameter
  10807. // order) instead of reparsing and reassembling it which may reorder
  10808. // parameters due to container ordering (e.g. `Params` uses
  10809. // `std::multimap`). When there is no query in `req.path`, fall back to
  10810. // building a query from `req.params` so existing callers that pass
  10811. // `Params` continue to work.
  10812. auto path_with_query =
  10813. path_encode_ ? detail::encode_path(path_part) : path_part;
  10814. if (!query_part.empty()) {
  10815. // Normalize the query string (decode then re-encode) while preserving
  10816. // the original parameter order.
  10817. auto normalized = detail::normalize_query_string(query_part);
  10818. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  10819. // Still populate req.params for handlers/users who read them.
  10820. detail::parse_query_text(query_part, req.params);
  10821. } else {
  10822. // No query in path; parse any query_part (empty) and append params
  10823. // from `req.params` when present (preserves prior behavior for
  10824. // callers who provide Params separately).
  10825. detail::parse_query_text(query_part, req.params);
  10826. if (!req.params.empty()) {
  10827. path_with_query = append_query_params(path_with_query, req.params);
  10828. }
  10829. }
  10830. // Write request line and headers
  10831. detail::write_request_line(bstrm, req.method, path_with_query);
  10832. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  10833. error)) {
  10834. output_error_log(error, &req);
  10835. return false;
  10836. }
  10837. // Flush buffer
  10838. auto &data = bstrm.get_buffer();
  10839. if (!detail::write_data(strm, data.data(), data.size())) {
  10840. error = Error::Write;
  10841. output_error_log(error, &req);
  10842. return false;
  10843. }
  10844. }
  10845. // After sending request line and headers, wait briefly for an early server
  10846. // response (e.g. 4xx) and avoid sending a potentially large request body
  10847. // unnecessarily. This workaround is only enabled on Windows because Unix
  10848. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  10849. // buffering can accept large writes even when the peer already responded.
  10850. // Check the stream first (which covers SSL via `is_readable()`), then
  10851. // fall back to select on the socket. Only perform the wait for very large
  10852. // request bodies to avoid interfering with normal small requests and
  10853. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  10854. // response. Skip this check when using Expect: 100-continue, as the protocol
  10855. // handles early responses properly.
  10856. #if defined(_WIN32)
  10857. if (!skip_body &&
  10858. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  10859. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10860. auto start = std::chrono::high_resolution_clock::now();
  10861. for (;;) {
  10862. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  10863. // from SSL internals. If the underlying socket is readable, assume an
  10864. // early response may be present.
  10865. auto sock = strm.socket();
  10866. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  10867. return false;
  10868. }
  10869. // Fallback to stream-level check for non-socket streams or when the
  10870. // socket isn't reporting readable. Avoid using `is_readable()` for
  10871. // SSL, since `SSL_pending()` may report buffered records that do not
  10872. // indicate a complete application-level response yet.
  10873. if (!is_ssl() && strm.is_readable()) { return false; }
  10874. auto now = std::chrono::high_resolution_clock::now();
  10875. auto elapsed =
  10876. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  10877. .count();
  10878. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  10879. break;
  10880. }
  10881. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  10882. }
  10883. }
  10884. #endif
  10885. // Body
  10886. if (skip_body) { return true; }
  10887. return write_request_body(strm, req, error);
  10888. }
  10889. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  10890. Error &error) {
  10891. if (req.body.empty()) {
  10892. return write_content_with_provider(strm, req, error);
  10893. }
  10894. if (req.upload_progress) {
  10895. auto body_size = req.body.size();
  10896. size_t written = 0;
  10897. auto data = req.body.data();
  10898. while (written < body_size) {
  10899. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  10900. if (!detail::write_data(strm, data + written, to_write)) {
  10901. error = Error::Write;
  10902. output_error_log(error, &req);
  10903. return false;
  10904. }
  10905. written += to_write;
  10906. if (!req.upload_progress(written, body_size)) {
  10907. error = Error::Canceled;
  10908. output_error_log(error, &req);
  10909. return false;
  10910. }
  10911. }
  10912. } else {
  10913. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  10914. error = Error::Write;
  10915. output_error_log(error, &req);
  10916. return false;
  10917. }
  10918. }
  10919. return true;
  10920. }
  10921. inline std::unique_ptr<Response>
  10922. ClientImpl::send_with_content_provider_and_receiver(
  10923. Request &req, const char *body, size_t content_length,
  10924. ContentProvider content_provider,
  10925. ContentProviderWithoutLength content_provider_without_length,
  10926. const std::string &content_type, ContentReceiver content_receiver,
  10927. Error &error) {
  10928. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10929. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10930. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  10931. #endif
  10932. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10933. if (compress_ && !content_provider_without_length) {
  10934. // TODO: Brotli support
  10935. detail::gzip_compressor compressor;
  10936. if (content_provider) {
  10937. auto ok = true;
  10938. size_t offset = 0;
  10939. DataSink data_sink;
  10940. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  10941. if (ok) {
  10942. auto last = offset + data_len == content_length;
  10943. auto ret = compressor.compress(
  10944. data, data_len, last,
  10945. [&](const char *compressed_data, size_t compressed_data_len) {
  10946. req.body.append(compressed_data, compressed_data_len);
  10947. return true;
  10948. });
  10949. if (ret) {
  10950. offset += data_len;
  10951. } else {
  10952. ok = false;
  10953. }
  10954. }
  10955. return ok;
  10956. };
  10957. while (ok && offset < content_length) {
  10958. if (!content_provider(offset, content_length - offset, data_sink)) {
  10959. error = Error::Canceled;
  10960. output_error_log(error, &req);
  10961. return nullptr;
  10962. }
  10963. }
  10964. } else {
  10965. if (!compressor.compress(body, content_length, true,
  10966. [&](const char *data, size_t data_len) {
  10967. req.body.append(data, data_len);
  10968. return true;
  10969. })) {
  10970. error = Error::Compression;
  10971. output_error_log(error, &req);
  10972. return nullptr;
  10973. }
  10974. }
  10975. } else
  10976. #endif
  10977. {
  10978. if (content_provider) {
  10979. req.content_length_ = content_length;
  10980. req.content_provider_ = std::move(content_provider);
  10981. req.is_chunked_content_provider_ = false;
  10982. } else if (content_provider_without_length) {
  10983. req.content_length_ = 0;
  10984. req.content_provider_ = detail::ContentProviderAdapter(
  10985. std::move(content_provider_without_length));
  10986. req.is_chunked_content_provider_ = true;
  10987. req.set_header("Transfer-Encoding", "chunked");
  10988. } else {
  10989. req.body.assign(body, content_length);
  10990. }
  10991. }
  10992. if (content_receiver) {
  10993. req.content_receiver =
  10994. [content_receiver](const char *data, size_t data_length,
  10995. size_t /*offset*/, size_t /*total_length*/) {
  10996. return content_receiver(data, data_length);
  10997. };
  10998. }
  10999. auto res = detail::make_unique<Response>();
  11000. return send(req, *res, error) ? std::move(res) : nullptr;
  11001. }
  11002. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11003. const std::string &method, const std::string &path, const Headers &headers,
  11004. const char *body, size_t content_length, ContentProvider content_provider,
  11005. ContentProviderWithoutLength content_provider_without_length,
  11006. const std::string &content_type, ContentReceiver content_receiver,
  11007. UploadProgress progress) {
  11008. Request req;
  11009. req.method = method;
  11010. req.headers = headers;
  11011. req.path = path;
  11012. req.upload_progress = std::move(progress);
  11013. if (max_timeout_msec_ > 0) {
  11014. req.start_time_ = std::chrono::steady_clock::now();
  11015. }
  11016. auto error = Error::Success;
  11017. auto res = send_with_content_provider_and_receiver(
  11018. req, body, content_length, std::move(content_provider),
  11019. std::move(content_provider_without_length), content_type,
  11020. std::move(content_receiver), error);
  11021. #ifdef CPPHTTPLIB_SSL_ENABLED
  11022. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11023. last_backend_error_};
  11024. #else
  11025. return Result{std::move(res), error, std::move(req.headers)};
  11026. #endif
  11027. }
  11028. inline void ClientImpl::output_log(const Request &req,
  11029. const Response &res) const {
  11030. if (logger_) {
  11031. std::lock_guard<std::mutex> guard(logger_mutex_);
  11032. logger_(req, res);
  11033. }
  11034. }
  11035. inline void ClientImpl::output_error_log(const Error &err,
  11036. const Request *req) const {
  11037. if (error_logger_) {
  11038. std::lock_guard<std::mutex> guard(logger_mutex_);
  11039. error_logger_(err, req);
  11040. }
  11041. }
  11042. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11043. Response &res, bool close_connection,
  11044. Error &error) {
  11045. // Auto-add Expect: 100-continue for large bodies
  11046. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11047. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11048. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11049. req.set_header("Expect", "100-continue");
  11050. }
  11051. }
  11052. // Check for Expect: 100-continue
  11053. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11054. // Send request (skip body if using Expect: 100-continue)
  11055. auto write_request_success =
  11056. write_request(strm, req, close_connection, error, expect_100_continue);
  11057. #ifdef CPPHTTPLIB_SSL_ENABLED
  11058. if (is_ssl() && !expect_100_continue) {
  11059. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  11060. if (!is_proxy_enabled) {
  11061. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11062. error = Error::SSLPeerCouldBeClosed_;
  11063. output_error_log(error, &req);
  11064. return false;
  11065. }
  11066. }
  11067. }
  11068. #endif
  11069. // Handle Expect: 100-continue with timeout
  11070. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11071. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11072. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11073. auto ret = detail::select_read(strm.socket(), sec, usec);
  11074. if (ret <= 0) {
  11075. // Timeout or error: send body anyway (server didn't respond in time)
  11076. if (!write_request_body(strm, req, error)) { return false; }
  11077. expect_100_continue = false; // Switch to normal response handling
  11078. }
  11079. }
  11080. // Receive response and headers
  11081. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11082. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  11083. !detail::read_headers(strm, res.headers)) {
  11084. if (write_request_success) { error = Error::Read; }
  11085. output_error_log(error, &req);
  11086. return false;
  11087. }
  11088. if (!write_request_success) { return false; }
  11089. // Handle Expect: 100-continue response
  11090. if (expect_100_continue) {
  11091. if (res.status == StatusCode::Continue_100) {
  11092. // Server accepted, send the body
  11093. if (!write_request_body(strm, req, error)) { return false; }
  11094. // Read the actual response
  11095. res.headers.clear();
  11096. res.body.clear();
  11097. if (!read_response_line(strm, req, res) ||
  11098. !detail::read_headers(strm, res.headers)) {
  11099. error = Error::Read;
  11100. output_error_log(error, &req);
  11101. return false;
  11102. }
  11103. }
  11104. // If not 100 Continue, server returned an error; proceed with that response
  11105. }
  11106. // Body
  11107. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11108. req.method != "CONNECT") {
  11109. auto redirect = 300 < res.status && res.status < 400 &&
  11110. res.status != StatusCode::NotModified_304 &&
  11111. follow_location_;
  11112. if (req.response_handler && !redirect) {
  11113. if (!req.response_handler(res)) {
  11114. error = Error::Canceled;
  11115. output_error_log(error, &req);
  11116. return false;
  11117. }
  11118. }
  11119. auto out =
  11120. req.content_receiver
  11121. ? static_cast<ContentReceiverWithProgress>(
  11122. [&](const char *buf, size_t n, size_t off, size_t len) {
  11123. if (redirect) { return true; }
  11124. auto ret = req.content_receiver(buf, n, off, len);
  11125. if (!ret) {
  11126. error = Error::Canceled;
  11127. output_error_log(error, &req);
  11128. }
  11129. return ret;
  11130. })
  11131. : static_cast<ContentReceiverWithProgress>(
  11132. [&](const char *buf, size_t n, size_t /*off*/,
  11133. size_t /*len*/) {
  11134. assert(res.body.size() + n <= res.body.max_size());
  11135. if (payload_max_length_ > 0 &&
  11136. (res.body.size() >= payload_max_length_ ||
  11137. n > payload_max_length_ - res.body.size())) {
  11138. return false;
  11139. }
  11140. res.body.append(buf, n);
  11141. return true;
  11142. });
  11143. auto progress = [&](size_t current, size_t total) {
  11144. if (!req.download_progress || redirect) { return true; }
  11145. auto ret = req.download_progress(current, total);
  11146. if (!ret) {
  11147. error = Error::Canceled;
  11148. output_error_log(error, &req);
  11149. }
  11150. return ret;
  11151. };
  11152. if (res.has_header("Content-Length")) {
  11153. if (!req.content_receiver) {
  11154. auto len = res.get_header_value_u64("Content-Length");
  11155. if (len > res.body.max_size()) {
  11156. error = Error::Read;
  11157. output_error_log(error, &req);
  11158. return false;
  11159. }
  11160. res.body.reserve(static_cast<size_t>(len));
  11161. }
  11162. }
  11163. if (res.status != StatusCode::NotModified_304) {
  11164. int dummy_status;
  11165. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  11166. ? (std::numeric_limits<size_t>::max)()
  11167. : payload_max_length_;
  11168. if (!detail::read_content(strm, res, max_length, dummy_status,
  11169. std::move(progress), std::move(out),
  11170. decompress_)) {
  11171. if (error != Error::Canceled) { error = Error::Read; }
  11172. output_error_log(error, &req);
  11173. return false;
  11174. }
  11175. }
  11176. }
  11177. // Log
  11178. output_log(req, res);
  11179. return true;
  11180. }
  11181. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  11182. const std::string &boundary, const UploadFormDataItems &items,
  11183. const FormDataProviderItems &provider_items) const {
  11184. size_t cur_item = 0;
  11185. size_t cur_start = 0;
  11186. // cur_item and cur_start are copied to within the std::function and
  11187. // maintain state between successive calls
  11188. return [&, cur_item, cur_start](size_t offset,
  11189. DataSink &sink) mutable -> bool {
  11190. if (!offset && !items.empty()) {
  11191. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  11192. return true;
  11193. } else if (cur_item < provider_items.size()) {
  11194. if (!cur_start) {
  11195. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  11196. provider_items[cur_item], boundary);
  11197. offset += begin.size();
  11198. cur_start = offset;
  11199. sink.os << begin;
  11200. }
  11201. DataSink cur_sink;
  11202. auto has_data = true;
  11203. cur_sink.write = sink.write;
  11204. cur_sink.done = [&]() { has_data = false; };
  11205. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  11206. return false;
  11207. }
  11208. if (!has_data) {
  11209. sink.os << detail::serialize_multipart_formdata_item_end();
  11210. cur_item++;
  11211. cur_start = 0;
  11212. }
  11213. return true;
  11214. } else {
  11215. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  11216. sink.done();
  11217. return true;
  11218. }
  11219. };
  11220. }
  11221. inline bool ClientImpl::process_socket(
  11222. const Socket &socket,
  11223. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11224. std::function<bool(Stream &strm)> callback) {
  11225. return detail::process_client_socket(
  11226. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11227. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  11228. }
  11229. inline bool ClientImpl::is_ssl() const { return false; }
  11230. inline Result ClientImpl::Get(const std::string &path,
  11231. DownloadProgress progress) {
  11232. return Get(path, Headers(), std::move(progress));
  11233. }
  11234. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11235. const Headers &headers,
  11236. DownloadProgress progress) {
  11237. if (params.empty()) { return Get(path, headers); }
  11238. std::string path_with_query = append_query_params(path, params);
  11239. return Get(path_with_query, headers, std::move(progress));
  11240. }
  11241. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11242. DownloadProgress progress) {
  11243. Request req;
  11244. req.method = "GET";
  11245. req.path = path;
  11246. req.headers = headers;
  11247. req.download_progress = std::move(progress);
  11248. if (max_timeout_msec_ > 0) {
  11249. req.start_time_ = std::chrono::steady_clock::now();
  11250. }
  11251. return send_(std::move(req));
  11252. }
  11253. inline Result ClientImpl::Get(const std::string &path,
  11254. ContentReceiver content_receiver,
  11255. DownloadProgress progress) {
  11256. return Get(path, Headers(), nullptr, std::move(content_receiver),
  11257. std::move(progress));
  11258. }
  11259. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11260. ContentReceiver content_receiver,
  11261. DownloadProgress progress) {
  11262. return Get(path, headers, nullptr, std::move(content_receiver),
  11263. std::move(progress));
  11264. }
  11265. inline Result ClientImpl::Get(const std::string &path,
  11266. ResponseHandler response_handler,
  11267. ContentReceiver content_receiver,
  11268. DownloadProgress progress) {
  11269. return Get(path, Headers(), std::move(response_handler),
  11270. std::move(content_receiver), std::move(progress));
  11271. }
  11272. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11273. ResponseHandler response_handler,
  11274. ContentReceiver content_receiver,
  11275. DownloadProgress progress) {
  11276. Request req;
  11277. req.method = "GET";
  11278. req.path = path;
  11279. req.headers = headers;
  11280. req.response_handler = std::move(response_handler);
  11281. req.content_receiver =
  11282. [content_receiver](const char *data, size_t data_length,
  11283. size_t /*offset*/, size_t /*total_length*/) {
  11284. return content_receiver(data, data_length);
  11285. };
  11286. req.download_progress = std::move(progress);
  11287. if (max_timeout_msec_ > 0) {
  11288. req.start_time_ = std::chrono::steady_clock::now();
  11289. }
  11290. return send_(std::move(req));
  11291. }
  11292. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11293. const Headers &headers,
  11294. ContentReceiver content_receiver,
  11295. DownloadProgress progress) {
  11296. return Get(path, params, headers, nullptr, std::move(content_receiver),
  11297. std::move(progress));
  11298. }
  11299. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11300. const Headers &headers,
  11301. ResponseHandler response_handler,
  11302. ContentReceiver content_receiver,
  11303. DownloadProgress progress) {
  11304. if (params.empty()) {
  11305. return Get(path, headers, std::move(response_handler),
  11306. std::move(content_receiver), std::move(progress));
  11307. }
  11308. std::string path_with_query = append_query_params(path, params);
  11309. return Get(path_with_query, headers, std::move(response_handler),
  11310. std::move(content_receiver), std::move(progress));
  11311. }
  11312. inline Result ClientImpl::Head(const std::string &path) {
  11313. return Head(path, Headers());
  11314. }
  11315. inline Result ClientImpl::Head(const std::string &path,
  11316. const Headers &headers) {
  11317. Request req;
  11318. req.method = "HEAD";
  11319. req.headers = headers;
  11320. req.path = path;
  11321. if (max_timeout_msec_ > 0) {
  11322. req.start_time_ = std::chrono::steady_clock::now();
  11323. }
  11324. return send_(std::move(req));
  11325. }
  11326. inline Result ClientImpl::Post(const std::string &path) {
  11327. return Post(path, std::string(), std::string());
  11328. }
  11329. inline Result ClientImpl::Post(const std::string &path,
  11330. const Headers &headers) {
  11331. return Post(path, headers, nullptr, 0, std::string());
  11332. }
  11333. inline Result ClientImpl::Post(const std::string &path, const char *body,
  11334. size_t content_length,
  11335. const std::string &content_type,
  11336. UploadProgress progress) {
  11337. return Post(path, Headers(), body, content_length, content_type, progress);
  11338. }
  11339. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  11340. const std::string &content_type,
  11341. UploadProgress progress) {
  11342. return Post(path, Headers(), body, content_type, progress);
  11343. }
  11344. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  11345. return Post(path, Headers(), params);
  11346. }
  11347. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  11348. ContentProvider content_provider,
  11349. const std::string &content_type,
  11350. UploadProgress progress) {
  11351. return Post(path, Headers(), content_length, std::move(content_provider),
  11352. content_type, progress);
  11353. }
  11354. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  11355. ContentProvider content_provider,
  11356. const std::string &content_type,
  11357. ContentReceiver content_receiver,
  11358. UploadProgress progress) {
  11359. return Post(path, Headers(), content_length, std::move(content_provider),
  11360. content_type, std::move(content_receiver), progress);
  11361. }
  11362. inline Result ClientImpl::Post(const std::string &path,
  11363. ContentProviderWithoutLength content_provider,
  11364. const std::string &content_type,
  11365. UploadProgress progress) {
  11366. return Post(path, Headers(), std::move(content_provider), content_type,
  11367. progress);
  11368. }
  11369. inline Result ClientImpl::Post(const std::string &path,
  11370. ContentProviderWithoutLength content_provider,
  11371. const std::string &content_type,
  11372. ContentReceiver content_receiver,
  11373. UploadProgress progress) {
  11374. return Post(path, Headers(), std::move(content_provider), content_type,
  11375. std::move(content_receiver), progress);
  11376. }
  11377. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11378. const Params &params) {
  11379. auto query = detail::params_to_query_str(params);
  11380. return Post(path, headers, query, "application/x-www-form-urlencoded");
  11381. }
  11382. inline Result ClientImpl::Post(const std::string &path,
  11383. const UploadFormDataItems &items,
  11384. UploadProgress progress) {
  11385. return Post(path, Headers(), items, progress);
  11386. }
  11387. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11388. const UploadFormDataItems &items,
  11389. UploadProgress progress) {
  11390. const auto &boundary = detail::make_multipart_data_boundary();
  11391. const auto &content_type =
  11392. detail::serialize_multipart_formdata_get_content_type(boundary);
  11393. auto content_length = detail::get_multipart_content_length(items, boundary);
  11394. return Post(path, headers, content_length,
  11395. detail::make_multipart_content_provider(items, boundary),
  11396. content_type, progress);
  11397. }
  11398. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11399. const UploadFormDataItems &items,
  11400. const std::string &boundary,
  11401. UploadProgress progress) {
  11402. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  11403. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  11404. }
  11405. const auto &content_type =
  11406. detail::serialize_multipart_formdata_get_content_type(boundary);
  11407. auto content_length = detail::get_multipart_content_length(items, boundary);
  11408. return Post(path, headers, content_length,
  11409. detail::make_multipart_content_provider(items, boundary),
  11410. content_type, progress);
  11411. }
  11412. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11413. const char *body, size_t content_length,
  11414. const std::string &content_type,
  11415. UploadProgress progress) {
  11416. return send_with_content_provider_and_receiver(
  11417. "POST", path, headers, body, content_length, nullptr, nullptr,
  11418. content_type, nullptr, progress);
  11419. }
  11420. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11421. const std::string &body,
  11422. const std::string &content_type,
  11423. UploadProgress progress) {
  11424. return send_with_content_provider_and_receiver(
  11425. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  11426. content_type, nullptr, progress);
  11427. }
  11428. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11429. size_t content_length,
  11430. ContentProvider content_provider,
  11431. const std::string &content_type,
  11432. UploadProgress progress) {
  11433. return send_with_content_provider_and_receiver(
  11434. "POST", path, headers, nullptr, content_length,
  11435. std::move(content_provider), nullptr, content_type, nullptr, progress);
  11436. }
  11437. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11438. size_t content_length,
  11439. ContentProvider content_provider,
  11440. const std::string &content_type,
  11441. ContentReceiver content_receiver,
  11442. DownloadProgress progress) {
  11443. return send_with_content_provider_and_receiver(
  11444. "POST", path, headers, nullptr, content_length,
  11445. std::move(content_provider), nullptr, content_type,
  11446. std::move(content_receiver), std::move(progress));
  11447. }
  11448. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11449. ContentProviderWithoutLength content_provider,
  11450. const std::string &content_type,
  11451. UploadProgress progress) {
  11452. return send_with_content_provider_and_receiver(
  11453. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11454. content_type, nullptr, progress);
  11455. }
  11456. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11457. ContentProviderWithoutLength content_provider,
  11458. const std::string &content_type,
  11459. ContentReceiver content_receiver,
  11460. DownloadProgress progress) {
  11461. return send_with_content_provider_and_receiver(
  11462. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11463. content_type, std::move(content_receiver), std::move(progress));
  11464. }
  11465. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11466. const UploadFormDataItems &items,
  11467. const FormDataProviderItems &provider_items,
  11468. UploadProgress progress) {
  11469. const auto &boundary = detail::make_multipart_data_boundary();
  11470. const auto &content_type =
  11471. detail::serialize_multipart_formdata_get_content_type(boundary);
  11472. return send_with_content_provider_and_receiver(
  11473. "POST", path, headers, nullptr, 0, nullptr,
  11474. get_multipart_content_provider(boundary, items, provider_items),
  11475. content_type, nullptr, progress);
  11476. }
  11477. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11478. const std::string &body,
  11479. const std::string &content_type,
  11480. ContentReceiver content_receiver,
  11481. DownloadProgress progress) {
  11482. Request req;
  11483. req.method = "POST";
  11484. req.path = path;
  11485. req.headers = headers;
  11486. req.body = body;
  11487. req.content_receiver =
  11488. [content_receiver](const char *data, size_t data_length,
  11489. size_t /*offset*/, size_t /*total_length*/) {
  11490. return content_receiver(data, data_length);
  11491. };
  11492. req.download_progress = std::move(progress);
  11493. if (max_timeout_msec_ > 0) {
  11494. req.start_time_ = std::chrono::steady_clock::now();
  11495. }
  11496. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11497. return send_(std::move(req));
  11498. }
  11499. inline Result ClientImpl::Put(const std::string &path) {
  11500. return Put(path, std::string(), std::string());
  11501. }
  11502. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  11503. return Put(path, headers, nullptr, 0, std::string());
  11504. }
  11505. inline Result ClientImpl::Put(const std::string &path, const char *body,
  11506. size_t content_length,
  11507. const std::string &content_type,
  11508. UploadProgress progress) {
  11509. return Put(path, Headers(), body, content_length, content_type, progress);
  11510. }
  11511. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  11512. const std::string &content_type,
  11513. UploadProgress progress) {
  11514. return Put(path, Headers(), body, content_type, progress);
  11515. }
  11516. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  11517. return Put(path, Headers(), params);
  11518. }
  11519. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  11520. ContentProvider content_provider,
  11521. const std::string &content_type,
  11522. UploadProgress progress) {
  11523. return Put(path, Headers(), content_length, std::move(content_provider),
  11524. content_type, progress);
  11525. }
  11526. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  11527. ContentProvider content_provider,
  11528. const std::string &content_type,
  11529. ContentReceiver content_receiver,
  11530. UploadProgress progress) {
  11531. return Put(path, Headers(), content_length, std::move(content_provider),
  11532. content_type, std::move(content_receiver), progress);
  11533. }
  11534. inline Result ClientImpl::Put(const std::string &path,
  11535. ContentProviderWithoutLength content_provider,
  11536. const std::string &content_type,
  11537. UploadProgress progress) {
  11538. return Put(path, Headers(), std::move(content_provider), content_type,
  11539. progress);
  11540. }
  11541. inline Result ClientImpl::Put(const std::string &path,
  11542. ContentProviderWithoutLength content_provider,
  11543. const std::string &content_type,
  11544. ContentReceiver content_receiver,
  11545. UploadProgress progress) {
  11546. return Put(path, Headers(), std::move(content_provider), content_type,
  11547. std::move(content_receiver), progress);
  11548. }
  11549. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11550. const Params &params) {
  11551. auto query = detail::params_to_query_str(params);
  11552. return Put(path, headers, query, "application/x-www-form-urlencoded");
  11553. }
  11554. inline Result ClientImpl::Put(const std::string &path,
  11555. const UploadFormDataItems &items,
  11556. UploadProgress progress) {
  11557. return Put(path, Headers(), items, progress);
  11558. }
  11559. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11560. const UploadFormDataItems &items,
  11561. UploadProgress progress) {
  11562. const auto &boundary = detail::make_multipart_data_boundary();
  11563. const auto &content_type =
  11564. detail::serialize_multipart_formdata_get_content_type(boundary);
  11565. auto content_length = detail::get_multipart_content_length(items, boundary);
  11566. return Put(path, headers, content_length,
  11567. detail::make_multipart_content_provider(items, boundary),
  11568. content_type, progress);
  11569. }
  11570. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11571. const UploadFormDataItems &items,
  11572. const std::string &boundary,
  11573. UploadProgress progress) {
  11574. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  11575. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  11576. }
  11577. const auto &content_type =
  11578. detail::serialize_multipart_formdata_get_content_type(boundary);
  11579. auto content_length = detail::get_multipart_content_length(items, boundary);
  11580. return Put(path, headers, content_length,
  11581. detail::make_multipart_content_provider(items, boundary),
  11582. content_type, progress);
  11583. }
  11584. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11585. const char *body, size_t content_length,
  11586. const std::string &content_type,
  11587. UploadProgress progress) {
  11588. return send_with_content_provider_and_receiver(
  11589. "PUT", path, headers, body, content_length, nullptr, nullptr,
  11590. content_type, nullptr, progress);
  11591. }
  11592. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11593. const std::string &body,
  11594. const std::string &content_type,
  11595. UploadProgress progress) {
  11596. return send_with_content_provider_and_receiver(
  11597. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  11598. content_type, nullptr, progress);
  11599. }
  11600. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11601. size_t content_length,
  11602. ContentProvider content_provider,
  11603. const std::string &content_type,
  11604. UploadProgress progress) {
  11605. return send_with_content_provider_and_receiver(
  11606. "PUT", path, headers, nullptr, content_length,
  11607. std::move(content_provider), nullptr, content_type, nullptr, progress);
  11608. }
  11609. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11610. size_t content_length,
  11611. ContentProvider content_provider,
  11612. const std::string &content_type,
  11613. ContentReceiver content_receiver,
  11614. UploadProgress progress) {
  11615. return send_with_content_provider_and_receiver(
  11616. "PUT", path, headers, nullptr, content_length,
  11617. std::move(content_provider), nullptr, content_type,
  11618. std::move(content_receiver), progress);
  11619. }
  11620. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11621. ContentProviderWithoutLength content_provider,
  11622. const std::string &content_type,
  11623. UploadProgress progress) {
  11624. return send_with_content_provider_and_receiver(
  11625. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11626. content_type, nullptr, progress);
  11627. }
  11628. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11629. ContentProviderWithoutLength content_provider,
  11630. const std::string &content_type,
  11631. ContentReceiver content_receiver,
  11632. UploadProgress progress) {
  11633. return send_with_content_provider_and_receiver(
  11634. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11635. content_type, std::move(content_receiver), progress);
  11636. }
  11637. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11638. const UploadFormDataItems &items,
  11639. const FormDataProviderItems &provider_items,
  11640. UploadProgress progress) {
  11641. const auto &boundary = detail::make_multipart_data_boundary();
  11642. const auto &content_type =
  11643. detail::serialize_multipart_formdata_get_content_type(boundary);
  11644. return send_with_content_provider_and_receiver(
  11645. "PUT", path, headers, nullptr, 0, nullptr,
  11646. get_multipart_content_provider(boundary, items, provider_items),
  11647. content_type, nullptr, progress);
  11648. }
  11649. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11650. const std::string &body,
  11651. const std::string &content_type,
  11652. ContentReceiver content_receiver,
  11653. DownloadProgress progress) {
  11654. Request req;
  11655. req.method = "PUT";
  11656. req.path = path;
  11657. req.headers = headers;
  11658. req.body = body;
  11659. req.content_receiver =
  11660. [content_receiver](const char *data, size_t data_length,
  11661. size_t /*offset*/, size_t /*total_length*/) {
  11662. return content_receiver(data, data_length);
  11663. };
  11664. req.download_progress = std::move(progress);
  11665. if (max_timeout_msec_ > 0) {
  11666. req.start_time_ = std::chrono::steady_clock::now();
  11667. }
  11668. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11669. return send_(std::move(req));
  11670. }
  11671. inline Result ClientImpl::Patch(const std::string &path) {
  11672. return Patch(path, std::string(), std::string());
  11673. }
  11674. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11675. UploadProgress progress) {
  11676. return Patch(path, headers, nullptr, 0, std::string(), progress);
  11677. }
  11678. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  11679. size_t content_length,
  11680. const std::string &content_type,
  11681. UploadProgress progress) {
  11682. return Patch(path, Headers(), body, content_length, content_type, progress);
  11683. }
  11684. inline Result ClientImpl::Patch(const std::string &path,
  11685. const std::string &body,
  11686. const std::string &content_type,
  11687. UploadProgress progress) {
  11688. return Patch(path, Headers(), body, content_type, progress);
  11689. }
  11690. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  11691. return Patch(path, Headers(), params);
  11692. }
  11693. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  11694. ContentProvider content_provider,
  11695. const std::string &content_type,
  11696. UploadProgress progress) {
  11697. return Patch(path, Headers(), content_length, std::move(content_provider),
  11698. content_type, progress);
  11699. }
  11700. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  11701. ContentProvider content_provider,
  11702. const std::string &content_type,
  11703. ContentReceiver content_receiver,
  11704. UploadProgress progress) {
  11705. return Patch(path, Headers(), content_length, std::move(content_provider),
  11706. content_type, std::move(content_receiver), progress);
  11707. }
  11708. inline Result ClientImpl::Patch(const std::string &path,
  11709. ContentProviderWithoutLength content_provider,
  11710. const std::string &content_type,
  11711. UploadProgress progress) {
  11712. return Patch(path, Headers(), std::move(content_provider), content_type,
  11713. progress);
  11714. }
  11715. inline Result ClientImpl::Patch(const std::string &path,
  11716. ContentProviderWithoutLength content_provider,
  11717. const std::string &content_type,
  11718. ContentReceiver content_receiver,
  11719. UploadProgress progress) {
  11720. return Patch(path, Headers(), std::move(content_provider), content_type,
  11721. std::move(content_receiver), progress);
  11722. }
  11723. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11724. const Params &params) {
  11725. auto query = detail::params_to_query_str(params);
  11726. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  11727. }
  11728. inline Result ClientImpl::Patch(const std::string &path,
  11729. const UploadFormDataItems &items,
  11730. UploadProgress progress) {
  11731. return Patch(path, Headers(), items, progress);
  11732. }
  11733. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11734. const UploadFormDataItems &items,
  11735. UploadProgress progress) {
  11736. const auto &boundary = detail::make_multipart_data_boundary();
  11737. const auto &content_type =
  11738. detail::serialize_multipart_formdata_get_content_type(boundary);
  11739. auto content_length = detail::get_multipart_content_length(items, boundary);
  11740. return Patch(path, headers, content_length,
  11741. detail::make_multipart_content_provider(items, boundary),
  11742. content_type, progress);
  11743. }
  11744. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11745. const UploadFormDataItems &items,
  11746. const std::string &boundary,
  11747. UploadProgress progress) {
  11748. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  11749. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  11750. }
  11751. const auto &content_type =
  11752. detail::serialize_multipart_formdata_get_content_type(boundary);
  11753. auto content_length = detail::get_multipart_content_length(items, boundary);
  11754. return Patch(path, headers, content_length,
  11755. detail::make_multipart_content_provider(items, boundary),
  11756. content_type, progress);
  11757. }
  11758. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11759. const char *body, size_t content_length,
  11760. const std::string &content_type,
  11761. UploadProgress progress) {
  11762. return send_with_content_provider_and_receiver(
  11763. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  11764. content_type, nullptr, progress);
  11765. }
  11766. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11767. const std::string &body,
  11768. const std::string &content_type,
  11769. UploadProgress progress) {
  11770. return send_with_content_provider_and_receiver(
  11771. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  11772. content_type, nullptr, progress);
  11773. }
  11774. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11775. size_t content_length,
  11776. ContentProvider content_provider,
  11777. const std::string &content_type,
  11778. UploadProgress progress) {
  11779. return send_with_content_provider_and_receiver(
  11780. "PATCH", path, headers, nullptr, content_length,
  11781. std::move(content_provider), nullptr, content_type, nullptr, progress);
  11782. }
  11783. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11784. size_t content_length,
  11785. ContentProvider content_provider,
  11786. const std::string &content_type,
  11787. ContentReceiver content_receiver,
  11788. UploadProgress progress) {
  11789. return send_with_content_provider_and_receiver(
  11790. "PATCH", path, headers, nullptr, content_length,
  11791. std::move(content_provider), nullptr, content_type,
  11792. std::move(content_receiver), progress);
  11793. }
  11794. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11795. ContentProviderWithoutLength content_provider,
  11796. const std::string &content_type,
  11797. UploadProgress progress) {
  11798. return send_with_content_provider_and_receiver(
  11799. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11800. content_type, nullptr, progress);
  11801. }
  11802. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11803. ContentProviderWithoutLength content_provider,
  11804. const std::string &content_type,
  11805. ContentReceiver content_receiver,
  11806. UploadProgress progress) {
  11807. return send_with_content_provider_and_receiver(
  11808. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11809. content_type, std::move(content_receiver), progress);
  11810. }
  11811. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11812. const UploadFormDataItems &items,
  11813. const FormDataProviderItems &provider_items,
  11814. UploadProgress progress) {
  11815. const auto &boundary = detail::make_multipart_data_boundary();
  11816. const auto &content_type =
  11817. detail::serialize_multipart_formdata_get_content_type(boundary);
  11818. return send_with_content_provider_and_receiver(
  11819. "PATCH", path, headers, nullptr, 0, nullptr,
  11820. get_multipart_content_provider(boundary, items, provider_items),
  11821. content_type, nullptr, progress);
  11822. }
  11823. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11824. const std::string &body,
  11825. const std::string &content_type,
  11826. ContentReceiver content_receiver,
  11827. DownloadProgress progress) {
  11828. Request req;
  11829. req.method = "PATCH";
  11830. req.path = path;
  11831. req.headers = headers;
  11832. req.body = body;
  11833. req.content_receiver =
  11834. [content_receiver](const char *data, size_t data_length,
  11835. size_t /*offset*/, size_t /*total_length*/) {
  11836. return content_receiver(data, data_length);
  11837. };
  11838. req.download_progress = std::move(progress);
  11839. if (max_timeout_msec_ > 0) {
  11840. req.start_time_ = std::chrono::steady_clock::now();
  11841. }
  11842. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11843. return send_(std::move(req));
  11844. }
  11845. inline Result ClientImpl::Delete(const std::string &path,
  11846. DownloadProgress progress) {
  11847. return Delete(path, Headers(), std::string(), std::string(), progress);
  11848. }
  11849. inline Result ClientImpl::Delete(const std::string &path,
  11850. const Headers &headers,
  11851. DownloadProgress progress) {
  11852. return Delete(path, headers, std::string(), std::string(), progress);
  11853. }
  11854. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  11855. size_t content_length,
  11856. const std::string &content_type,
  11857. DownloadProgress progress) {
  11858. return Delete(path, Headers(), body, content_length, content_type, progress);
  11859. }
  11860. inline Result ClientImpl::Delete(const std::string &path,
  11861. const std::string &body,
  11862. const std::string &content_type,
  11863. DownloadProgress progress) {
  11864. return Delete(path, Headers(), body.data(), body.size(), content_type,
  11865. progress);
  11866. }
  11867. inline Result ClientImpl::Delete(const std::string &path,
  11868. const Headers &headers,
  11869. const std::string &body,
  11870. const std::string &content_type,
  11871. DownloadProgress progress) {
  11872. return Delete(path, headers, body.data(), body.size(), content_type,
  11873. progress);
  11874. }
  11875. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  11876. DownloadProgress progress) {
  11877. return Delete(path, Headers(), params, progress);
  11878. }
  11879. inline Result ClientImpl::Delete(const std::string &path,
  11880. const Headers &headers, const Params &params,
  11881. DownloadProgress progress) {
  11882. auto query = detail::params_to_query_str(params);
  11883. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  11884. progress);
  11885. }
  11886. inline Result ClientImpl::Delete(const std::string &path,
  11887. const Headers &headers, const char *body,
  11888. size_t content_length,
  11889. const std::string &content_type,
  11890. DownloadProgress progress) {
  11891. Request req;
  11892. req.method = "DELETE";
  11893. req.headers = headers;
  11894. req.path = path;
  11895. req.download_progress = std::move(progress);
  11896. if (max_timeout_msec_ > 0) {
  11897. req.start_time_ = std::chrono::steady_clock::now();
  11898. }
  11899. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11900. req.body.assign(body, content_length);
  11901. return send_(std::move(req));
  11902. }
  11903. inline Result ClientImpl::Options(const std::string &path) {
  11904. return Options(path, Headers());
  11905. }
  11906. inline Result ClientImpl::Options(const std::string &path,
  11907. const Headers &headers) {
  11908. Request req;
  11909. req.method = "OPTIONS";
  11910. req.headers = headers;
  11911. req.path = path;
  11912. if (max_timeout_msec_ > 0) {
  11913. req.start_time_ = std::chrono::steady_clock::now();
  11914. }
  11915. return send_(std::move(req));
  11916. }
  11917. inline void ClientImpl::stop() {
  11918. std::lock_guard<std::mutex> guard(socket_mutex_);
  11919. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  11920. // do is to shutdown_socket, so that threads using this socket suddenly
  11921. // discover they can't read/write any more and error out. Everything else
  11922. // (closing the socket, shutting ssl down) is unsafe because these actions
  11923. // are not thread-safe.
  11924. if (socket_requests_in_flight_ > 0) {
  11925. shutdown_socket(socket_);
  11926. // Aside from that, we set a flag for the socket to be closed when we're
  11927. // done.
  11928. socket_should_be_closed_when_request_is_done_ = true;
  11929. return;
  11930. }
  11931. // Otherwise, still holding the mutex, we can shut everything down ourselves
  11932. shutdown_ssl(socket_, true);
  11933. shutdown_socket(socket_);
  11934. close_socket(socket_);
  11935. }
  11936. inline std::string ClientImpl::host() const { return host_; }
  11937. inline int ClientImpl::port() const { return port_; }
  11938. inline size_t ClientImpl::is_socket_open() const {
  11939. std::lock_guard<std::mutex> guard(socket_mutex_);
  11940. return socket_.is_open();
  11941. }
  11942. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  11943. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  11944. connection_timeout_sec_ = sec;
  11945. connection_timeout_usec_ = usec;
  11946. }
  11947. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  11948. read_timeout_sec_ = sec;
  11949. read_timeout_usec_ = usec;
  11950. }
  11951. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  11952. write_timeout_sec_ = sec;
  11953. write_timeout_usec_ = usec;
  11954. }
  11955. inline void ClientImpl::set_max_timeout(time_t msec) {
  11956. max_timeout_msec_ = msec;
  11957. }
  11958. inline void ClientImpl::set_basic_auth(const std::string &username,
  11959. const std::string &password) {
  11960. basic_auth_username_ = username;
  11961. basic_auth_password_ = password;
  11962. }
  11963. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  11964. bearer_token_auth_token_ = token;
  11965. }
  11966. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  11967. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  11968. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  11969. inline void
  11970. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  11971. addr_map_ = std::move(addr_map);
  11972. }
  11973. inline void ClientImpl::set_default_headers(Headers headers) {
  11974. default_headers_ = std::move(headers);
  11975. }
  11976. inline void ClientImpl::set_header_writer(
  11977. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11978. header_writer_ = writer;
  11979. }
  11980. inline void ClientImpl::set_address_family(int family) {
  11981. address_family_ = family;
  11982. }
  11983. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  11984. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  11985. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  11986. socket_options_ = std::move(socket_options);
  11987. }
  11988. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  11989. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  11990. inline void ClientImpl::set_payload_max_length(size_t length) {
  11991. payload_max_length_ = length;
  11992. has_payload_max_length_ = true;
  11993. }
  11994. inline void ClientImpl::set_interface(const std::string &intf) {
  11995. interface_ = intf;
  11996. }
  11997. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  11998. proxy_host_ = host;
  11999. proxy_port_ = port;
  12000. }
  12001. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12002. const std::string &password) {
  12003. proxy_basic_auth_username_ = username;
  12004. proxy_basic_auth_password_ = password;
  12005. }
  12006. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12007. proxy_bearer_token_auth_token_ = token;
  12008. }
  12009. #ifdef CPPHTTPLIB_SSL_ENABLED
  12010. inline void ClientImpl::set_digest_auth(const std::string &username,
  12011. const std::string &password) {
  12012. digest_auth_username_ = username;
  12013. digest_auth_password_ = password;
  12014. }
  12015. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12016. const std::string &ca_cert_dir_path) {
  12017. ca_cert_file_path_ = ca_cert_file_path;
  12018. ca_cert_dir_path_ = ca_cert_dir_path;
  12019. }
  12020. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12021. const std::string &password) {
  12022. proxy_digest_auth_username_ = username;
  12023. proxy_digest_auth_password_ = password;
  12024. }
  12025. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12026. server_certificate_verification_ = enabled;
  12027. }
  12028. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12029. server_hostname_verification_ = enabled;
  12030. }
  12031. #endif
  12032. // ClientImpl::set_ca_cert_store is defined after TLS namespace (uses helpers)
  12033. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12034. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  12035. std::size_t size) const {
  12036. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  12037. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  12038. if (!mem) { return nullptr; }
  12039. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  12040. if (!inf) { return nullptr; }
  12041. auto cts = X509_STORE_new();
  12042. if (cts) {
  12043. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  12044. auto itmp = sk_X509_INFO_value(inf, i);
  12045. if (!itmp) { continue; }
  12046. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  12047. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  12048. }
  12049. }
  12050. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  12051. return cts;
  12052. }
  12053. inline void ClientImpl::set_server_certificate_verifier(
  12054. std::function<SSLVerifierResponse(SSL *ssl)> /*verifier*/) {
  12055. // Base implementation does nothing - SSLClient overrides this
  12056. }
  12057. #endif
  12058. inline void ClientImpl::set_logger(Logger logger) {
  12059. logger_ = std::move(logger);
  12060. }
  12061. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12062. error_logger_ = std::move(error_logger);
  12063. }
  12064. /*
  12065. * SSL/TLS Common Implementation
  12066. */
  12067. inline ClientConnection::~ClientConnection() {
  12068. #ifdef CPPHTTPLIB_SSL_ENABLED
  12069. if (session) {
  12070. tls::shutdown(session, true);
  12071. tls::free_session(session);
  12072. session = nullptr;
  12073. }
  12074. #endif
  12075. if (sock != INVALID_SOCKET) {
  12076. detail::close_socket(sock);
  12077. sock = INVALID_SOCKET;
  12078. }
  12079. }
  12080. // Universal client implementation
  12081. inline Client::Client(const std::string &scheme_host_port)
  12082. : Client(scheme_host_port, std::string(), std::string()) {}
  12083. inline Client::Client(const std::string &scheme_host_port,
  12084. const std::string &client_cert_path,
  12085. const std::string &client_key_path) {
  12086. const static std::regex re(
  12087. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  12088. std::smatch m;
  12089. if (std::regex_match(scheme_host_port, m, re)) {
  12090. auto scheme = m[1].str();
  12091. #ifdef CPPHTTPLIB_SSL_ENABLED
  12092. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12093. #else
  12094. if (!scheme.empty() && scheme != "http") {
  12095. #endif
  12096. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12097. std::string msg = "'" + scheme + "' scheme is not supported.";
  12098. throw std::invalid_argument(msg);
  12099. #endif
  12100. return;
  12101. }
  12102. auto is_ssl = scheme == "https";
  12103. auto host = m[2].str();
  12104. if (host.empty()) { host = m[3].str(); }
  12105. auto port_str = m[4].str();
  12106. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  12107. if (is_ssl) {
  12108. #ifdef CPPHTTPLIB_SSL_ENABLED
  12109. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12110. client_key_path);
  12111. is_ssl_ = is_ssl;
  12112. #endif
  12113. } else {
  12114. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12115. client_key_path);
  12116. }
  12117. } else {
  12118. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12119. // if port param below changes.
  12120. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12121. client_cert_path, client_key_path);
  12122. }
  12123. } // namespace detail
  12124. inline Client::Client(const std::string &host, int port)
  12125. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  12126. inline Client::Client(const std::string &host, int port,
  12127. const std::string &client_cert_path,
  12128. const std::string &client_key_path)
  12129. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12130. client_key_path)) {}
  12131. inline Client::~Client() = default;
  12132. inline bool Client::is_valid() const {
  12133. return cli_ != nullptr && cli_->is_valid();
  12134. }
  12135. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12136. return cli_->Get(path, std::move(progress));
  12137. }
  12138. inline Result Client::Get(const std::string &path, const Headers &headers,
  12139. DownloadProgress progress) {
  12140. return cli_->Get(path, headers, std::move(progress));
  12141. }
  12142. inline Result Client::Get(const std::string &path,
  12143. ContentReceiver content_receiver,
  12144. DownloadProgress progress) {
  12145. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  12146. }
  12147. inline Result Client::Get(const std::string &path, const Headers &headers,
  12148. ContentReceiver content_receiver,
  12149. DownloadProgress progress) {
  12150. return cli_->Get(path, headers, std::move(content_receiver),
  12151. std::move(progress));
  12152. }
  12153. inline Result Client::Get(const std::string &path,
  12154. ResponseHandler response_handler,
  12155. ContentReceiver content_receiver,
  12156. DownloadProgress progress) {
  12157. return cli_->Get(path, std::move(response_handler),
  12158. std::move(content_receiver), std::move(progress));
  12159. }
  12160. inline Result Client::Get(const std::string &path, const Headers &headers,
  12161. ResponseHandler response_handler,
  12162. ContentReceiver content_receiver,
  12163. DownloadProgress progress) {
  12164. return cli_->Get(path, headers, std::move(response_handler),
  12165. std::move(content_receiver), std::move(progress));
  12166. }
  12167. inline Result Client::Get(const std::string &path, const Params &params,
  12168. const Headers &headers, DownloadProgress progress) {
  12169. return cli_->Get(path, params, headers, std::move(progress));
  12170. }
  12171. inline Result Client::Get(const std::string &path, const Params &params,
  12172. const Headers &headers,
  12173. ContentReceiver content_receiver,
  12174. DownloadProgress progress) {
  12175. return cli_->Get(path, params, headers, std::move(content_receiver),
  12176. std::move(progress));
  12177. }
  12178. inline Result Client::Get(const std::string &path, const Params &params,
  12179. const Headers &headers,
  12180. ResponseHandler response_handler,
  12181. ContentReceiver content_receiver,
  12182. DownloadProgress progress) {
  12183. return cli_->Get(path, params, headers, std::move(response_handler),
  12184. std::move(content_receiver), std::move(progress));
  12185. }
  12186. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  12187. inline Result Client::Head(const std::string &path, const Headers &headers) {
  12188. return cli_->Head(path, headers);
  12189. }
  12190. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  12191. inline Result Client::Post(const std::string &path, const Headers &headers) {
  12192. return cli_->Post(path, headers);
  12193. }
  12194. inline Result Client::Post(const std::string &path, const char *body,
  12195. size_t content_length,
  12196. const std::string &content_type,
  12197. UploadProgress progress) {
  12198. return cli_->Post(path, body, content_length, content_type, progress);
  12199. }
  12200. inline Result Client::Post(const std::string &path, const Headers &headers,
  12201. const char *body, size_t content_length,
  12202. const std::string &content_type,
  12203. UploadProgress progress) {
  12204. return cli_->Post(path, headers, body, content_length, content_type,
  12205. progress);
  12206. }
  12207. inline Result Client::Post(const std::string &path, const std::string &body,
  12208. const std::string &content_type,
  12209. UploadProgress progress) {
  12210. return cli_->Post(path, body, content_type, progress);
  12211. }
  12212. inline Result Client::Post(const std::string &path, const Headers &headers,
  12213. const std::string &body,
  12214. const std::string &content_type,
  12215. UploadProgress progress) {
  12216. return cli_->Post(path, headers, body, content_type, progress);
  12217. }
  12218. inline Result Client::Post(const std::string &path, size_t content_length,
  12219. ContentProvider content_provider,
  12220. const std::string &content_type,
  12221. UploadProgress progress) {
  12222. return cli_->Post(path, content_length, std::move(content_provider),
  12223. content_type, progress);
  12224. }
  12225. inline Result Client::Post(const std::string &path, size_t content_length,
  12226. ContentProvider content_provider,
  12227. const std::string &content_type,
  12228. ContentReceiver content_receiver,
  12229. UploadProgress progress) {
  12230. return cli_->Post(path, content_length, std::move(content_provider),
  12231. content_type, std::move(content_receiver), progress);
  12232. }
  12233. inline Result Client::Post(const std::string &path,
  12234. ContentProviderWithoutLength content_provider,
  12235. const std::string &content_type,
  12236. UploadProgress progress) {
  12237. return cli_->Post(path, std::move(content_provider), content_type, progress);
  12238. }
  12239. inline Result Client::Post(const std::string &path,
  12240. ContentProviderWithoutLength content_provider,
  12241. const std::string &content_type,
  12242. ContentReceiver content_receiver,
  12243. UploadProgress progress) {
  12244. return cli_->Post(path, std::move(content_provider), content_type,
  12245. std::move(content_receiver), progress);
  12246. }
  12247. inline Result Client::Post(const std::string &path, const Headers &headers,
  12248. size_t content_length,
  12249. ContentProvider content_provider,
  12250. const std::string &content_type,
  12251. UploadProgress progress) {
  12252. return cli_->Post(path, headers, content_length, std::move(content_provider),
  12253. content_type, progress);
  12254. }
  12255. inline Result Client::Post(const std::string &path, const Headers &headers,
  12256. size_t content_length,
  12257. ContentProvider content_provider,
  12258. const std::string &content_type,
  12259. ContentReceiver content_receiver,
  12260. DownloadProgress progress) {
  12261. return cli_->Post(path, headers, content_length, std::move(content_provider),
  12262. content_type, std::move(content_receiver), progress);
  12263. }
  12264. inline Result Client::Post(const std::string &path, const Headers &headers,
  12265. ContentProviderWithoutLength content_provider,
  12266. const std::string &content_type,
  12267. UploadProgress progress) {
  12268. return cli_->Post(path, headers, std::move(content_provider), content_type,
  12269. progress);
  12270. }
  12271. inline Result Client::Post(const std::string &path, const Headers &headers,
  12272. ContentProviderWithoutLength content_provider,
  12273. const std::string &content_type,
  12274. ContentReceiver content_receiver,
  12275. DownloadProgress progress) {
  12276. return cli_->Post(path, headers, std::move(content_provider), content_type,
  12277. std::move(content_receiver), progress);
  12278. }
  12279. inline Result Client::Post(const std::string &path, const Params &params) {
  12280. return cli_->Post(path, params);
  12281. }
  12282. inline Result Client::Post(const std::string &path, const Headers &headers,
  12283. const Params &params) {
  12284. return cli_->Post(path, headers, params);
  12285. }
  12286. inline Result Client::Post(const std::string &path,
  12287. const UploadFormDataItems &items,
  12288. UploadProgress progress) {
  12289. return cli_->Post(path, items, progress);
  12290. }
  12291. inline Result Client::Post(const std::string &path, const Headers &headers,
  12292. const UploadFormDataItems &items,
  12293. UploadProgress progress) {
  12294. return cli_->Post(path, headers, items, progress);
  12295. }
  12296. inline Result Client::Post(const std::string &path, const Headers &headers,
  12297. const UploadFormDataItems &items,
  12298. const std::string &boundary,
  12299. UploadProgress progress) {
  12300. return cli_->Post(path, headers, items, boundary, progress);
  12301. }
  12302. inline Result Client::Post(const std::string &path, const Headers &headers,
  12303. const UploadFormDataItems &items,
  12304. const FormDataProviderItems &provider_items,
  12305. UploadProgress progress) {
  12306. return cli_->Post(path, headers, items, provider_items, progress);
  12307. }
  12308. inline Result Client::Post(const std::string &path, const Headers &headers,
  12309. const std::string &body,
  12310. const std::string &content_type,
  12311. ContentReceiver content_receiver,
  12312. DownloadProgress progress) {
  12313. return cli_->Post(path, headers, body, content_type,
  12314. std::move(content_receiver), progress);
  12315. }
  12316. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  12317. inline Result Client::Put(const std::string &path, const Headers &headers) {
  12318. return cli_->Put(path, headers);
  12319. }
  12320. inline Result Client::Put(const std::string &path, const char *body,
  12321. size_t content_length,
  12322. const std::string &content_type,
  12323. UploadProgress progress) {
  12324. return cli_->Put(path, body, content_length, content_type, progress);
  12325. }
  12326. inline Result Client::Put(const std::string &path, const Headers &headers,
  12327. const char *body, size_t content_length,
  12328. const std::string &content_type,
  12329. UploadProgress progress) {
  12330. return cli_->Put(path, headers, body, content_length, content_type, progress);
  12331. }
  12332. inline Result Client::Put(const std::string &path, const std::string &body,
  12333. const std::string &content_type,
  12334. UploadProgress progress) {
  12335. return cli_->Put(path, body, content_type, progress);
  12336. }
  12337. inline Result Client::Put(const std::string &path, const Headers &headers,
  12338. const std::string &body,
  12339. const std::string &content_type,
  12340. UploadProgress progress) {
  12341. return cli_->Put(path, headers, body, content_type, progress);
  12342. }
  12343. inline Result Client::Put(const std::string &path, size_t content_length,
  12344. ContentProvider content_provider,
  12345. const std::string &content_type,
  12346. UploadProgress progress) {
  12347. return cli_->Put(path, content_length, std::move(content_provider),
  12348. content_type, progress);
  12349. }
  12350. inline Result Client::Put(const std::string &path, size_t content_length,
  12351. ContentProvider content_provider,
  12352. const std::string &content_type,
  12353. ContentReceiver content_receiver,
  12354. UploadProgress progress) {
  12355. return cli_->Put(path, content_length, std::move(content_provider),
  12356. content_type, std::move(content_receiver), progress);
  12357. }
  12358. inline Result Client::Put(const std::string &path,
  12359. ContentProviderWithoutLength content_provider,
  12360. const std::string &content_type,
  12361. UploadProgress progress) {
  12362. return cli_->Put(path, std::move(content_provider), content_type, progress);
  12363. }
  12364. inline Result Client::Put(const std::string &path,
  12365. ContentProviderWithoutLength content_provider,
  12366. const std::string &content_type,
  12367. ContentReceiver content_receiver,
  12368. UploadProgress progress) {
  12369. return cli_->Put(path, std::move(content_provider), content_type,
  12370. std::move(content_receiver), progress);
  12371. }
  12372. inline Result Client::Put(const std::string &path, const Headers &headers,
  12373. size_t content_length,
  12374. ContentProvider content_provider,
  12375. const std::string &content_type,
  12376. UploadProgress progress) {
  12377. return cli_->Put(path, headers, content_length, std::move(content_provider),
  12378. content_type, progress);
  12379. }
  12380. inline Result Client::Put(const std::string &path, const Headers &headers,
  12381. size_t content_length,
  12382. ContentProvider content_provider,
  12383. const std::string &content_type,
  12384. ContentReceiver content_receiver,
  12385. UploadProgress progress) {
  12386. return cli_->Put(path, headers, content_length, std::move(content_provider),
  12387. content_type, std::move(content_receiver), progress);
  12388. }
  12389. inline Result Client::Put(const std::string &path, const Headers &headers,
  12390. ContentProviderWithoutLength content_provider,
  12391. const std::string &content_type,
  12392. UploadProgress progress) {
  12393. return cli_->Put(path, headers, std::move(content_provider), content_type,
  12394. progress);
  12395. }
  12396. inline Result Client::Put(const std::string &path, const Headers &headers,
  12397. ContentProviderWithoutLength content_provider,
  12398. const std::string &content_type,
  12399. ContentReceiver content_receiver,
  12400. UploadProgress progress) {
  12401. return cli_->Put(path, headers, std::move(content_provider), content_type,
  12402. std::move(content_receiver), progress);
  12403. }
  12404. inline Result Client::Put(const std::string &path, const Params &params) {
  12405. return cli_->Put(path, params);
  12406. }
  12407. inline Result Client::Put(const std::string &path, const Headers &headers,
  12408. const Params &params) {
  12409. return cli_->Put(path, headers, params);
  12410. }
  12411. inline Result Client::Put(const std::string &path,
  12412. const UploadFormDataItems &items,
  12413. UploadProgress progress) {
  12414. return cli_->Put(path, items, progress);
  12415. }
  12416. inline Result Client::Put(const std::string &path, const Headers &headers,
  12417. const UploadFormDataItems &items,
  12418. UploadProgress progress) {
  12419. return cli_->Put(path, headers, items, progress);
  12420. }
  12421. inline Result Client::Put(const std::string &path, const Headers &headers,
  12422. const UploadFormDataItems &items,
  12423. const std::string &boundary,
  12424. UploadProgress progress) {
  12425. return cli_->Put(path, headers, items, boundary, progress);
  12426. }
  12427. inline Result Client::Put(const std::string &path, const Headers &headers,
  12428. const UploadFormDataItems &items,
  12429. const FormDataProviderItems &provider_items,
  12430. UploadProgress progress) {
  12431. return cli_->Put(path, headers, items, provider_items, progress);
  12432. }
  12433. inline Result Client::Put(const std::string &path, const Headers &headers,
  12434. const std::string &body,
  12435. const std::string &content_type,
  12436. ContentReceiver content_receiver,
  12437. DownloadProgress progress) {
  12438. return cli_->Put(path, headers, body, content_type, content_receiver,
  12439. progress);
  12440. }
  12441. inline Result Client::Patch(const std::string &path) {
  12442. return cli_->Patch(path);
  12443. }
  12444. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  12445. return cli_->Patch(path, headers);
  12446. }
  12447. inline Result Client::Patch(const std::string &path, const char *body,
  12448. size_t content_length,
  12449. const std::string &content_type,
  12450. UploadProgress progress) {
  12451. return cli_->Patch(path, body, content_length, content_type, progress);
  12452. }
  12453. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12454. const char *body, size_t content_length,
  12455. const std::string &content_type,
  12456. UploadProgress progress) {
  12457. return cli_->Patch(path, headers, body, content_length, content_type,
  12458. progress);
  12459. }
  12460. inline Result Client::Patch(const std::string &path, const std::string &body,
  12461. const std::string &content_type,
  12462. UploadProgress progress) {
  12463. return cli_->Patch(path, body, content_type, progress);
  12464. }
  12465. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12466. const std::string &body,
  12467. const std::string &content_type,
  12468. UploadProgress progress) {
  12469. return cli_->Patch(path, headers, body, content_type, progress);
  12470. }
  12471. inline Result Client::Patch(const std::string &path, size_t content_length,
  12472. ContentProvider content_provider,
  12473. const std::string &content_type,
  12474. UploadProgress progress) {
  12475. return cli_->Patch(path, content_length, std::move(content_provider),
  12476. content_type, progress);
  12477. }
  12478. inline Result Client::Patch(const std::string &path, size_t content_length,
  12479. ContentProvider content_provider,
  12480. const std::string &content_type,
  12481. ContentReceiver content_receiver,
  12482. UploadProgress progress) {
  12483. return cli_->Patch(path, content_length, std::move(content_provider),
  12484. content_type, std::move(content_receiver), progress);
  12485. }
  12486. inline Result Client::Patch(const std::string &path,
  12487. ContentProviderWithoutLength content_provider,
  12488. const std::string &content_type,
  12489. UploadProgress progress) {
  12490. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  12491. }
  12492. inline Result Client::Patch(const std::string &path,
  12493. ContentProviderWithoutLength content_provider,
  12494. const std::string &content_type,
  12495. ContentReceiver content_receiver,
  12496. UploadProgress progress) {
  12497. return cli_->Patch(path, std::move(content_provider), content_type,
  12498. std::move(content_receiver), progress);
  12499. }
  12500. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12501. size_t content_length,
  12502. ContentProvider content_provider,
  12503. const std::string &content_type,
  12504. UploadProgress progress) {
  12505. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  12506. content_type, progress);
  12507. }
  12508. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12509. size_t content_length,
  12510. ContentProvider content_provider,
  12511. const std::string &content_type,
  12512. ContentReceiver content_receiver,
  12513. UploadProgress progress) {
  12514. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  12515. content_type, std::move(content_receiver), progress);
  12516. }
  12517. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12518. ContentProviderWithoutLength content_provider,
  12519. const std::string &content_type,
  12520. UploadProgress progress) {
  12521. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  12522. progress);
  12523. }
  12524. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12525. ContentProviderWithoutLength content_provider,
  12526. const std::string &content_type,
  12527. ContentReceiver content_receiver,
  12528. UploadProgress progress) {
  12529. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  12530. std::move(content_receiver), progress);
  12531. }
  12532. inline Result Client::Patch(const std::string &path, const Params &params) {
  12533. return cli_->Patch(path, params);
  12534. }
  12535. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12536. const Params &params) {
  12537. return cli_->Patch(path, headers, params);
  12538. }
  12539. inline Result Client::Patch(const std::string &path,
  12540. const UploadFormDataItems &items,
  12541. UploadProgress progress) {
  12542. return cli_->Patch(path, items, progress);
  12543. }
  12544. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12545. const UploadFormDataItems &items,
  12546. UploadProgress progress) {
  12547. return cli_->Patch(path, headers, items, progress);
  12548. }
  12549. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12550. const UploadFormDataItems &items,
  12551. const std::string &boundary,
  12552. UploadProgress progress) {
  12553. return cli_->Patch(path, headers, items, boundary, progress);
  12554. }
  12555. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12556. const UploadFormDataItems &items,
  12557. const FormDataProviderItems &provider_items,
  12558. UploadProgress progress) {
  12559. return cli_->Patch(path, headers, items, provider_items, progress);
  12560. }
  12561. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12562. const std::string &body,
  12563. const std::string &content_type,
  12564. ContentReceiver content_receiver,
  12565. DownloadProgress progress) {
  12566. return cli_->Patch(path, headers, body, content_type, content_receiver,
  12567. progress);
  12568. }
  12569. inline Result Client::Delete(const std::string &path,
  12570. DownloadProgress progress) {
  12571. return cli_->Delete(path, progress);
  12572. }
  12573. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12574. DownloadProgress progress) {
  12575. return cli_->Delete(path, headers, progress);
  12576. }
  12577. inline Result Client::Delete(const std::string &path, const char *body,
  12578. size_t content_length,
  12579. const std::string &content_type,
  12580. DownloadProgress progress) {
  12581. return cli_->Delete(path, body, content_length, content_type, progress);
  12582. }
  12583. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12584. const char *body, size_t content_length,
  12585. const std::string &content_type,
  12586. DownloadProgress progress) {
  12587. return cli_->Delete(path, headers, body, content_length, content_type,
  12588. progress);
  12589. }
  12590. inline Result Client::Delete(const std::string &path, const std::string &body,
  12591. const std::string &content_type,
  12592. DownloadProgress progress) {
  12593. return cli_->Delete(path, body, content_type, progress);
  12594. }
  12595. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12596. const std::string &body,
  12597. const std::string &content_type,
  12598. DownloadProgress progress) {
  12599. return cli_->Delete(path, headers, body, content_type, progress);
  12600. }
  12601. inline Result Client::Delete(const std::string &path, const Params &params,
  12602. DownloadProgress progress) {
  12603. return cli_->Delete(path, params, progress);
  12604. }
  12605. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12606. const Params &params, DownloadProgress progress) {
  12607. return cli_->Delete(path, headers, params, progress);
  12608. }
  12609. inline Result Client::Options(const std::string &path) {
  12610. return cli_->Options(path);
  12611. }
  12612. inline Result Client::Options(const std::string &path, const Headers &headers) {
  12613. return cli_->Options(path, headers);
  12614. }
  12615. inline ClientImpl::StreamHandle
  12616. Client::open_stream(const std::string &method, const std::string &path,
  12617. const Params &params, const Headers &headers,
  12618. const std::string &body, const std::string &content_type) {
  12619. return cli_->open_stream(method, path, params, headers, body, content_type);
  12620. }
  12621. inline bool Client::send(Request &req, Response &res, Error &error) {
  12622. return cli_->send(req, res, error);
  12623. }
  12624. inline Result Client::send(const Request &req) { return cli_->send(req); }
  12625. inline void Client::stop() { cli_->stop(); }
  12626. inline std::string Client::host() const { return cli_->host(); }
  12627. inline int Client::port() const { return cli_->port(); }
  12628. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  12629. inline socket_t Client::socket() const { return cli_->socket(); }
  12630. inline void
  12631. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12632. cli_->set_hostname_addr_map(std::move(addr_map));
  12633. }
  12634. inline void Client::set_default_headers(Headers headers) {
  12635. cli_->set_default_headers(std::move(headers));
  12636. }
  12637. inline void Client::set_header_writer(
  12638. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12639. cli_->set_header_writer(writer);
  12640. }
  12641. inline void Client::set_address_family(int family) {
  12642. cli_->set_address_family(family);
  12643. }
  12644. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  12645. inline void Client::set_socket_options(SocketOptions socket_options) {
  12646. cli_->set_socket_options(std::move(socket_options));
  12647. }
  12648. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  12649. cli_->set_connection_timeout(sec, usec);
  12650. }
  12651. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  12652. cli_->set_read_timeout(sec, usec);
  12653. }
  12654. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  12655. cli_->set_write_timeout(sec, usec);
  12656. }
  12657. inline void Client::set_basic_auth(const std::string &username,
  12658. const std::string &password) {
  12659. cli_->set_basic_auth(username, password);
  12660. }
  12661. inline void Client::set_bearer_token_auth(const std::string &token) {
  12662. cli_->set_bearer_token_auth(token);
  12663. }
  12664. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  12665. inline void Client::set_follow_location(bool on) {
  12666. cli_->set_follow_location(on);
  12667. }
  12668. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  12669. [[deprecated("Use set_path_encode instead")]]
  12670. inline void Client::set_url_encode(bool on) {
  12671. cli_->set_path_encode(on);
  12672. }
  12673. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  12674. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  12675. inline void Client::set_payload_max_length(size_t length) {
  12676. cli_->set_payload_max_length(length);
  12677. }
  12678. inline void Client::set_interface(const std::string &intf) {
  12679. cli_->set_interface(intf);
  12680. }
  12681. inline void Client::set_proxy(const std::string &host, int port) {
  12682. cli_->set_proxy(host, port);
  12683. }
  12684. inline void Client::set_proxy_basic_auth(const std::string &username,
  12685. const std::string &password) {
  12686. cli_->set_proxy_basic_auth(username, password);
  12687. }
  12688. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  12689. cli_->set_proxy_bearer_token_auth(token);
  12690. }
  12691. inline void Client::set_logger(Logger logger) {
  12692. cli_->set_logger(std::move(logger));
  12693. }
  12694. inline void Client::set_error_logger(ErrorLogger error_logger) {
  12695. cli_->set_error_logger(std::move(error_logger));
  12696. }
  12697. /*
  12698. * Group 6: SSL Server and Client implementation
  12699. */
  12700. #ifdef CPPHTTPLIB_SSL_ENABLED
  12701. // SSL HTTP server implementation
  12702. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  12703. const char *client_ca_cert_file_path,
  12704. const char *client_ca_cert_dir_path,
  12705. const char *private_key_password) {
  12706. using namespace tls;
  12707. ctx_ = create_server_context();
  12708. if (!ctx_) { return; }
  12709. // Load server certificate and private key
  12710. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  12711. private_key_password)) {
  12712. last_ssl_error_ = static_cast<int>(get_error());
  12713. free_context(ctx_);
  12714. ctx_ = nullptr;
  12715. return;
  12716. }
  12717. // Load client CA certificates for client authentication
  12718. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  12719. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  12720. client_ca_cert_dir_path)) {
  12721. last_ssl_error_ = static_cast<int>(get_error());
  12722. free_context(ctx_);
  12723. ctx_ = nullptr;
  12724. return;
  12725. }
  12726. // Enable client certificate verification
  12727. set_verify_client(ctx_, true);
  12728. }
  12729. }
  12730. inline SSLServer::SSLServer(const PemMemory &pem) {
  12731. using namespace tls;
  12732. ctx_ = create_server_context();
  12733. if (ctx_) {
  12734. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  12735. pem.private_key_password)) {
  12736. last_ssl_error_ = static_cast<int>(get_error());
  12737. free_context(ctx_);
  12738. ctx_ = nullptr;
  12739. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  12740. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  12741. last_ssl_error_ = static_cast<int>(get_error());
  12742. free_context(ctx_);
  12743. ctx_ = nullptr;
  12744. } else {
  12745. set_verify_client(ctx_, true);
  12746. }
  12747. }
  12748. }
  12749. }
  12750. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  12751. using namespace tls;
  12752. ctx_ = create_server_context();
  12753. if (ctx_) {
  12754. if (!setup_callback(ctx_)) {
  12755. free_context(ctx_);
  12756. ctx_ = nullptr;
  12757. }
  12758. }
  12759. }
  12760. inline SSLServer::~SSLServer() {
  12761. if (ctx_) { tls::free_context(ctx_); }
  12762. }
  12763. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  12764. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  12765. using namespace tls;
  12766. // Create TLS session with mutex protection
  12767. session_t session = nullptr;
  12768. {
  12769. std::lock_guard<std::mutex> guard(ctx_mutex_);
  12770. session = create_session(static_cast<ctx_t>(ctx_), sock);
  12771. }
  12772. if (!session) {
  12773. last_ssl_error_ = static_cast<int>(get_error());
  12774. detail::shutdown_socket(sock);
  12775. detail::close_socket(sock);
  12776. return false;
  12777. }
  12778. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  12779. bool handshake_done = false;
  12780. bool ret = false;
  12781. bool websocket_upgraded = false;
  12782. auto cleanup = detail::scope_exit([&] {
  12783. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  12784. free_session(session);
  12785. detail::shutdown_socket(sock);
  12786. detail::close_socket(sock);
  12787. });
  12788. // Perform TLS accept handshake with timeout
  12789. TlsError tls_err;
  12790. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  12791. &tls_err)) {
  12792. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12793. // Map TlsError to legacy ssl_error for backward compatibility
  12794. if (tls_err.code == ErrorCode::WantRead) {
  12795. last_ssl_error_ = SSL_ERROR_WANT_READ;
  12796. } else if (tls_err.code == ErrorCode::WantWrite) {
  12797. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  12798. } else {
  12799. last_ssl_error_ = SSL_ERROR_SSL;
  12800. }
  12801. #else
  12802. last_ssl_error_ = static_cast<int>(get_error());
  12803. #endif
  12804. return false;
  12805. }
  12806. handshake_done = true;
  12807. std::string remote_addr;
  12808. int remote_port = 0;
  12809. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  12810. std::string local_addr;
  12811. int local_port = 0;
  12812. detail::get_local_ip_and_port(sock, local_addr, local_port);
  12813. ret = detail::process_server_socket_ssl(
  12814. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  12815. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12816. write_timeout_usec_,
  12817. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  12818. return process_request(
  12819. strm, remote_addr, remote_port, local_addr, local_port,
  12820. close_connection, connection_closed,
  12821. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  12822. });
  12823. return ret;
  12824. }
  12825. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  12826. const char *key_pem,
  12827. const char *client_ca_pem,
  12828. const char *password) {
  12829. if (!ctx_) { return false; }
  12830. std::lock_guard<std::mutex> guard(ctx_mutex_);
  12831. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  12832. return false;
  12833. }
  12834. if (client_ca_pem) {
  12835. return tls::update_server_client_ca(ctx_, client_ca_pem);
  12836. }
  12837. return true;
  12838. }
  12839. // SSL HTTP client implementation
  12840. inline SSLClient::~SSLClient() {
  12841. if (ctx_) { tls::free_context(ctx_); }
  12842. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  12843. // base function rather than the derived function once we get to the
  12844. // base class destructor, and won't free the SSL (causing a leak).
  12845. shutdown_ssl_impl(socket_, true);
  12846. }
  12847. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  12848. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  12849. shutdown_ssl_impl(socket, shutdown_gracefully);
  12850. }
  12851. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  12852. bool shutdown_gracefully) {
  12853. if (socket.sock == INVALID_SOCKET) {
  12854. assert(socket.ssl == nullptr);
  12855. return;
  12856. }
  12857. if (socket.ssl) {
  12858. tls::shutdown(socket.ssl, shutdown_gracefully);
  12859. {
  12860. std::lock_guard<std::mutex> guard(ctx_mutex_);
  12861. tls::free_session(socket.ssl);
  12862. }
  12863. socket.ssl = nullptr;
  12864. }
  12865. assert(socket.ssl == nullptr);
  12866. }
  12867. inline bool SSLClient::process_socket(
  12868. const Socket &socket,
  12869. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12870. std::function<bool(Stream &strm)> callback) {
  12871. assert(socket.ssl);
  12872. return detail::process_client_socket_ssl(
  12873. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  12874. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  12875. std::move(callback));
  12876. }
  12877. inline bool SSLClient::is_ssl() const { return true; }
  12878. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  12879. if (!is_valid()) {
  12880. error = Error::SSLConnection;
  12881. return false;
  12882. }
  12883. return ClientImpl::create_and_connect_socket(socket, error);
  12884. }
  12885. // Assumes that socket_mutex_ is locked and that there are no requests in
  12886. // flight
  12887. inline bool SSLClient::connect_with_proxy(
  12888. Socket &socket,
  12889. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12890. Response &res, bool &success, Error &error) {
  12891. success = true;
  12892. Response proxy_res;
  12893. if (!detail::process_client_socket(
  12894. socket.sock, read_timeout_sec_, read_timeout_usec_,
  12895. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  12896. start_time, [&](Stream &strm) {
  12897. Request req2;
  12898. req2.method = "CONNECT";
  12899. req2.path =
  12900. detail::make_host_and_port_string_always_port(host_, port_);
  12901. if (max_timeout_msec_ > 0) {
  12902. req2.start_time_ = std::chrono::steady_clock::now();
  12903. }
  12904. return process_request(strm, req2, proxy_res, false, error);
  12905. })) {
  12906. // Thread-safe to close everything because we are assuming there are no
  12907. // requests in flight
  12908. shutdown_ssl(socket, true);
  12909. shutdown_socket(socket);
  12910. close_socket(socket);
  12911. success = false;
  12912. return false;
  12913. }
  12914. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  12915. if (!proxy_digest_auth_username_.empty() &&
  12916. !proxy_digest_auth_password_.empty()) {
  12917. std::map<std::string, std::string> auth;
  12918. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  12919. // Close the current socket and create a new one for the authenticated
  12920. // request
  12921. shutdown_ssl(socket, true);
  12922. shutdown_socket(socket);
  12923. close_socket(socket);
  12924. // Create a new socket for the authenticated CONNECT request
  12925. if (!ensure_socket_connection(socket, error)) {
  12926. success = false;
  12927. output_error_log(error, nullptr);
  12928. return false;
  12929. }
  12930. proxy_res = Response();
  12931. if (!detail::process_client_socket(
  12932. socket.sock, read_timeout_sec_, read_timeout_usec_,
  12933. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  12934. start_time, [&](Stream &strm) {
  12935. Request req3;
  12936. req3.method = "CONNECT";
  12937. req3.path = detail::make_host_and_port_string_always_port(
  12938. host_, port_);
  12939. req3.headers.insert(detail::make_digest_authentication_header(
  12940. req3, auth, 1, detail::random_string(10),
  12941. proxy_digest_auth_username_, proxy_digest_auth_password_,
  12942. true));
  12943. if (max_timeout_msec_ > 0) {
  12944. req3.start_time_ = std::chrono::steady_clock::now();
  12945. }
  12946. return process_request(strm, req3, proxy_res, false, error);
  12947. })) {
  12948. // Thread-safe to close everything because we are assuming there are
  12949. // no requests in flight
  12950. shutdown_ssl(socket, true);
  12951. shutdown_socket(socket);
  12952. close_socket(socket);
  12953. success = false;
  12954. return false;
  12955. }
  12956. }
  12957. }
  12958. }
  12959. // If status code is not 200, proxy request is failed.
  12960. // Set error to ProxyConnection and return proxy response
  12961. // as the response of the request
  12962. if (proxy_res.status != StatusCode::OK_200) {
  12963. error = Error::ProxyConnection;
  12964. output_error_log(error, nullptr);
  12965. res = std::move(proxy_res);
  12966. // Thread-safe to close everything because we are assuming there are
  12967. // no requests in flight
  12968. shutdown_ssl(socket, true);
  12969. shutdown_socket(socket);
  12970. close_socket(socket);
  12971. return false;
  12972. }
  12973. return true;
  12974. }
  12975. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  12976. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  12977. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  12978. if (!initialize_ssl(socket, error)) {
  12979. shutdown_socket(socket);
  12980. close_socket(socket);
  12981. return false;
  12982. }
  12983. return true;
  12984. }
  12985. // SSL HTTP client implementation
  12986. inline SSLClient::SSLClient(const std::string &host)
  12987. : SSLClient(host, 443, std::string(), std::string()) {}
  12988. inline SSLClient::SSLClient(const std::string &host, int port)
  12989. : SSLClient(host, port, std::string(), std::string()) {}
  12990. inline SSLClient::SSLClient(const std::string &host, int port,
  12991. const std::string &client_cert_path,
  12992. const std::string &client_key_path,
  12993. const std::string &private_key_password)
  12994. : ClientImpl(host, port, client_cert_path, client_key_path) {
  12995. ctx_ = tls::create_client_context();
  12996. if (!ctx_) { return; }
  12997. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  12998. if (!client_cert_path.empty() && !client_key_path.empty()) {
  12999. const char *password =
  13000. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13001. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13002. client_key_path.c_str(), password)) {
  13003. last_backend_error_ = tls::get_error();
  13004. tls::free_context(ctx_);
  13005. ctx_ = nullptr;
  13006. }
  13007. }
  13008. }
  13009. inline SSLClient::SSLClient(const std::string &host, int port,
  13010. const PemMemory &pem)
  13011. : ClientImpl(host, port) {
  13012. ctx_ = tls::create_client_context();
  13013. if (!ctx_) { return; }
  13014. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  13015. if (pem.cert_pem && pem.key_pem) {
  13016. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13017. pem.private_key_password)) {
  13018. last_backend_error_ = tls::get_error();
  13019. tls::free_context(ctx_);
  13020. ctx_ = nullptr;
  13021. }
  13022. }
  13023. }
  13024. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13025. if (ca_cert_store && ctx_) {
  13026. // set_ca_store takes ownership of ca_cert_store
  13027. tls::set_ca_store(ctx_, ca_cert_store);
  13028. } else if (ca_cert_store) {
  13029. tls::free_ca_store(ca_cert_store);
  13030. }
  13031. }
  13032. inline void
  13033. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13034. if (!ctx_) { return; }
  13035. tls::set_verify_callback(ctx_, verifier);
  13036. }
  13037. inline void SSLClient::set_session_verifier(
  13038. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13039. session_verifier_ = std::move(verifier);
  13040. }
  13041. #if defined(_WIN32) && \
  13042. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13043. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13044. enable_windows_cert_verification_ = enabled;
  13045. }
  13046. #endif
  13047. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13048. std::size_t size) {
  13049. if (ctx_ && ca_cert && size > 0) {
  13050. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13051. tls::load_ca_pem(ctx_, ca_cert, size);
  13052. }
  13053. }
  13054. inline bool SSLClient::load_certs() {
  13055. auto ret = true;
  13056. std::call_once(initialize_cert_, [&]() {
  13057. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13058. if (!ca_cert_file_path_.empty()) {
  13059. if (!tls::load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  13060. last_backend_error_ = tls::get_error();
  13061. ret = false;
  13062. }
  13063. } else if (!ca_cert_dir_path_.empty()) {
  13064. if (!tls::load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  13065. last_backend_error_ = tls::get_error();
  13066. ret = false;
  13067. }
  13068. } else if (ca_cert_pem_.empty()) {
  13069. if (!tls::load_system_certs(ctx_)) {
  13070. last_backend_error_ = tls::get_error();
  13071. }
  13072. }
  13073. });
  13074. return ret;
  13075. }
  13076. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13077. using namespace tls;
  13078. // Load CA certificates if server verification is enabled
  13079. if (server_certificate_verification_) {
  13080. if (!load_certs()) {
  13081. error = Error::SSLLoadingCerts;
  13082. output_error_log(error, nullptr);
  13083. return false;
  13084. }
  13085. }
  13086. bool is_ip = detail::is_ip_address(host_);
  13087. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13088. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13089. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13090. // For IP addresses with verification enabled, use OPTIONAL mode since
  13091. // these backends require hostname for strict verification.
  13092. if (is_ip && server_certificate_verification_) {
  13093. set_verify_client(ctx_, false);
  13094. } else {
  13095. set_verify_client(ctx_, server_certificate_verification_);
  13096. }
  13097. #endif
  13098. // Create TLS session
  13099. session_t session = nullptr;
  13100. {
  13101. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13102. session = create_session(ctx_, socket.sock);
  13103. }
  13104. if (!session) {
  13105. error = Error::SSLConnection;
  13106. last_backend_error_ = get_error();
  13107. return false;
  13108. }
  13109. // Use scope_exit to ensure session is freed on error paths
  13110. bool success = false;
  13111. auto session_guard = detail::scope_exit([&] {
  13112. if (!success) { free_session(session); }
  13113. });
  13114. // Set SNI extension (skip for IP addresses per RFC 6066).
  13115. // On MbedTLS, set_sni also enables hostname verification internally.
  13116. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13117. if (!is_ip) {
  13118. if (!set_sni(session, host_.c_str())) {
  13119. error = Error::SSLConnection;
  13120. last_backend_error_ = get_error();
  13121. return false;
  13122. }
  13123. }
  13124. // Perform non-blocking TLS handshake with timeout
  13125. TlsError tls_err;
  13126. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13127. connection_timeout_usec_, &tls_err)) {
  13128. last_ssl_error_ = static_cast<int>(tls_err.code);
  13129. last_backend_error_ = tls_err.backend_code;
  13130. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13131. error = Error::SSLServerVerification;
  13132. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13133. error = Error::SSLServerHostnameVerification;
  13134. } else {
  13135. error = Error::SSLConnection;
  13136. }
  13137. output_error_log(error, nullptr);
  13138. return false;
  13139. }
  13140. // Post-handshake session verifier callback
  13141. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13142. if (session_verifier_) { verification_status = session_verifier_(session); }
  13143. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13144. last_backend_error_ = get_error();
  13145. error = Error::SSLServerVerification;
  13146. output_error_log(error, nullptr);
  13147. return false;
  13148. }
  13149. // Default server certificate verification
  13150. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  13151. server_certificate_verification_) {
  13152. verify_result_ = tls::get_verify_result(session);
  13153. if (verify_result_ != 0) {
  13154. last_backend_error_ = static_cast<unsigned long>(verify_result_);
  13155. error = Error::SSLServerVerification;
  13156. output_error_log(error, nullptr);
  13157. return false;
  13158. }
  13159. auto server_cert = get_peer_cert(session);
  13160. if (!server_cert) {
  13161. last_backend_error_ = get_error();
  13162. error = Error::SSLServerVerification;
  13163. output_error_log(error, nullptr);
  13164. return false;
  13165. }
  13166. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  13167. // Hostname verification (post-handshake for all cases).
  13168. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  13169. // On MbedTLS, set_sni already enabled hostname verification during
  13170. // handshake for non-IP hosts, but this check is still needed for IP
  13171. // addresses where SNI is not set.
  13172. if (server_hostname_verification_) {
  13173. if (!verify_hostname(server_cert, host_.c_str())) {
  13174. last_backend_error_ = hostname_mismatch_code();
  13175. error = Error::SSLServerHostnameVerification;
  13176. output_error_log(error, nullptr);
  13177. return false;
  13178. }
  13179. }
  13180. #if defined(_WIN32) && \
  13181. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13182. // Additional Windows Schannel verification.
  13183. // This provides real-time certificate validation with Windows Update
  13184. // integration, working with both OpenSSL and MbedTLS backends.
  13185. // Skip when a custom CA cert is specified, as the Windows certificate
  13186. // store would not know about user-provided CA certificates.
  13187. if (enable_windows_cert_verification_ && ca_cert_file_path_.empty() &&
  13188. ca_cert_dir_path_.empty() && ca_cert_pem_.empty()) {
  13189. std::vector<unsigned char> der;
  13190. if (get_cert_der(server_cert, der)) {
  13191. unsigned long wincrypt_error = 0;
  13192. if (!detail::verify_cert_with_windows_schannel(
  13193. der, host_, server_hostname_verification_, wincrypt_error)) {
  13194. last_backend_error_ = wincrypt_error;
  13195. error = Error::SSLServerVerification;
  13196. output_error_log(error, nullptr);
  13197. return false;
  13198. }
  13199. }
  13200. }
  13201. #endif
  13202. }
  13203. success = true;
  13204. socket.ssl = session;
  13205. return true;
  13206. }
  13207. inline void Client::set_digest_auth(const std::string &username,
  13208. const std::string &password) {
  13209. cli_->set_digest_auth(username, password);
  13210. }
  13211. inline void Client::set_proxy_digest_auth(const std::string &username,
  13212. const std::string &password) {
  13213. cli_->set_proxy_digest_auth(username, password);
  13214. }
  13215. inline void Client::enable_server_certificate_verification(bool enabled) {
  13216. cli_->enable_server_certificate_verification(enabled);
  13217. }
  13218. inline void Client::enable_server_hostname_verification(bool enabled) {
  13219. cli_->enable_server_hostname_verification(enabled);
  13220. }
  13221. #if defined(_WIN32) && \
  13222. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13223. inline void Client::enable_windows_certificate_verification(bool enabled) {
  13224. if (is_ssl_) {
  13225. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  13226. enabled);
  13227. }
  13228. }
  13229. #endif
  13230. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  13231. const std::string &ca_cert_dir_path) {
  13232. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  13233. }
  13234. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13235. if (is_ssl_) {
  13236. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  13237. } else if (ca_cert_store) {
  13238. tls::free_ca_store(ca_cert_store);
  13239. }
  13240. }
  13241. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  13242. set_ca_cert_store(tls::create_ca_store(ca_cert, size));
  13243. }
  13244. inline void
  13245. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13246. if (is_ssl_) {
  13247. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  13248. std::move(verifier));
  13249. }
  13250. }
  13251. inline void Client::set_session_verifier(
  13252. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13253. if (is_ssl_) {
  13254. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  13255. }
  13256. }
  13257. inline tls::ctx_t Client::tls_context() const {
  13258. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  13259. return nullptr;
  13260. }
  13261. #endif // CPPHTTPLIB_SSL_ENABLED
  13262. /*
  13263. * Group 7: TLS abstraction layer - Common API
  13264. */
  13265. #ifdef CPPHTTPLIB_SSL_ENABLED
  13266. namespace tls {
  13267. // Helper for PeerCert construction
  13268. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  13269. return PeerCert(get_peer_cert(session));
  13270. }
  13271. namespace impl {
  13272. inline VerifyCallback &get_verify_callback() {
  13273. static thread_local VerifyCallback callback;
  13274. return callback;
  13275. }
  13276. inline VerifyCallback &get_mbedtls_verify_callback() {
  13277. static thread_local VerifyCallback callback;
  13278. return callback;
  13279. }
  13280. // Check if a string is an IPv4 address
  13281. inline bool is_ipv4_address(const std::string &str) {
  13282. int dots = 0;
  13283. for (char c : str) {
  13284. if (c == '.') {
  13285. dots++;
  13286. } else if (!isdigit(static_cast<unsigned char>(c))) {
  13287. return false;
  13288. }
  13289. }
  13290. return dots == 3;
  13291. }
  13292. // Parse IPv4 address string to bytes
  13293. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  13294. int parts[4];
  13295. if (sscanf(str.c_str(), "%d.%d.%d.%d", &parts[0], &parts[1], &parts[2],
  13296. &parts[3]) != 4) {
  13297. return false;
  13298. }
  13299. for (int i = 0; i < 4; i++) {
  13300. if (parts[i] < 0 || parts[i] > 255) return false;
  13301. out[i] = static_cast<unsigned char>(parts[i]);
  13302. }
  13303. return true;
  13304. }
  13305. #ifdef _WIN32
  13306. // Enumerate Windows system certificates and call callback with DER data
  13307. template <typename Callback>
  13308. inline bool enumerate_windows_system_certs(Callback cb) {
  13309. bool loaded = false;
  13310. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  13311. for (auto store_name : store_names) {
  13312. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  13313. if (hStore) {
  13314. PCCERT_CONTEXT pContext = nullptr;
  13315. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  13316. nullptr) {
  13317. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  13318. loaded = true;
  13319. }
  13320. }
  13321. CertCloseStore(hStore, 0);
  13322. }
  13323. }
  13324. return loaded;
  13325. }
  13326. #endif
  13327. #if defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  13328. // Enumerate macOS Keychain certificates and call callback with DER data
  13329. template <typename Callback>
  13330. inline bool enumerate_macos_keychain_certs(Callback cb) {
  13331. bool loaded = false;
  13332. CFArrayRef certs = nullptr;
  13333. OSStatus status = SecTrustCopyAnchorCertificates(&certs);
  13334. if (status == errSecSuccess && certs) {
  13335. CFIndex count = CFArrayGetCount(certs);
  13336. for (CFIndex i = 0; i < count; i++) {
  13337. SecCertificateRef cert =
  13338. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  13339. CFDataRef data = SecCertificateCopyData(cert);
  13340. if (data) {
  13341. if (cb(CFDataGetBytePtr(data),
  13342. static_cast<size_t>(CFDataGetLength(data)))) {
  13343. loaded = true;
  13344. }
  13345. CFRelease(data);
  13346. }
  13347. }
  13348. CFRelease(certs);
  13349. }
  13350. return loaded;
  13351. }
  13352. #endif
  13353. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  13354. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  13355. // Common CA certificate file paths on Linux/Unix
  13356. inline const char **system_ca_paths() {
  13357. static const char *paths[] = {
  13358. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  13359. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  13360. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  13361. "/etc/pki/tls/cacert.pem", // OpenELEC
  13362. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  13363. nullptr};
  13364. return paths;
  13365. }
  13366. // Common CA certificate directory paths on Linux/Unix
  13367. inline const char **system_ca_dirs() {
  13368. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  13369. "/etc/pki/tls/certs", // RHEL/CentOS
  13370. "/usr/share/ca-certificates", // Other
  13371. nullptr};
  13372. return dirs;
  13373. }
  13374. #endif
  13375. } // namespace impl
  13376. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  13377. const char *ca_dir) {
  13378. if (!ctx) { return false; }
  13379. bool success = true;
  13380. if (ca_file && *ca_file) {
  13381. if (!load_ca_file(ctx, ca_file)) { success = false; }
  13382. }
  13383. if (ca_dir && *ca_dir) {
  13384. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  13385. }
  13386. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13387. // Set CA list for client certificate request (CertificateRequest message)
  13388. if (ca_file && *ca_file) {
  13389. auto list = SSL_load_client_CA_file(ca_file);
  13390. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  13391. }
  13392. #endif
  13393. return success;
  13394. }
  13395. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  13396. const char *password) {
  13397. return set_client_cert_pem(ctx, cert, key, password);
  13398. }
  13399. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  13400. const char *key_path, const char *password) {
  13401. return set_client_cert_file(ctx, cert_path, key_path, password);
  13402. }
  13403. // PeerCert implementation
  13404. inline PeerCert::PeerCert() = default;
  13405. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  13406. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  13407. other.cert_ = nullptr;
  13408. }
  13409. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  13410. if (this != &other) {
  13411. if (cert_) { free_cert(cert_); }
  13412. cert_ = other.cert_;
  13413. other.cert_ = nullptr;
  13414. }
  13415. return *this;
  13416. }
  13417. inline PeerCert::~PeerCert() {
  13418. if (cert_) { free_cert(cert_); }
  13419. }
  13420. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  13421. inline std::string PeerCert::subject_cn() const {
  13422. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  13423. }
  13424. inline std::string PeerCert::issuer_name() const {
  13425. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  13426. }
  13427. inline bool PeerCert::check_hostname(const char *hostname) const {
  13428. return cert_ ? verify_hostname(cert_, hostname) : false;
  13429. }
  13430. inline std::vector<SanEntry> PeerCert::sans() const {
  13431. std::vector<SanEntry> result;
  13432. if (cert_) { get_cert_sans(cert_, result); }
  13433. return result;
  13434. }
  13435. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  13436. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  13437. }
  13438. inline std::string PeerCert::serial() const {
  13439. return cert_ ? get_cert_serial(cert_) : std::string();
  13440. }
  13441. // VerifyContext method implementations
  13442. inline std::string VerifyContext::subject_cn() const {
  13443. return cert ? get_cert_subject_cn(cert) : std::string();
  13444. }
  13445. inline std::string VerifyContext::issuer_name() const {
  13446. return cert ? get_cert_issuer_name(cert) : std::string();
  13447. }
  13448. inline bool VerifyContext::check_hostname(const char *hostname) const {
  13449. return cert ? verify_hostname(cert, hostname) : false;
  13450. }
  13451. inline std::vector<SanEntry> VerifyContext::sans() const {
  13452. std::vector<SanEntry> result;
  13453. if (cert) { get_cert_sans(cert, result); }
  13454. return result;
  13455. }
  13456. inline bool VerifyContext::validity(time_t &not_before,
  13457. time_t &not_after) const {
  13458. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  13459. }
  13460. inline std::string VerifyContext::serial() const {
  13461. return cert ? get_cert_serial(cert) : std::string();
  13462. }
  13463. // TlsError static method implementation
  13464. inline std::string TlsError::verify_error_to_string(long error_code) {
  13465. return verify_error_string(error_code);
  13466. }
  13467. } // namespace tls
  13468. // Request::peer_cert() implementation
  13469. inline tls::PeerCert Request::peer_cert() const {
  13470. return tls::get_peer_cert_from_session(ssl);
  13471. }
  13472. // Request::sni() implementation
  13473. inline std::string Request::sni() const {
  13474. if (!ssl) { return std::string(); }
  13475. const char *s = tls::get_sni(ssl);
  13476. return s ? std::string(s) : std::string();
  13477. }
  13478. #endif // CPPHTTPLIB_SSL_ENABLED
  13479. /*
  13480. * Group 8: TLS abstraction layer - OpenSSL backend
  13481. */
  13482. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13483. inline SSL_CTX *Client::ssl_context() const {
  13484. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  13485. return nullptr;
  13486. }
  13487. inline void Client::set_server_certificate_verifier(
  13488. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  13489. cli_->set_server_certificate_verifier(verifier);
  13490. }
  13491. inline long Client::get_verify_result() const {
  13492. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).get_verify_result(); }
  13493. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  13494. }
  13495. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  13496. /*
  13497. * OpenSSL Backend Implementation
  13498. */
  13499. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13500. namespace tls {
  13501. namespace impl {
  13502. // OpenSSL-specific helpers for converting native types to PEM
  13503. inline std::string x509_to_pem(X509 *cert) {
  13504. if (!cert) return {};
  13505. BIO *bio = BIO_new(BIO_s_mem());
  13506. if (!bio) return {};
  13507. if (PEM_write_bio_X509(bio, cert) != 1) {
  13508. BIO_free(bio);
  13509. return {};
  13510. }
  13511. char *data = nullptr;
  13512. long len = BIO_get_mem_data(bio, &data);
  13513. std::string pem(data, static_cast<size_t>(len));
  13514. BIO_free(bio);
  13515. return pem;
  13516. }
  13517. inline std::string evp_pkey_to_pem(EVP_PKEY *key) {
  13518. if (!key) return {};
  13519. BIO *bio = BIO_new(BIO_s_mem());
  13520. if (!bio) return {};
  13521. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr,
  13522. nullptr) != 1) {
  13523. BIO_free(bio);
  13524. return {};
  13525. }
  13526. char *data = nullptr;
  13527. long len = BIO_get_mem_data(bio, &data);
  13528. std::string pem(data, static_cast<size_t>(len));
  13529. BIO_free(bio);
  13530. return pem;
  13531. }
  13532. inline std::string x509_store_to_pem(X509_STORE *store) {
  13533. if (!store) return {};
  13534. std::string pem;
  13535. auto objs = X509_STORE_get0_objects(store);
  13536. if (!objs) return {};
  13537. auto count = sk_X509_OBJECT_num(objs);
  13538. for (decltype(count) i = 0; i < count; i++) {
  13539. auto obj = sk_X509_OBJECT_value(objs, i);
  13540. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13541. auto cert = X509_OBJECT_get0_X509(obj);
  13542. if (cert) { pem += x509_to_pem(cert); }
  13543. }
  13544. }
  13545. return pem;
  13546. }
  13547. // Helper to map OpenSSL SSL_get_error to ErrorCode
  13548. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  13549. switch (ssl_error) {
  13550. case SSL_ERROR_NONE: return ErrorCode::Success;
  13551. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  13552. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  13553. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  13554. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  13555. case SSL_ERROR_SSL:
  13556. default: return ErrorCode::Fatal;
  13557. }
  13558. }
  13559. // Helper: Create client CA list from PEM string
  13560. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  13561. // Caller takes ownership of returned list
  13562. inline STACK_OF(X509_NAME) *
  13563. create_client_ca_list_from_pem(const char *ca_pem) {
  13564. if (!ca_pem) { return nullptr; }
  13565. auto ca_list = sk_X509_NAME_new_null();
  13566. if (!ca_list) { return nullptr; }
  13567. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  13568. if (!bio) {
  13569. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  13570. return nullptr;
  13571. }
  13572. X509 *cert = nullptr;
  13573. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  13574. nullptr) {
  13575. X509_NAME *name = X509_get_subject_name(cert);
  13576. if (name) { sk_X509_NAME_push(ca_list, X509_NAME_dup(name)); }
  13577. X509_free(cert);
  13578. }
  13579. BIO_free(bio);
  13580. return ca_list;
  13581. }
  13582. // Helper: Extract CA names from X509_STORE
  13583. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  13584. // Caller takes ownership of returned list
  13585. inline STACK_OF(X509_NAME) *
  13586. extract_client_ca_list_from_store(X509_STORE *store) {
  13587. if (!store) { return nullptr; }
  13588. auto ca_list = sk_X509_NAME_new_null();
  13589. if (!ca_list) { return nullptr; }
  13590. auto objs = X509_STORE_get0_objects(store);
  13591. if (!objs) {
  13592. sk_X509_NAME_free(ca_list);
  13593. return nullptr;
  13594. }
  13595. auto count = sk_X509_OBJECT_num(objs);
  13596. for (decltype(count) i = 0; i < count; i++) {
  13597. auto obj = sk_X509_OBJECT_value(objs, i);
  13598. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13599. auto cert = X509_OBJECT_get0_X509(obj);
  13600. if (cert) {
  13601. auto subject = X509_get_subject_name(cert);
  13602. if (subject) {
  13603. auto name_dup = X509_NAME_dup(subject);
  13604. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  13605. }
  13606. }
  13607. }
  13608. }
  13609. if (sk_X509_NAME_num(ca_list) == 0) {
  13610. sk_X509_NAME_free(ca_list);
  13611. return nullptr;
  13612. }
  13613. return ca_list;
  13614. }
  13615. // OpenSSL verify callback wrapper
  13616. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  13617. auto &callback = get_verify_callback();
  13618. if (!callback) { return preverify_ok; }
  13619. // Get SSL object from X509_STORE_CTX
  13620. auto ssl = static_cast<SSL *>(
  13621. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  13622. if (!ssl) { return preverify_ok; }
  13623. // Get current certificate and depth
  13624. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  13625. int depth = X509_STORE_CTX_get_error_depth(ctx);
  13626. int error = X509_STORE_CTX_get_error(ctx);
  13627. // Build context
  13628. VerifyContext verify_ctx;
  13629. verify_ctx.session = static_cast<session_t>(ssl);
  13630. verify_ctx.cert = static_cast<cert_t>(cert);
  13631. verify_ctx.depth = depth;
  13632. verify_ctx.preverify_ok = (preverify_ok != 0);
  13633. verify_ctx.error_code = error;
  13634. verify_ctx.error_string =
  13635. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  13636. return callback(verify_ctx) ? 1 : 0;
  13637. }
  13638. } // namespace impl
  13639. inline ctx_t create_client_context() {
  13640. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  13641. if (ctx) {
  13642. // Disable auto-retry to properly handle non-blocking I/O
  13643. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  13644. // Set minimum TLS version
  13645. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  13646. }
  13647. return static_cast<ctx_t>(ctx);
  13648. }
  13649. inline void free_context(ctx_t ctx) {
  13650. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  13651. }
  13652. inline bool set_min_version(ctx_t ctx, Version version) {
  13653. if (!ctx) return false;
  13654. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  13655. static_cast<int>(version)) == 1;
  13656. }
  13657. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  13658. if (!ctx || !pem || len == 0) return false;
  13659. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13660. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13661. if (!store) return false;
  13662. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  13663. if (!bio) return false;
  13664. bool ok = true;
  13665. X509 *cert = nullptr;
  13666. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  13667. nullptr) {
  13668. if (X509_STORE_add_cert(store, cert) != 1) {
  13669. // Ignore duplicate errors
  13670. auto err = ERR_peek_last_error();
  13671. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  13672. ok = false;
  13673. }
  13674. }
  13675. X509_free(cert);
  13676. if (!ok) break;
  13677. }
  13678. BIO_free(bio);
  13679. // Clear any "no more certificates" errors
  13680. ERR_clear_error();
  13681. return ok;
  13682. }
  13683. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  13684. if (!ctx || !file_path) return false;
  13685. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  13686. nullptr) == 1;
  13687. }
  13688. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  13689. if (!ctx || !dir_path) return false;
  13690. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  13691. dir_path) == 1;
  13692. }
  13693. inline bool load_system_certs(ctx_t ctx) {
  13694. if (!ctx) return false;
  13695. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13696. #ifdef _WIN32
  13697. // Windows: Load from system certificate store (ROOT and CA)
  13698. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13699. if (!store) return false;
  13700. bool loaded_any = false;
  13701. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  13702. for (auto store_name : store_names) {
  13703. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  13704. if (!hStore) continue;
  13705. PCCERT_CONTEXT pContext = nullptr;
  13706. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  13707. nullptr) {
  13708. const unsigned char *data = pContext->pbCertEncoded;
  13709. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  13710. if (x509) {
  13711. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  13712. X509_free(x509);
  13713. }
  13714. }
  13715. CertCloseStore(hStore, 0);
  13716. }
  13717. return loaded_any;
  13718. #elif defined(__APPLE__)
  13719. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  13720. // macOS: Load from Keychain
  13721. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13722. if (!store) return false;
  13723. CFArrayRef certs = nullptr;
  13724. if (SecTrustCopyAnchorCertificates(&certs) != errSecSuccess || !certs) {
  13725. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  13726. }
  13727. bool loaded_any = false;
  13728. auto count = CFArrayGetCount(certs);
  13729. for (CFIndex i = 0; i < count; i++) {
  13730. auto cert = reinterpret_cast<SecCertificateRef>(
  13731. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  13732. CFDataRef der = SecCertificateCopyData(cert);
  13733. if (der) {
  13734. const unsigned char *data = CFDataGetBytePtr(der);
  13735. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  13736. if (x509) {
  13737. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  13738. X509_free(x509);
  13739. }
  13740. CFRelease(der);
  13741. }
  13742. }
  13743. CFRelease(certs);
  13744. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  13745. #else
  13746. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  13747. #endif
  13748. #else
  13749. // Other Unix: use default verify paths
  13750. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  13751. #endif
  13752. }
  13753. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  13754. const char *password) {
  13755. if (!ctx || !cert || !key) return false;
  13756. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13757. // Load certificate
  13758. auto cert_bio = BIO_new_mem_buf(cert, -1);
  13759. if (!cert_bio) return false;
  13760. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  13761. BIO_free(cert_bio);
  13762. if (!x509) return false;
  13763. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  13764. X509_free(x509);
  13765. if (!cert_ok) return false;
  13766. // Load private key
  13767. auto key_bio = BIO_new_mem_buf(key, -1);
  13768. if (!key_bio) return false;
  13769. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  13770. password ? const_cast<char *>(password)
  13771. : nullptr);
  13772. BIO_free(key_bio);
  13773. if (!pkey) return false;
  13774. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  13775. EVP_PKEY_free(pkey);
  13776. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  13777. }
  13778. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  13779. const char *key_path, const char *password) {
  13780. if (!ctx || !cert_path || !key_path) return false;
  13781. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13782. if (password && password[0] != '\0') {
  13783. SSL_CTX_set_default_passwd_cb_userdata(
  13784. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  13785. }
  13786. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  13787. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  13788. }
  13789. inline ctx_t create_server_context() {
  13790. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13791. if (ctx) {
  13792. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  13793. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13794. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  13795. }
  13796. return static_cast<ctx_t>(ctx);
  13797. }
  13798. inline void set_verify_client(ctx_t ctx, bool require) {
  13799. if (!ctx) return;
  13800. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  13801. require
  13802. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  13803. : SSL_VERIFY_NONE,
  13804. nullptr);
  13805. }
  13806. inline session_t create_session(ctx_t ctx, socket_t sock) {
  13807. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  13808. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13809. SSL *ssl = SSL_new(ssl_ctx);
  13810. if (!ssl) return nullptr;
  13811. // Disable auto-retry for proper non-blocking I/O handling
  13812. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  13813. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  13814. if (!bio) {
  13815. SSL_free(ssl);
  13816. return nullptr;
  13817. }
  13818. SSL_set_bio(ssl, bio, bio);
  13819. return static_cast<session_t>(ssl);
  13820. }
  13821. inline void free_session(session_t session) {
  13822. if (session) { SSL_free(static_cast<SSL *>(session)); }
  13823. }
  13824. inline bool set_sni(session_t session, const char *hostname) {
  13825. if (!session || !hostname) return false;
  13826. auto ssl = static_cast<SSL *>(session);
  13827. // Set SNI (Server Name Indication) only - does not enable verification
  13828. #if defined(OPENSSL_IS_BORINGSSL)
  13829. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  13830. #else
  13831. // Direct call instead of macro to suppress -Wold-style-cast warning
  13832. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  13833. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  13834. #endif
  13835. }
  13836. inline bool set_hostname(session_t session, const char *hostname) {
  13837. if (!session || !hostname) return false;
  13838. auto ssl = static_cast<SSL *>(session);
  13839. // Set SNI (Server Name Indication)
  13840. if (!set_sni(session, hostname)) { return false; }
  13841. // Enable hostname verification
  13842. auto param = SSL_get0_param(ssl);
  13843. if (!param) return false;
  13844. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  13845. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  13846. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  13847. return true;
  13848. }
  13849. inline TlsError connect(session_t session) {
  13850. if (!session) { return TlsError(); }
  13851. auto ssl = static_cast<SSL *>(session);
  13852. auto ret = SSL_connect(ssl);
  13853. TlsError err;
  13854. if (ret == 1) {
  13855. err.code = ErrorCode::Success;
  13856. } else {
  13857. auto ssl_err = SSL_get_error(ssl, ret);
  13858. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  13859. err.backend_code = ERR_get_error();
  13860. }
  13861. return err;
  13862. }
  13863. inline TlsError accept(session_t session) {
  13864. if (!session) { return TlsError(); }
  13865. auto ssl = static_cast<SSL *>(session);
  13866. auto ret = SSL_accept(ssl);
  13867. TlsError err;
  13868. if (ret == 1) {
  13869. err.code = ErrorCode::Success;
  13870. } else {
  13871. auto ssl_err = SSL_get_error(ssl, ret);
  13872. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  13873. err.backend_code = ERR_get_error();
  13874. }
  13875. return err;
  13876. }
  13877. inline bool connect_nonblocking(session_t session, socket_t sock,
  13878. time_t timeout_sec, time_t timeout_usec,
  13879. TlsError *err) {
  13880. if (!session) {
  13881. if (err) { err->code = ErrorCode::Fatal; }
  13882. return false;
  13883. }
  13884. auto ssl = static_cast<SSL *>(session);
  13885. auto bio = SSL_get_rbio(ssl);
  13886. // Set non-blocking mode for handshake
  13887. detail::set_nonblocking(sock, true);
  13888. if (bio) { BIO_set_nbio(bio, 1); }
  13889. auto cleanup = detail::scope_exit([&]() {
  13890. // Restore blocking mode after handshake
  13891. if (bio) { BIO_set_nbio(bio, 0); }
  13892. detail::set_nonblocking(sock, false);
  13893. });
  13894. auto res = 0;
  13895. while ((res = SSL_connect(ssl)) != 1) {
  13896. auto ssl_err = SSL_get_error(ssl, res);
  13897. switch (ssl_err) {
  13898. case SSL_ERROR_WANT_READ:
  13899. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  13900. continue;
  13901. }
  13902. break;
  13903. case SSL_ERROR_WANT_WRITE:
  13904. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  13905. continue;
  13906. }
  13907. break;
  13908. default: break;
  13909. }
  13910. if (err) {
  13911. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  13912. err->backend_code = ERR_get_error();
  13913. }
  13914. return false;
  13915. }
  13916. if (err) { err->code = ErrorCode::Success; }
  13917. return true;
  13918. }
  13919. inline bool accept_nonblocking(session_t session, socket_t sock,
  13920. time_t timeout_sec, time_t timeout_usec,
  13921. TlsError *err) {
  13922. if (!session) {
  13923. if (err) { err->code = ErrorCode::Fatal; }
  13924. return false;
  13925. }
  13926. auto ssl = static_cast<SSL *>(session);
  13927. auto bio = SSL_get_rbio(ssl);
  13928. // Set non-blocking mode for handshake
  13929. detail::set_nonblocking(sock, true);
  13930. if (bio) { BIO_set_nbio(bio, 1); }
  13931. auto cleanup = detail::scope_exit([&]() {
  13932. // Restore blocking mode after handshake
  13933. if (bio) { BIO_set_nbio(bio, 0); }
  13934. detail::set_nonblocking(sock, false);
  13935. });
  13936. auto res = 0;
  13937. while ((res = SSL_accept(ssl)) != 1) {
  13938. auto ssl_err = SSL_get_error(ssl, res);
  13939. switch (ssl_err) {
  13940. case SSL_ERROR_WANT_READ:
  13941. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  13942. continue;
  13943. }
  13944. break;
  13945. case SSL_ERROR_WANT_WRITE:
  13946. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  13947. continue;
  13948. }
  13949. break;
  13950. default: break;
  13951. }
  13952. if (err) {
  13953. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  13954. err->backend_code = ERR_get_error();
  13955. }
  13956. return false;
  13957. }
  13958. if (err) { err->code = ErrorCode::Success; }
  13959. return true;
  13960. }
  13961. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  13962. if (!session || !buf) {
  13963. err.code = ErrorCode::Fatal;
  13964. return -1;
  13965. }
  13966. auto ssl = static_cast<SSL *>(session);
  13967. constexpr auto max_len =
  13968. static_cast<size_t>((std::numeric_limits<int>::max)());
  13969. if (len > max_len) { len = max_len; }
  13970. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  13971. if (ret > 0) {
  13972. err.code = ErrorCode::Success;
  13973. return ret;
  13974. }
  13975. auto ssl_err = SSL_get_error(ssl, ret);
  13976. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  13977. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  13978. return -1;
  13979. }
  13980. inline ssize_t write(session_t session, const void *buf, size_t len,
  13981. TlsError &err) {
  13982. if (!session || !buf) {
  13983. err.code = ErrorCode::Fatal;
  13984. return -1;
  13985. }
  13986. auto ssl = static_cast<SSL *>(session);
  13987. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  13988. if (ret > 0) {
  13989. err.code = ErrorCode::Success;
  13990. return ret;
  13991. }
  13992. auto ssl_err = SSL_get_error(ssl, ret);
  13993. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  13994. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  13995. return -1;
  13996. }
  13997. inline int pending(const_session_t session) {
  13998. if (!session) return 0;
  13999. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14000. }
  14001. inline void shutdown(session_t session, bool graceful) {
  14002. if (!session) return;
  14003. auto ssl = static_cast<SSL *>(session);
  14004. if (graceful) {
  14005. // First call sends close_notify
  14006. if (SSL_shutdown(ssl) == 0) {
  14007. // Second call waits for peer's close_notify
  14008. SSL_shutdown(ssl);
  14009. }
  14010. }
  14011. }
  14012. inline bool is_peer_closed(session_t session, socket_t sock) {
  14013. if (!session) return true;
  14014. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14015. detail::set_nonblocking(sock, true);
  14016. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14017. auto ssl = static_cast<SSL *>(session);
  14018. char buf;
  14019. auto ret = SSL_peek(ssl, &buf, 1);
  14020. if (ret > 0) return false;
  14021. auto err = SSL_get_error(ssl, ret);
  14022. return err == SSL_ERROR_ZERO_RETURN;
  14023. }
  14024. inline cert_t get_peer_cert(const_session_t session) {
  14025. if (!session) return nullptr;
  14026. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14027. static_cast<SSL *>(const_cast<void *>(session))));
  14028. }
  14029. inline void free_cert(cert_t cert) {
  14030. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14031. }
  14032. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14033. if (!cert || !hostname) return false;
  14034. auto x509 = static_cast<X509 *>(cert);
  14035. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14036. if (detail::is_ip_address(hostname)) {
  14037. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14038. }
  14039. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14040. }
  14041. inline uint64_t hostname_mismatch_code() {
  14042. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14043. }
  14044. inline long get_verify_result(const_session_t session) {
  14045. if (!session) return X509_V_ERR_UNSPECIFIED;
  14046. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14047. }
  14048. inline std::string get_cert_subject_cn(cert_t cert) {
  14049. if (!cert) return "";
  14050. auto x509 = static_cast<X509 *>(cert);
  14051. auto subject_name = X509_get_subject_name(x509);
  14052. if (!subject_name) return "";
  14053. char buf[256];
  14054. auto len =
  14055. X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf, sizeof(buf));
  14056. if (len < 0) return "";
  14057. return std::string(buf, static_cast<size_t>(len));
  14058. }
  14059. inline std::string get_cert_issuer_name(cert_t cert) {
  14060. if (!cert) return "";
  14061. auto x509 = static_cast<X509 *>(cert);
  14062. auto issuer_name = X509_get_issuer_name(x509);
  14063. if (!issuer_name) return "";
  14064. char buf[256];
  14065. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14066. return std::string(buf);
  14067. }
  14068. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14069. sans.clear();
  14070. if (!cert) return false;
  14071. auto x509 = static_cast<X509 *>(cert);
  14072. auto names = static_cast<GENERAL_NAMES *>(
  14073. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14074. if (!names) return true; // No SANs is valid
  14075. auto count = sk_GENERAL_NAME_num(names);
  14076. for (decltype(count) i = 0; i < count; i++) {
  14077. auto gen = sk_GENERAL_NAME_value(names, i);
  14078. if (!gen) continue;
  14079. SanEntry entry;
  14080. switch (gen->type) {
  14081. case GEN_DNS:
  14082. entry.type = SanType::DNS;
  14083. if (gen->d.dNSName) {
  14084. entry.value = std::string(
  14085. reinterpret_cast<const char *>(
  14086. ASN1_STRING_get0_data(gen->d.dNSName)),
  14087. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14088. }
  14089. break;
  14090. case GEN_IPADD:
  14091. entry.type = SanType::IP;
  14092. if (gen->d.iPAddress) {
  14093. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14094. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14095. if (len == 4) {
  14096. // IPv4
  14097. char buf[INET_ADDRSTRLEN];
  14098. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14099. entry.value = buf;
  14100. } else if (len == 16) {
  14101. // IPv6
  14102. char buf[INET6_ADDRSTRLEN];
  14103. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14104. entry.value = buf;
  14105. }
  14106. }
  14107. break;
  14108. case GEN_EMAIL:
  14109. entry.type = SanType::EMAIL;
  14110. if (gen->d.rfc822Name) {
  14111. entry.value = std::string(
  14112. reinterpret_cast<const char *>(
  14113. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14114. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14115. }
  14116. break;
  14117. case GEN_URI:
  14118. entry.type = SanType::URI;
  14119. if (gen->d.uniformResourceIdentifier) {
  14120. entry.value = std::string(
  14121. reinterpret_cast<const char *>(
  14122. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14123. static_cast<size_t>(
  14124. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14125. }
  14126. break;
  14127. default: entry.type = SanType::OTHER; break;
  14128. }
  14129. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14130. }
  14131. GENERAL_NAMES_free(names);
  14132. return true;
  14133. }
  14134. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14135. time_t &not_after) {
  14136. if (!cert) return false;
  14137. auto x509 = static_cast<X509 *>(cert);
  14138. auto nb = X509_get0_notBefore(x509);
  14139. auto na = X509_get0_notAfter(x509);
  14140. if (!nb || !na) return false;
  14141. ASN1_TIME *epoch = ASN1_TIME_new();
  14142. if (!epoch) return false;
  14143. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  14144. if (!ASN1_TIME_set(epoch, 0)) return false;
  14145. int pday, psec;
  14146. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  14147. not_before = 86400 * (time_t)pday + psec;
  14148. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  14149. not_after = 86400 * (time_t)pday + psec;
  14150. return true;
  14151. }
  14152. inline std::string get_cert_serial(cert_t cert) {
  14153. if (!cert) return "";
  14154. auto x509 = static_cast<X509 *>(cert);
  14155. auto serial = X509_get_serialNumber(x509);
  14156. if (!serial) return "";
  14157. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  14158. if (!bn) return "";
  14159. auto hex = BN_bn2hex(bn);
  14160. BN_free(bn);
  14161. if (!hex) return "";
  14162. std::string result(hex);
  14163. OPENSSL_free(hex);
  14164. return result;
  14165. }
  14166. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14167. if (!cert) return false;
  14168. auto x509 = static_cast<X509 *>(cert);
  14169. auto len = i2d_X509(x509, nullptr);
  14170. if (len < 0) return false;
  14171. der.resize(static_cast<size_t>(len));
  14172. auto p = der.data();
  14173. i2d_X509(x509, &p);
  14174. return true;
  14175. }
  14176. inline const char *get_sni(const_session_t session) {
  14177. if (!session) return nullptr;
  14178. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14179. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14180. }
  14181. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  14182. inline uint64_t get_error() { return ERR_get_error(); }
  14183. inline std::string error_string(uint64_t code) {
  14184. char buf[256];
  14185. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  14186. return std::string(buf);
  14187. }
  14188. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14189. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  14190. if (!mem) { return nullptr; }
  14191. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  14192. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  14193. if (!inf) { return nullptr; }
  14194. auto store = X509_STORE_new();
  14195. if (store) {
  14196. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  14197. auto itmp = sk_X509_INFO_value(inf, i);
  14198. if (!itmp) { continue; }
  14199. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  14200. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  14201. }
  14202. }
  14203. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  14204. return static_cast<ca_store_t>(store);
  14205. }
  14206. inline void free_ca_store(ca_store_t store) {
  14207. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  14208. }
  14209. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  14210. if (!ctx || !store) { return false; }
  14211. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14212. auto x509_store = static_cast<X509_STORE *>(store);
  14213. // Check if same store is already set
  14214. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  14215. // SSL_CTX_set_cert_store takes ownership and frees the old store
  14216. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  14217. return true;
  14218. }
  14219. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  14220. certs.clear();
  14221. if (!ctx) { return 0; }
  14222. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14223. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14224. if (!store) { return 0; }
  14225. auto objs = X509_STORE_get0_objects(store);
  14226. if (!objs) { return 0; }
  14227. auto count = sk_X509_OBJECT_num(objs);
  14228. for (decltype(count) i = 0; i < count; i++) {
  14229. auto obj = sk_X509_OBJECT_value(objs, i);
  14230. if (!obj) { continue; }
  14231. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  14232. auto x509 = X509_OBJECT_get0_X509(obj);
  14233. if (x509) {
  14234. // Increment reference count so caller can free it
  14235. X509_up_ref(x509);
  14236. certs.push_back(static_cast<cert_t>(x509));
  14237. }
  14238. }
  14239. }
  14240. return certs.size();
  14241. }
  14242. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  14243. std::vector<std::string> names;
  14244. if (!ctx) { return names; }
  14245. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14246. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14247. if (!store) { return names; }
  14248. auto objs = X509_STORE_get0_objects(store);
  14249. if (!objs) { return names; }
  14250. auto count = sk_X509_OBJECT_num(objs);
  14251. for (decltype(count) i = 0; i < count; i++) {
  14252. auto obj = sk_X509_OBJECT_value(objs, i);
  14253. if (!obj) { continue; }
  14254. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  14255. auto x509 = X509_OBJECT_get0_X509(obj);
  14256. if (x509) {
  14257. auto subject = X509_get_subject_name(x509);
  14258. if (subject) {
  14259. char buf[512];
  14260. X509_NAME_oneline(subject, buf, sizeof(buf));
  14261. names.push_back(buf);
  14262. }
  14263. }
  14264. }
  14265. }
  14266. return names;
  14267. }
  14268. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  14269. const char *key_pem, const char *password) {
  14270. if (!ctx || !cert_pem || !key_pem) { return false; }
  14271. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14272. // Load certificate from PEM
  14273. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  14274. if (!cert_bio) { return false; }
  14275. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14276. BIO_free(cert_bio);
  14277. if (!cert) { return false; }
  14278. // Load private key from PEM
  14279. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  14280. if (!key_bio) {
  14281. X509_free(cert);
  14282. return false;
  14283. }
  14284. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14285. password ? const_cast<char *>(password)
  14286. : nullptr);
  14287. BIO_free(key_bio);
  14288. if (!key) {
  14289. X509_free(cert);
  14290. return false;
  14291. }
  14292. // Update certificate and key
  14293. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  14294. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  14295. X509_free(cert);
  14296. EVP_PKEY_free(key);
  14297. return ret;
  14298. }
  14299. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  14300. if (!ctx || !ca_pem) { return false; }
  14301. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14302. // Create new X509_STORE from PEM
  14303. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  14304. if (!store) { return false; }
  14305. // SSL_CTX_set_cert_store takes ownership
  14306. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  14307. // Set client CA list for client certificate request
  14308. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  14309. if (ca_list) {
  14310. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  14311. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  14312. }
  14313. return true;
  14314. }
  14315. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  14316. if (!ctx) { return false; }
  14317. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14318. impl::get_verify_callback() = std::move(callback);
  14319. if (impl::get_verify_callback()) {
  14320. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  14321. } else {
  14322. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  14323. }
  14324. return true;
  14325. }
  14326. inline long get_verify_error(const_session_t session) {
  14327. if (!session) { return -1; }
  14328. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14329. return SSL_get_verify_result(ssl);
  14330. }
  14331. inline std::string verify_error_string(long error_code) {
  14332. if (error_code == X509_V_OK) { return ""; }
  14333. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  14334. return str ? str : "unknown error";
  14335. }
  14336. namespace impl {
  14337. // OpenSSL-specific helpers for public API wrappers
  14338. inline ctx_t create_server_context_from_x509(X509 *cert, EVP_PKEY *key,
  14339. X509_STORE *client_ca_store,
  14340. int &out_error) {
  14341. out_error = 0;
  14342. auto cert_pem = x509_to_pem(cert);
  14343. auto key_pem = evp_pkey_to_pem(key);
  14344. if (cert_pem.empty() || key_pem.empty()) {
  14345. out_error = static_cast<int>(ERR_get_error());
  14346. return nullptr;
  14347. }
  14348. auto ctx = create_server_context();
  14349. if (!ctx) {
  14350. out_error = static_cast<int>(get_error());
  14351. return nullptr;
  14352. }
  14353. if (!set_server_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr)) {
  14354. out_error = static_cast<int>(get_error());
  14355. free_context(ctx);
  14356. return nullptr;
  14357. }
  14358. if (client_ca_store) {
  14359. // Set cert store for verification (SSL_CTX_set_cert_store takes ownership)
  14360. SSL_CTX_set_cert_store(static_cast<SSL_CTX *>(ctx), client_ca_store);
  14361. // Extract and set client CA list directly from store (more efficient than
  14362. // PEM conversion)
  14363. auto ca_list = extract_client_ca_list_from_store(client_ca_store);
  14364. if (ca_list) {
  14365. SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), ca_list);
  14366. }
  14367. set_verify_client(ctx, true);
  14368. }
  14369. return ctx;
  14370. }
  14371. inline void update_server_certs_from_x509(ctx_t ctx, X509 *cert, EVP_PKEY *key,
  14372. X509_STORE *client_ca_store) {
  14373. auto cert_pem = x509_to_pem(cert);
  14374. auto key_pem = evp_pkey_to_pem(key);
  14375. if (!cert_pem.empty() && !key_pem.empty()) {
  14376. update_server_cert(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr);
  14377. }
  14378. if (client_ca_store) {
  14379. auto ca_pem = x509_store_to_pem(client_ca_store);
  14380. if (!ca_pem.empty()) { update_server_client_ca(ctx, ca_pem.c_str()); }
  14381. X509_STORE_free(client_ca_store);
  14382. }
  14383. }
  14384. inline ctx_t create_client_context_from_x509(X509 *cert, EVP_PKEY *key,
  14385. const char *password,
  14386. unsigned long &out_error) {
  14387. out_error = 0;
  14388. auto ctx = create_client_context();
  14389. if (!ctx) {
  14390. out_error = static_cast<unsigned long>(get_error());
  14391. return nullptr;
  14392. }
  14393. if (cert && key) {
  14394. auto cert_pem = x509_to_pem(cert);
  14395. auto key_pem = evp_pkey_to_pem(key);
  14396. if (cert_pem.empty() || key_pem.empty()) {
  14397. out_error = ERR_get_error();
  14398. free_context(ctx);
  14399. return nullptr;
  14400. }
  14401. if (!set_client_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  14402. password)) {
  14403. out_error = static_cast<unsigned long>(get_error());
  14404. free_context(ctx);
  14405. return nullptr;
  14406. }
  14407. }
  14408. return ctx;
  14409. }
  14410. } // namespace impl
  14411. } // namespace tls
  14412. // ClientImpl::set_ca_cert_store - defined here to use
  14413. // tls::impl::x509_store_to_pem Deprecated: converts X509_STORE to PEM and
  14414. // stores for redirect transfer
  14415. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  14416. if (ca_cert_store) {
  14417. ca_cert_pem_ = tls::impl::x509_store_to_pem(ca_cert_store);
  14418. }
  14419. }
  14420. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  14421. X509_STORE *client_ca_cert_store) {
  14422. ctx_ = tls::impl::create_server_context_from_x509(
  14423. cert, private_key, client_ca_cert_store, last_ssl_error_);
  14424. }
  14425. inline SSLServer::SSLServer(
  14426. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  14427. // Use abstract API to create context
  14428. ctx_ = tls::create_server_context();
  14429. if (ctx_) {
  14430. // Pass to OpenSSL-specific callback (ctx_ is SSL_CTX* internally)
  14431. auto ssl_ctx = static_cast<SSL_CTX *>(ctx_);
  14432. if (!setup_ssl_ctx_callback(*ssl_ctx)) {
  14433. tls::free_context(ctx_);
  14434. ctx_ = nullptr;
  14435. }
  14436. }
  14437. }
  14438. inline SSL_CTX *SSLServer::ssl_context() const {
  14439. return static_cast<SSL_CTX *>(ctx_);
  14440. }
  14441. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  14442. X509_STORE *client_ca_cert_store) {
  14443. std::lock_guard<std::mutex> guard(ctx_mutex_);
  14444. tls::impl::update_server_certs_from_x509(ctx_, cert, private_key,
  14445. client_ca_cert_store);
  14446. }
  14447. inline SSLClient::SSLClient(const std::string &host, int port,
  14448. X509 *client_cert, EVP_PKEY *client_key,
  14449. const std::string &private_key_password)
  14450. : ClientImpl(host, port) {
  14451. const char *password =
  14452. private_key_password.empty() ? nullptr : private_key_password.c_str();
  14453. ctx_ = tls::impl::create_client_context_from_x509(
  14454. client_cert, client_key, password, last_backend_error_);
  14455. }
  14456. inline long SSLClient::get_verify_result() const { return verify_result_; }
  14457. inline void SSLClient::set_server_certificate_verifier(
  14458. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  14459. // Wrap SSL* callback into backend-independent session_verifier_
  14460. auto v = std::make_shared<std::function<SSLVerifierResponse(SSL *)>>(
  14461. std::move(verifier));
  14462. session_verifier_ = [v](tls::session_t session) {
  14463. return (*v)(static_cast<SSL *>(session));
  14464. };
  14465. }
  14466. inline SSL_CTX *SSLClient::ssl_context() const {
  14467. return static_cast<SSL_CTX *>(ctx_);
  14468. }
  14469. inline bool SSLClient::verify_host(X509 *server_cert) const {
  14470. /* Quote from RFC2818 section 3.1 "Server Identity"
  14471. If a subjectAltName extension of type dNSName is present, that MUST
  14472. be used as the identity. Otherwise, the (most specific) Common Name
  14473. field in the Subject field of the certificate MUST be used. Although
  14474. the use of the Common Name is existing practice, it is deprecated and
  14475. Certification Authorities are encouraged to use the dNSName instead.
  14476. Matching is performed using the matching rules specified by
  14477. [RFC2459]. If more than one identity of a given type is present in
  14478. the certificate (e.g., more than one dNSName name, a match in any one
  14479. of the set is considered acceptable.) Names may contain the wildcard
  14480. character * which is considered to match any single domain name
  14481. component or component fragment. E.g., *.a.com matches foo.a.com but
  14482. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  14483. In some cases, the URI is specified as an IP address rather than a
  14484. hostname. In this case, the iPAddress subjectAltName must be present
  14485. in the certificate and must exactly match the IP in the URI.
  14486. */
  14487. return verify_host_with_subject_alt_name(server_cert) ||
  14488. verify_host_with_common_name(server_cert);
  14489. }
  14490. inline bool
  14491. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  14492. auto ret = false;
  14493. auto type = GEN_DNS;
  14494. struct in6_addr addr6 = {};
  14495. struct in_addr addr = {};
  14496. size_t addr_len = 0;
  14497. #ifndef __MINGW32__
  14498. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  14499. type = GEN_IPADD;
  14500. addr_len = sizeof(struct in6_addr);
  14501. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  14502. type = GEN_IPADD;
  14503. addr_len = sizeof(struct in_addr);
  14504. }
  14505. #endif
  14506. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  14507. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  14508. if (alt_names) {
  14509. auto dsn_matched = false;
  14510. auto ip_matched = false;
  14511. auto count = sk_GENERAL_NAME_num(alt_names);
  14512. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  14513. auto val = sk_GENERAL_NAME_value(alt_names, i);
  14514. if (!val || val->type != type) { continue; }
  14515. auto name =
  14516. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  14517. if (name == nullptr) { continue; }
  14518. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  14519. switch (type) {
  14520. case GEN_DNS:
  14521. dsn_matched =
  14522. detail::match_hostname(std::string(name, name_len), host_);
  14523. break;
  14524. case GEN_IPADD:
  14525. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  14526. ip_matched = true;
  14527. }
  14528. break;
  14529. }
  14530. }
  14531. if (dsn_matched || ip_matched) { ret = true; }
  14532. }
  14533. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  14534. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  14535. return ret;
  14536. }
  14537. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  14538. const auto subject_name = X509_get_subject_name(server_cert);
  14539. if (subject_name != nullptr) {
  14540. char name[BUFSIZ];
  14541. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  14542. name, sizeof(name));
  14543. if (name_len != -1) {
  14544. return detail::match_hostname(
  14545. std::string(name, static_cast<size_t>(name_len)), host_);
  14546. }
  14547. }
  14548. return false;
  14549. }
  14550. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  14551. /*
  14552. * Group 9: TLS abstraction layer - Mbed TLS backend
  14553. */
  14554. /*
  14555. * Mbed TLS Backend Implementation
  14556. */
  14557. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14558. namespace tls {
  14559. namespace impl {
  14560. // Mbed TLS session wrapper
  14561. struct MbedTlsSession {
  14562. mbedtls_ssl_context ssl;
  14563. socket_t sock = INVALID_SOCKET;
  14564. std::string hostname; // For client: set via set_sni
  14565. std::string sni_hostname; // For server: received from client via SNI callback
  14566. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  14567. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  14568. MbedTlsSession(const MbedTlsSession &) = delete;
  14569. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  14570. };
  14571. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  14572. // queue)
  14573. inline int &mbedtls_last_error() {
  14574. static thread_local int err = 0;
  14575. return err;
  14576. }
  14577. // Helper to map Mbed TLS error to ErrorCode
  14578. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  14579. if (ret == 0) { return ErrorCode::Success; }
  14580. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  14581. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  14582. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  14583. return ErrorCode::PeerClosed;
  14584. }
  14585. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  14586. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  14587. out_errno = errno;
  14588. return ErrorCode::SyscallError;
  14589. }
  14590. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  14591. return ErrorCode::CertVerifyFailed;
  14592. }
  14593. return ErrorCode::Fatal;
  14594. }
  14595. // BIO-like send callback for Mbed TLS
  14596. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  14597. size_t len) {
  14598. auto sock = *static_cast<socket_t *>(ctx);
  14599. #ifdef _WIN32
  14600. auto ret =
  14601. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  14602. if (ret == SOCKET_ERROR) {
  14603. int err = WSAGetLastError();
  14604. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  14605. return MBEDTLS_ERR_NET_SEND_FAILED;
  14606. }
  14607. #else
  14608. auto ret = send(sock, buf, len, 0);
  14609. if (ret < 0) {
  14610. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  14611. return MBEDTLS_ERR_SSL_WANT_WRITE;
  14612. }
  14613. return MBEDTLS_ERR_NET_SEND_FAILED;
  14614. }
  14615. #endif
  14616. return static_cast<int>(ret);
  14617. }
  14618. // BIO-like recv callback for Mbed TLS
  14619. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  14620. auto sock = *static_cast<socket_t *>(ctx);
  14621. #ifdef _WIN32
  14622. auto ret =
  14623. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  14624. if (ret == SOCKET_ERROR) {
  14625. int err = WSAGetLastError();
  14626. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  14627. return MBEDTLS_ERR_NET_RECV_FAILED;
  14628. }
  14629. #else
  14630. auto ret = recv(sock, buf, len, 0);
  14631. if (ret < 0) {
  14632. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  14633. return MBEDTLS_ERR_SSL_WANT_READ;
  14634. }
  14635. return MBEDTLS_ERR_NET_RECV_FAILED;
  14636. }
  14637. #endif
  14638. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  14639. return static_cast<int>(ret);
  14640. }
  14641. // MbedTlsContext constructor/destructor implementations
  14642. inline MbedTlsContext::MbedTlsContext() {
  14643. mbedtls_ssl_config_init(&conf);
  14644. mbedtls_entropy_init(&entropy);
  14645. mbedtls_ctr_drbg_init(&ctr_drbg);
  14646. mbedtls_x509_crt_init(&ca_chain);
  14647. mbedtls_x509_crt_init(&own_cert);
  14648. mbedtls_pk_init(&own_key);
  14649. }
  14650. inline MbedTlsContext::~MbedTlsContext() {
  14651. mbedtls_pk_free(&own_key);
  14652. mbedtls_x509_crt_free(&own_cert);
  14653. mbedtls_x509_crt_free(&ca_chain);
  14654. mbedtls_ctr_drbg_free(&ctr_drbg);
  14655. mbedtls_entropy_free(&entropy);
  14656. mbedtls_ssl_config_free(&conf);
  14657. }
  14658. // Thread-local storage for SNI captured during handshake
  14659. // This is needed because the SNI callback doesn't have a way to pass
  14660. // session-specific data before the session is fully set up
  14661. inline std::string &mbedpending_sni() {
  14662. static thread_local std::string sni;
  14663. return sni;
  14664. }
  14665. // SNI callback for Mbed TLS server to capture client's SNI hostname
  14666. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  14667. const unsigned char *name, size_t name_len) {
  14668. (void)p_ctx;
  14669. (void)ssl;
  14670. // Store SNI name in thread-local storage
  14671. // It will be retrieved and stored in the session after handshake
  14672. if (name && name_len > 0) {
  14673. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  14674. } else {
  14675. mbedpending_sni().clear();
  14676. }
  14677. return 0; // Accept any SNI
  14678. }
  14679. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  14680. int cert_depth, uint32_t *flags);
  14681. // MbedTLS verify callback wrapper
  14682. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  14683. int cert_depth, uint32_t *flags) {
  14684. auto &callback = get_verify_callback();
  14685. if (!callback) { return 0; } // Continue with default verification
  14686. // data points to the MbedTlsSession
  14687. auto *session = static_cast<MbedTlsSession *>(data);
  14688. // Build context
  14689. VerifyContext verify_ctx;
  14690. verify_ctx.session = static_cast<session_t>(session);
  14691. verify_ctx.cert = static_cast<cert_t>(crt);
  14692. verify_ctx.depth = cert_depth;
  14693. verify_ctx.preverify_ok = (*flags == 0);
  14694. verify_ctx.error_code = static_cast<long>(*flags);
  14695. // Convert Mbed TLS flags to error string
  14696. static thread_local char error_buf[256];
  14697. if (*flags != 0) {
  14698. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  14699. verify_ctx.error_string = error_buf;
  14700. } else {
  14701. verify_ctx.error_string = nullptr;
  14702. }
  14703. bool accepted = callback(verify_ctx);
  14704. if (accepted) {
  14705. *flags = 0; // Clear all error flags
  14706. return 0;
  14707. }
  14708. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  14709. }
  14710. } // namespace impl
  14711. inline ctx_t create_client_context() {
  14712. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  14713. if (!ctx) { return nullptr; }
  14714. ctx->is_server = false;
  14715. // Seed the random number generator
  14716. const char *pers = "httplib_client";
  14717. int ret = mbedtls_ctr_drbg_seed(
  14718. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  14719. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  14720. if (ret != 0) {
  14721. impl::mbedtls_last_error() = ret;
  14722. delete ctx;
  14723. return nullptr;
  14724. }
  14725. // Set up SSL config for client
  14726. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  14727. MBEDTLS_SSL_TRANSPORT_STREAM,
  14728. MBEDTLS_SSL_PRESET_DEFAULT);
  14729. if (ret != 0) {
  14730. impl::mbedtls_last_error() = ret;
  14731. delete ctx;
  14732. return nullptr;
  14733. }
  14734. // Set random number generator
  14735. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  14736. // Default: verify peer certificate
  14737. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14738. // Set minimum TLS version to 1.2
  14739. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14740. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14741. #else
  14742. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14743. MBEDTLS_SSL_MINOR_VERSION_3);
  14744. #endif
  14745. return static_cast<ctx_t>(ctx);
  14746. }
  14747. inline ctx_t create_server_context() {
  14748. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  14749. if (!ctx) { return nullptr; }
  14750. ctx->is_server = true;
  14751. // Seed the random number generator
  14752. const char *pers = "httplib_server";
  14753. int ret = mbedtls_ctr_drbg_seed(
  14754. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  14755. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  14756. if (ret != 0) {
  14757. impl::mbedtls_last_error() = ret;
  14758. delete ctx;
  14759. return nullptr;
  14760. }
  14761. // Set up SSL config for server
  14762. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  14763. MBEDTLS_SSL_TRANSPORT_STREAM,
  14764. MBEDTLS_SSL_PRESET_DEFAULT);
  14765. if (ret != 0) {
  14766. impl::mbedtls_last_error() = ret;
  14767. delete ctx;
  14768. return nullptr;
  14769. }
  14770. // Set random number generator
  14771. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  14772. // Default: don't verify client
  14773. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  14774. // Set minimum TLS version to 1.2
  14775. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14776. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14777. #else
  14778. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14779. MBEDTLS_SSL_MINOR_VERSION_3);
  14780. #endif
  14781. // Set SNI callback to capture client's SNI hostname
  14782. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  14783. return static_cast<ctx_t>(ctx);
  14784. }
  14785. inline void free_context(ctx_t ctx) {
  14786. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  14787. }
  14788. inline bool set_min_version(ctx_t ctx, Version version) {
  14789. if (!ctx) { return false; }
  14790. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14791. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14792. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  14793. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  14794. if (version >= Version::TLS1_3) {
  14795. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  14796. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  14797. #endif
  14798. }
  14799. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  14800. #else
  14801. // Mbed TLS 2.x uses major/minor version numbers
  14802. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  14803. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  14804. if (version >= Version::TLS1_3) {
  14805. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  14806. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  14807. #else
  14808. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  14809. #endif
  14810. }
  14811. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  14812. #endif
  14813. return true;
  14814. }
  14815. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14816. if (!ctx || !pem) { return false; }
  14817. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14818. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  14819. // Add null terminator if not present
  14820. std::string pem_str(pem, len);
  14821. int ret = mbedtls_x509_crt_parse(
  14822. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  14823. pem_str.size() + 1);
  14824. if (ret != 0) {
  14825. impl::mbedtls_last_error() = ret;
  14826. return false;
  14827. }
  14828. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  14829. return true;
  14830. }
  14831. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14832. if (!ctx || !file_path) { return false; }
  14833. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14834. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  14835. if (ret != 0) {
  14836. impl::mbedtls_last_error() = ret;
  14837. return false;
  14838. }
  14839. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  14840. return true;
  14841. }
  14842. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14843. if (!ctx || !dir_path) { return false; }
  14844. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14845. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  14846. if (ret < 0) { // Returns number of certs on success, negative on error
  14847. impl::mbedtls_last_error() = ret;
  14848. return false;
  14849. }
  14850. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  14851. return true;
  14852. }
  14853. inline bool load_system_certs(ctx_t ctx) {
  14854. if (!ctx) { return false; }
  14855. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14856. bool loaded = false;
  14857. #ifdef _WIN32
  14858. loaded = impl::enumerate_windows_system_certs(
  14859. [&](const unsigned char *data, size_t len) {
  14860. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  14861. });
  14862. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  14863. loaded = impl::enumerate_macos_keychain_certs(
  14864. [&](const unsigned char *data, size_t len) {
  14865. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  14866. });
  14867. #else
  14868. for (auto path = impl::system_ca_paths(); *path; ++path) {
  14869. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  14870. loaded = true;
  14871. break;
  14872. }
  14873. }
  14874. if (!loaded) {
  14875. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  14876. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  14877. loaded = true;
  14878. break;
  14879. }
  14880. }
  14881. }
  14882. #endif
  14883. if (loaded) {
  14884. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  14885. }
  14886. return loaded;
  14887. }
  14888. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14889. const char *password) {
  14890. if (!ctx || !cert || !key) { return false; }
  14891. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14892. // Parse certificate
  14893. std::string cert_str(cert);
  14894. int ret = mbedtls_x509_crt_parse(
  14895. &mctx->own_cert,
  14896. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  14897. cert_str.size() + 1);
  14898. if (ret != 0) {
  14899. impl::mbedtls_last_error() = ret;
  14900. return false;
  14901. }
  14902. // Parse private key
  14903. std::string key_str(key);
  14904. const unsigned char *pwd =
  14905. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  14906. size_t pwd_len = password ? strlen(password) : 0;
  14907. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14908. ret = mbedtls_pk_parse_key(
  14909. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  14910. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  14911. &mctx->ctr_drbg);
  14912. #else
  14913. ret = mbedtls_pk_parse_key(
  14914. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  14915. key_str.size() + 1, pwd, pwd_len);
  14916. #endif
  14917. if (ret != 0) {
  14918. impl::mbedtls_last_error() = ret;
  14919. return false;
  14920. }
  14921. // Verify that the certificate and private key match
  14922. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14923. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  14924. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  14925. #else
  14926. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  14927. #endif
  14928. if (ret != 0) {
  14929. impl::mbedtls_last_error() = ret;
  14930. return false;
  14931. }
  14932. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  14933. if (ret != 0) {
  14934. impl::mbedtls_last_error() = ret;
  14935. return false;
  14936. }
  14937. return true;
  14938. }
  14939. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14940. const char *key_path, const char *password) {
  14941. if (!ctx || !cert_path || !key_path) { return false; }
  14942. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14943. // Parse certificate file
  14944. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  14945. if (ret != 0) {
  14946. impl::mbedtls_last_error() = ret;
  14947. return false;
  14948. }
  14949. // Parse private key file
  14950. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14951. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  14952. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  14953. #else
  14954. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  14955. #endif
  14956. if (ret != 0) {
  14957. impl::mbedtls_last_error() = ret;
  14958. return false;
  14959. }
  14960. // Verify that the certificate and private key match
  14961. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14962. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  14963. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  14964. #else
  14965. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  14966. #endif
  14967. if (ret != 0) {
  14968. impl::mbedtls_last_error() = ret;
  14969. return false;
  14970. }
  14971. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  14972. if (ret != 0) {
  14973. impl::mbedtls_last_error() = ret;
  14974. return false;
  14975. }
  14976. return true;
  14977. }
  14978. inline void set_verify_client(ctx_t ctx, bool require) {
  14979. if (!ctx) { return; }
  14980. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14981. mctx->verify_client = require;
  14982. if (require) {
  14983. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14984. } else {
  14985. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  14986. // is called (matching OpenSSL behavior). Otherwise use NONE.
  14987. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  14988. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  14989. : MBEDTLS_SSL_VERIFY_NONE);
  14990. }
  14991. }
  14992. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14993. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  14994. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14995. auto session = new (std::nothrow) impl::MbedTlsSession();
  14996. if (!session) { return nullptr; }
  14997. session->sock = sock;
  14998. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  14999. if (ret != 0) {
  15000. impl::mbedtls_last_error() = ret;
  15001. delete session;
  15002. return nullptr;
  15003. }
  15004. // Set BIO callbacks
  15005. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15006. impl::mbedtls_net_recv_cb, nullptr);
  15007. // Set per-session verify callback with session pointer if callback is
  15008. // registered
  15009. if (mctx->has_verify_callback) {
  15010. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15011. session);
  15012. }
  15013. return static_cast<session_t>(session);
  15014. }
  15015. inline void free_session(session_t session) {
  15016. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15017. }
  15018. inline bool set_sni(session_t session, const char *hostname) {
  15019. if (!session || !hostname) { return false; }
  15020. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15021. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15022. if (ret != 0) {
  15023. impl::mbedtls_last_error() = ret;
  15024. return false;
  15025. }
  15026. msession->hostname = hostname;
  15027. return true;
  15028. }
  15029. inline bool set_hostname(session_t session, const char *hostname) {
  15030. // In Mbed TLS, set_hostname also sets up hostname verification
  15031. return set_sni(session, hostname);
  15032. }
  15033. inline TlsError connect(session_t session) {
  15034. TlsError err;
  15035. if (!session) {
  15036. err.code = ErrorCode::Fatal;
  15037. return err;
  15038. }
  15039. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15040. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15041. if (ret == 0) {
  15042. err.code = ErrorCode::Success;
  15043. } else {
  15044. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15045. err.backend_code = static_cast<uint64_t>(-ret);
  15046. impl::mbedtls_last_error() = ret;
  15047. }
  15048. return err;
  15049. }
  15050. inline TlsError accept(session_t session) {
  15051. // Same as connect for Mbed TLS - handshake works for both client and server
  15052. auto result = connect(session);
  15053. // After successful handshake, capture SNI from thread-local storage
  15054. if (result.code == ErrorCode::Success && session) {
  15055. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15056. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15057. impl::mbedpending_sni().clear();
  15058. }
  15059. return result;
  15060. }
  15061. inline bool connect_nonblocking(session_t session, socket_t sock,
  15062. time_t timeout_sec, time_t timeout_usec,
  15063. TlsError *err) {
  15064. if (!session) {
  15065. if (err) { err->code = ErrorCode::Fatal; }
  15066. return false;
  15067. }
  15068. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15069. // Set socket to non-blocking mode
  15070. detail::set_nonblocking(sock, true);
  15071. auto cleanup =
  15072. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15073. int ret;
  15074. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15075. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15076. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15077. continue;
  15078. }
  15079. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15080. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15081. continue;
  15082. }
  15083. }
  15084. // TlsError or timeout
  15085. if (err) {
  15086. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15087. err->backend_code = static_cast<uint64_t>(-ret);
  15088. }
  15089. impl::mbedtls_last_error() = ret;
  15090. return false;
  15091. }
  15092. if (err) { err->code = ErrorCode::Success; }
  15093. return true;
  15094. }
  15095. inline bool accept_nonblocking(session_t session, socket_t sock,
  15096. time_t timeout_sec, time_t timeout_usec,
  15097. TlsError *err) {
  15098. // Same implementation as connect for Mbed TLS
  15099. bool result =
  15100. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15101. // After successful handshake, capture SNI from thread-local storage
  15102. if (result && session) {
  15103. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15104. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15105. impl::mbedpending_sni().clear();
  15106. }
  15107. return result;
  15108. }
  15109. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15110. if (!session || !buf) {
  15111. err.code = ErrorCode::Fatal;
  15112. return -1;
  15113. }
  15114. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15115. int ret =
  15116. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15117. if (ret > 0) {
  15118. err.code = ErrorCode::Success;
  15119. return static_cast<ssize_t>(ret);
  15120. }
  15121. if (ret == 0) {
  15122. err.code = ErrorCode::PeerClosed;
  15123. return 0;
  15124. }
  15125. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15126. err.backend_code = static_cast<uint64_t>(-ret);
  15127. impl::mbedtls_last_error() = ret;
  15128. return -1;
  15129. }
  15130. inline ssize_t write(session_t session, const void *buf, size_t len,
  15131. TlsError &err) {
  15132. if (!session || !buf) {
  15133. err.code = ErrorCode::Fatal;
  15134. return -1;
  15135. }
  15136. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15137. int ret = mbedtls_ssl_write(&msession->ssl,
  15138. static_cast<const unsigned char *>(buf), len);
  15139. if (ret > 0) {
  15140. err.code = ErrorCode::Success;
  15141. return static_cast<ssize_t>(ret);
  15142. }
  15143. if (ret == 0) {
  15144. err.code = ErrorCode::PeerClosed;
  15145. return 0;
  15146. }
  15147. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15148. err.backend_code = static_cast<uint64_t>(-ret);
  15149. impl::mbedtls_last_error() = ret;
  15150. return -1;
  15151. }
  15152. inline int pending(const_session_t session) {
  15153. if (!session) { return 0; }
  15154. auto msession =
  15155. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15156. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15157. }
  15158. inline void shutdown(session_t session, bool graceful) {
  15159. if (!session) { return; }
  15160. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15161. if (graceful) {
  15162. // Try to send close_notify, but don't block forever
  15163. int ret;
  15164. int attempts = 0;
  15165. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15166. attempts < 3) {
  15167. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15168. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15169. break;
  15170. }
  15171. attempts++;
  15172. }
  15173. }
  15174. }
  15175. inline bool is_peer_closed(session_t session, socket_t sock) {
  15176. if (!session || sock == INVALID_SOCKET) { return true; }
  15177. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15178. // Check if there's already decrypted data available in the TLS buffer
  15179. // If so, the connection is definitely alive
  15180. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15181. // Set socket to non-blocking to avoid blocking on read
  15182. detail::set_nonblocking(sock, true);
  15183. auto cleanup =
  15184. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15185. // Try a 1-byte read to check connection status
  15186. // Note: This will consume the byte if data is available, but for the
  15187. // purpose of checking if peer is closed, this should be acceptable
  15188. // since we're only called when we expect the connection might be closing
  15189. unsigned char buf;
  15190. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15191. // If we got data or WANT_READ (would block), connection is alive
  15192. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15193. // If we get a peer close notify or a connection reset, the peer is closed
  15194. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15195. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15196. }
  15197. inline cert_t get_peer_cert(const_session_t session) {
  15198. if (!session) { return nullptr; }
  15199. auto msession =
  15200. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15201. // Mbed TLS returns a pointer to the internal peer cert chain.
  15202. // WARNING: This pointer is only valid while the session is active.
  15203. // Do not use the certificate after calling free_session().
  15204. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15205. return const_cast<mbedtls_x509_crt *>(cert);
  15206. }
  15207. inline void free_cert(cert_t cert) {
  15208. // Mbed TLS: peer certificate is owned by the SSL context.
  15209. // No-op here, but callers should still call this for cross-backend
  15210. // portability.
  15211. (void)cert;
  15212. }
  15213. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15214. if (!cert || !hostname) { return false; }
  15215. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15216. std::string host_str(hostname);
  15217. // Check if hostname is an IP address
  15218. bool is_ip = impl::is_ipv4_address(host_str);
  15219. unsigned char ip_bytes[4];
  15220. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  15221. // Check Subject Alternative Names (SAN)
  15222. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15223. // - DNS names: raw string bytes
  15224. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15225. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15226. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15227. const unsigned char *p = san->buf.p;
  15228. size_t len = san->buf.len;
  15229. if (is_ip) {
  15230. // Check if this SAN is an IPv4 address (4 bytes)
  15231. if (len == 4 && memcmp(p, ip_bytes, 4) == 0) { return true; }
  15232. // Check if this SAN is an IPv6 address (16 bytes) - skip for now
  15233. } else {
  15234. // Check if this SAN is a DNS name (printable ASCII string)
  15235. bool is_dns = len > 0;
  15236. for (size_t i = 0; i < len && is_dns; i++) {
  15237. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15238. }
  15239. if (is_dns) {
  15240. std::string san_name(reinterpret_cast<const char *>(p), len);
  15241. if (detail::match_hostname(san_name, host_str)) { return true; }
  15242. }
  15243. }
  15244. san = san->next;
  15245. }
  15246. // Fallback: Check Common Name (CN) in subject
  15247. char cn[256];
  15248. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15249. if (ret > 0) {
  15250. std::string cn_str(cn);
  15251. // Look for "CN=" in the DN string
  15252. size_t cn_pos = cn_str.find("CN=");
  15253. if (cn_pos != std::string::npos) {
  15254. size_t start = cn_pos + 3;
  15255. size_t end = cn_str.find(',', start);
  15256. std::string cn_value =
  15257. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15258. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15259. }
  15260. }
  15261. return false;
  15262. }
  15263. inline uint64_t hostname_mismatch_code() {
  15264. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15265. }
  15266. inline long get_verify_result(const_session_t session) {
  15267. if (!session) { return -1; }
  15268. auto msession =
  15269. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15270. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15271. // Return 0 (X509_V_OK equivalent) if verification passed
  15272. return flags == 0 ? 0 : static_cast<long>(flags);
  15273. }
  15274. inline std::string get_cert_subject_cn(cert_t cert) {
  15275. if (!cert) return "";
  15276. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15277. // Find the CN in the subject
  15278. const mbedtls_x509_name *name = &x509->subject;
  15279. while (name != nullptr) {
  15280. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15281. return std::string(reinterpret_cast<const char *>(name->val.p),
  15282. name->val.len);
  15283. }
  15284. name = name->next;
  15285. }
  15286. return "";
  15287. }
  15288. inline std::string get_cert_issuer_name(cert_t cert) {
  15289. if (!cert) return "";
  15290. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15291. // Build a human-readable issuer name string
  15292. char buf[512];
  15293. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15294. if (ret < 0) return "";
  15295. return std::string(buf);
  15296. }
  15297. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15298. sans.clear();
  15299. if (!cert) return false;
  15300. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15301. // Parse the Subject Alternative Name extension
  15302. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15303. while (cur != nullptr) {
  15304. if (cur->buf.len > 0) {
  15305. // Mbed TLS stores SAN as ASN.1 sequences
  15306. // The tag byte indicates the type
  15307. const unsigned char *p = cur->buf.p;
  15308. size_t len = cur->buf.len;
  15309. // First byte is the tag
  15310. unsigned char tag = *p;
  15311. p++;
  15312. len--;
  15313. // Parse length (simple single-byte length assumed)
  15314. if (len > 0 && *p < 0x80) {
  15315. size_t value_len = *p;
  15316. p++;
  15317. len--;
  15318. if (value_len <= len) {
  15319. SanEntry entry;
  15320. // ASN.1 context tags for GeneralName
  15321. switch (tag & 0x1F) {
  15322. case 2: // dNSName
  15323. entry.type = SanType::DNS;
  15324. entry.value =
  15325. std::string(reinterpret_cast<const char *>(p), value_len);
  15326. break;
  15327. case 7: // iPAddress
  15328. entry.type = SanType::IP;
  15329. if (value_len == 4) {
  15330. // IPv4
  15331. char buf[16];
  15332. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15333. entry.value = buf;
  15334. } else if (value_len == 16) {
  15335. // IPv6
  15336. char buf[64];
  15337. snprintf(buf, sizeof(buf),
  15338. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  15339. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  15340. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  15341. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  15342. entry.value = buf;
  15343. }
  15344. break;
  15345. case 1: // rfc822Name (email)
  15346. entry.type = SanType::EMAIL;
  15347. entry.value =
  15348. std::string(reinterpret_cast<const char *>(p), value_len);
  15349. break;
  15350. case 6: // uniformResourceIdentifier
  15351. entry.type = SanType::URI;
  15352. entry.value =
  15353. std::string(reinterpret_cast<const char *>(p), value_len);
  15354. break;
  15355. default: entry.type = SanType::OTHER; break;
  15356. }
  15357. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15358. }
  15359. }
  15360. }
  15361. cur = cur->next;
  15362. }
  15363. return true;
  15364. }
  15365. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15366. time_t &not_after) {
  15367. if (!cert) return false;
  15368. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15369. // Convert mbedtls_x509_time to time_t
  15370. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  15371. struct tm tm_time = {};
  15372. tm_time.tm_year = t.year - 1900;
  15373. tm_time.tm_mon = t.mon - 1;
  15374. tm_time.tm_mday = t.day;
  15375. tm_time.tm_hour = t.hour;
  15376. tm_time.tm_min = t.min;
  15377. tm_time.tm_sec = t.sec;
  15378. #ifdef _WIN32
  15379. return _mkgmtime(&tm_time);
  15380. #else
  15381. return timegm(&tm_time);
  15382. #endif
  15383. };
  15384. not_before = to_time_t(x509->valid_from);
  15385. not_after = to_time_t(x509->valid_to);
  15386. return true;
  15387. }
  15388. inline std::string get_cert_serial(cert_t cert) {
  15389. if (!cert) return "";
  15390. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15391. // Convert serial number to hex string
  15392. std::string result;
  15393. result.reserve(x509->serial.len * 2);
  15394. for (size_t i = 0; i < x509->serial.len; i++) {
  15395. char hex[3];
  15396. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  15397. result += hex;
  15398. }
  15399. return result;
  15400. }
  15401. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15402. if (!cert) return false;
  15403. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  15404. if (!crt->raw.p || crt->raw.len == 0) return false;
  15405. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  15406. return true;
  15407. }
  15408. inline const char *get_sni(const_session_t session) {
  15409. if (!session) return nullptr;
  15410. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  15411. // For server: return SNI received from client during handshake
  15412. if (!msession->sni_hostname.empty()) {
  15413. return msession->sni_hostname.c_str();
  15414. }
  15415. // For client: return the hostname set via set_sni
  15416. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  15417. return nullptr;
  15418. }
  15419. inline uint64_t peek_error() {
  15420. // Mbed TLS doesn't have an error queue, return the last error
  15421. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  15422. }
  15423. inline uint64_t get_error() {
  15424. // Mbed TLS doesn't have an error queue, return and clear the last error
  15425. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  15426. impl::mbedtls_last_error() = 0;
  15427. return err;
  15428. }
  15429. inline std::string error_string(uint64_t code) {
  15430. char buf[256];
  15431. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  15432. return std::string(buf);
  15433. }
  15434. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  15435. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  15436. if (!ca_chain) { return nullptr; }
  15437. mbedtls_x509_crt_init(ca_chain);
  15438. // mbedtls_x509_crt_parse expects null-terminated PEM
  15439. int ret = mbedtls_x509_crt_parse(ca_chain,
  15440. reinterpret_cast<const unsigned char *>(pem),
  15441. len + 1); // +1 for null terminator
  15442. if (ret != 0) {
  15443. // Try without +1 in case PEM is already null-terminated
  15444. ret = mbedtls_x509_crt_parse(
  15445. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  15446. if (ret != 0) {
  15447. mbedtls_x509_crt_free(ca_chain);
  15448. delete ca_chain;
  15449. return nullptr;
  15450. }
  15451. }
  15452. return static_cast<ca_store_t>(ca_chain);
  15453. }
  15454. inline void free_ca_store(ca_store_t store) {
  15455. if (store) {
  15456. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  15457. mbedtls_x509_crt_free(ca_chain);
  15458. delete ca_chain;
  15459. }
  15460. }
  15461. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15462. if (!ctx || !store) { return false; }
  15463. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15464. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  15465. // Free existing CA chain
  15466. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  15467. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  15468. // Copy the CA chain (deep copy)
  15469. // Parse from the raw data of the source cert
  15470. mbedtls_x509_crt *src = ca_chain;
  15471. while (src != nullptr) {
  15472. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  15473. src->raw.len);
  15474. if (ret != 0) { return false; }
  15475. src = src->next;
  15476. }
  15477. // Update the SSL config to use the new CA chain
  15478. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  15479. return true;
  15480. }
  15481. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15482. certs.clear();
  15483. if (!ctx) { return 0; }
  15484. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15485. // Iterate through the CA chain
  15486. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  15487. while (cert != nullptr && cert->raw.len > 0) {
  15488. // Create a copy of the certificate for the caller
  15489. auto *copy = new mbedtls_x509_crt;
  15490. mbedtls_x509_crt_init(copy);
  15491. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  15492. if (ret == 0) {
  15493. certs.push_back(static_cast<cert_t>(copy));
  15494. } else {
  15495. mbedtls_x509_crt_free(copy);
  15496. delete copy;
  15497. }
  15498. cert = cert->next;
  15499. }
  15500. return certs.size();
  15501. }
  15502. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15503. std::vector<std::string> names;
  15504. if (!ctx) { return names; }
  15505. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15506. // Iterate through the CA chain
  15507. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  15508. while (cert != nullptr && cert->raw.len > 0) {
  15509. char buf[512];
  15510. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  15511. if (ret > 0) { names.push_back(buf); }
  15512. cert = cert->next;
  15513. }
  15514. return names;
  15515. }
  15516. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15517. const char *key_pem, const char *password) {
  15518. if (!ctx || !cert_pem || !key_pem) { return false; }
  15519. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15520. // Free existing certificate and key
  15521. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  15522. mbedtls_pk_free(&mbed_ctx->own_key);
  15523. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  15524. mbedtls_pk_init(&mbed_ctx->own_key);
  15525. // Parse certificate PEM
  15526. int ret = mbedtls_x509_crt_parse(
  15527. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  15528. strlen(cert_pem) + 1);
  15529. if (ret != 0) {
  15530. impl::mbedtls_last_error() = ret;
  15531. return false;
  15532. }
  15533. // Parse private key PEM
  15534. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15535. ret = mbedtls_pk_parse_key(
  15536. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  15537. strlen(key_pem) + 1,
  15538. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  15539. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  15540. &mbed_ctx->ctr_drbg);
  15541. #else
  15542. ret = mbedtls_pk_parse_key(
  15543. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  15544. strlen(key_pem) + 1,
  15545. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  15546. password ? strlen(password) : 0);
  15547. #endif
  15548. if (ret != 0) {
  15549. impl::mbedtls_last_error() = ret;
  15550. return false;
  15551. }
  15552. // Configure SSL to use the new certificate and key
  15553. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  15554. &mbed_ctx->own_key);
  15555. if (ret != 0) {
  15556. impl::mbedtls_last_error() = ret;
  15557. return false;
  15558. }
  15559. return true;
  15560. }
  15561. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15562. if (!ctx || !ca_pem) { return false; }
  15563. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15564. // Free existing CA chain
  15565. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  15566. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  15567. // Parse CA PEM
  15568. int ret = mbedtls_x509_crt_parse(
  15569. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  15570. strlen(ca_pem) + 1);
  15571. if (ret != 0) {
  15572. impl::mbedtls_last_error() = ret;
  15573. return false;
  15574. }
  15575. // Update SSL config to use new CA chain
  15576. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  15577. return true;
  15578. }
  15579. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15580. if (!ctx) { return false; }
  15581. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15582. impl::get_verify_callback() = std::move(callback);
  15583. mbed_ctx->has_verify_callback =
  15584. static_cast<bool>(impl::get_verify_callback());
  15585. if (mbed_ctx->has_verify_callback) {
  15586. // Set OPTIONAL mode to ensure callback is called even when verification
  15587. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  15588. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  15589. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  15590. nullptr);
  15591. } else {
  15592. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  15593. }
  15594. return true;
  15595. }
  15596. inline long get_verify_error(const_session_t session) {
  15597. if (!session) { return -1; }
  15598. auto *msession =
  15599. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15600. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  15601. }
  15602. inline std::string verify_error_string(long error_code) {
  15603. if (error_code == 0) { return ""; }
  15604. char buf[256];
  15605. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  15606. static_cast<uint32_t>(error_code));
  15607. // Remove trailing newline if present
  15608. std::string result(buf);
  15609. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  15610. result.pop_back();
  15611. }
  15612. return result;
  15613. }
  15614. } // namespace tls
  15615. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  15616. /*
  15617. * Group 10: TLS abstraction layer - wolfSSL backend
  15618. */
  15619. /*
  15620. * wolfSSL Backend Implementation
  15621. */
  15622. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  15623. namespace tls {
  15624. namespace impl {
  15625. // wolfSSL session wrapper
  15626. struct WolfSSLSession {
  15627. WOLFSSL *ssl = nullptr;
  15628. socket_t sock = INVALID_SOCKET;
  15629. std::string hostname; // For client: set via set_sni
  15630. std::string sni_hostname; // For server: received from client via SNI callback
  15631. WolfSSLSession() = default;
  15632. ~WolfSSLSession() {
  15633. if (ssl) { wolfSSL_free(ssl); }
  15634. }
  15635. WolfSSLSession(const WolfSSLSession &) = delete;
  15636. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  15637. };
  15638. // Thread-local error code accessor for wolfSSL
  15639. inline uint64_t &wolfssl_last_error() {
  15640. static thread_local uint64_t err = 0;
  15641. return err;
  15642. }
  15643. // Helper to map wolfSSL error to ErrorCode.
  15644. // ssl_error is the value from wolfSSL_get_error().
  15645. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  15646. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  15647. int &out_errno) {
  15648. switch (ssl_error) {
  15649. case SSL_ERROR_NONE: return ErrorCode::Success;
  15650. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  15651. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  15652. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  15653. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  15654. default:
  15655. if (ssl) {
  15656. // wolfSSL stores the low-level error code as a negative value.
  15657. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  15658. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  15659. if (low_err == DOMAIN_NAME_MISMATCH) {
  15660. return ErrorCode::HostnameMismatch;
  15661. }
  15662. // Check verify result to distinguish cert verification from generic SSL
  15663. // errors.
  15664. long vr = wolfSSL_get_verify_result(ssl);
  15665. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  15666. }
  15667. return ErrorCode::Fatal;
  15668. }
  15669. }
  15670. // WolfSSLContext constructor/destructor implementations
  15671. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  15672. inline WolfSSLContext::~WolfSSLContext() {
  15673. if (ctx) { wolfSSL_CTX_free(ctx); }
  15674. }
  15675. // Thread-local storage for SNI captured during handshake
  15676. inline std::string &wolfssl_pending_sni() {
  15677. static thread_local std::string sni;
  15678. return sni;
  15679. }
  15680. // SNI callback for wolfSSL server to capture client's SNI hostname
  15681. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  15682. (void)ret;
  15683. (void)exArg;
  15684. void *name_data = nullptr;
  15685. unsigned short name_len =
  15686. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  15687. if (name_data && name_len > 0) {
  15688. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  15689. name_len);
  15690. } else {
  15691. wolfssl_pending_sni().clear();
  15692. }
  15693. return 0; // Continue regardless
  15694. }
  15695. // wolfSSL verify callback wrapper
  15696. inline int wolfssl_verify_callback(int preverify_ok,
  15697. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  15698. auto &callback = get_verify_callback();
  15699. if (!callback) { return preverify_ok; }
  15700. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  15701. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  15702. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  15703. // Get the WOLFSSL object from the X509_STORE_CTX
  15704. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  15705. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  15706. VerifyContext verify_ctx;
  15707. verify_ctx.session = static_cast<session_t>(ssl);
  15708. verify_ctx.cert = static_cast<cert_t>(cert);
  15709. verify_ctx.depth = depth;
  15710. verify_ctx.preverify_ok = (preverify_ok != 0);
  15711. verify_ctx.error_code = static_cast<long>(err);
  15712. if (err != 0) {
  15713. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  15714. } else {
  15715. verify_ctx.error_string = nullptr;
  15716. }
  15717. bool accepted = callback(verify_ctx);
  15718. return accepted ? 1 : 0;
  15719. }
  15720. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  15721. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  15722. wolfSSL_CTX_set_default_passwd_cb(
  15723. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  15724. auto *pwd = static_cast<const char *>(userdata);
  15725. if (!pwd) return 0;
  15726. auto len = static_cast<int>(strlen(pwd));
  15727. if (len > size) len = size;
  15728. memcpy(buf, pwd, static_cast<size_t>(len));
  15729. return len;
  15730. });
  15731. }
  15732. } // namespace impl
  15733. inline ctx_t create_client_context() {
  15734. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  15735. if (!ctx) { return nullptr; }
  15736. ctx->is_server = false;
  15737. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  15738. if (!method) {
  15739. delete ctx;
  15740. return nullptr;
  15741. }
  15742. ctx->ctx = wolfSSL_CTX_new(method);
  15743. if (!ctx->ctx) {
  15744. delete ctx;
  15745. return nullptr;
  15746. }
  15747. // Default: verify peer certificate
  15748. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  15749. return static_cast<ctx_t>(ctx);
  15750. }
  15751. inline ctx_t create_server_context() {
  15752. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  15753. if (!ctx) { return nullptr; }
  15754. ctx->is_server = true;
  15755. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  15756. if (!method) {
  15757. delete ctx;
  15758. return nullptr;
  15759. }
  15760. ctx->ctx = wolfSSL_CTX_new(method);
  15761. if (!ctx->ctx) {
  15762. delete ctx;
  15763. return nullptr;
  15764. }
  15765. // Default: don't verify client
  15766. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  15767. // Enable SNI on server
  15768. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  15769. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  15770. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  15771. return static_cast<ctx_t>(ctx);
  15772. }
  15773. inline void free_context(ctx_t ctx) {
  15774. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  15775. }
  15776. inline bool set_min_version(ctx_t ctx, Version version) {
  15777. if (!ctx) { return false; }
  15778. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15779. int min_ver = WOLFSSL_TLSV1_2;
  15780. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  15781. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  15782. }
  15783. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15784. if (!ctx || !pem) { return false; }
  15785. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15786. int ret = wolfSSL_CTX_load_verify_buffer(
  15787. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  15788. static_cast<long>(len), SSL_FILETYPE_PEM);
  15789. if (ret != SSL_SUCCESS) {
  15790. impl::wolfssl_last_error() =
  15791. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15792. return false;
  15793. }
  15794. wctx->ca_pem_data_.append(pem, len);
  15795. return true;
  15796. }
  15797. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15798. if (!ctx || !file_path) { return false; }
  15799. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15800. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  15801. if (ret != SSL_SUCCESS) {
  15802. impl::wolfssl_last_error() =
  15803. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15804. return false;
  15805. }
  15806. return true;
  15807. }
  15808. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15809. if (!ctx || !dir_path) { return false; }
  15810. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15811. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  15812. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  15813. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  15814. // immediately. Return true even on failure since the CA file may have
  15815. // already been loaded, matching OpenSSL's lenient behavior.
  15816. (void)ret;
  15817. return true;
  15818. }
  15819. inline bool load_system_certs(ctx_t ctx) {
  15820. if (!ctx) { return false; }
  15821. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15822. bool loaded = false;
  15823. #ifdef _WIN32
  15824. loaded = impl::enumerate_windows_system_certs(
  15825. [&](const unsigned char *data, size_t len) {
  15826. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  15827. static_cast<long>(len),
  15828. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  15829. });
  15830. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15831. loaded = impl::enumerate_macos_keychain_certs(
  15832. [&](const unsigned char *data, size_t len) {
  15833. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  15834. static_cast<long>(len),
  15835. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  15836. });
  15837. #else
  15838. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15839. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  15840. SSL_SUCCESS) {
  15841. loaded = true;
  15842. break;
  15843. }
  15844. }
  15845. if (!loaded) {
  15846. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15847. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  15848. SSL_SUCCESS) {
  15849. loaded = true;
  15850. break;
  15851. }
  15852. }
  15853. }
  15854. #endif
  15855. return loaded;
  15856. }
  15857. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15858. const char *password) {
  15859. if (!ctx || !cert || !key) { return false; }
  15860. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15861. // Load certificate
  15862. int ret = wolfSSL_CTX_use_certificate_buffer(
  15863. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  15864. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  15865. if (ret != SSL_SUCCESS) {
  15866. impl::wolfssl_last_error() =
  15867. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15868. return false;
  15869. }
  15870. // Set password callback if password is provided
  15871. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  15872. // Load private key
  15873. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  15874. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  15875. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  15876. if (ret != SSL_SUCCESS) {
  15877. impl::wolfssl_last_error() =
  15878. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15879. return false;
  15880. }
  15881. // Verify that the certificate and private key match
  15882. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  15883. }
  15884. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15885. const char *key_path, const char *password) {
  15886. if (!ctx || !cert_path || !key_path) { return false; }
  15887. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15888. // Load certificate file
  15889. int ret =
  15890. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  15891. if (ret != SSL_SUCCESS) {
  15892. impl::wolfssl_last_error() =
  15893. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15894. return false;
  15895. }
  15896. // Set password callback if password is provided
  15897. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  15898. // Load private key file
  15899. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  15900. if (ret != SSL_SUCCESS) {
  15901. impl::wolfssl_last_error() =
  15902. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15903. return false;
  15904. }
  15905. // Verify that the certificate and private key match
  15906. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  15907. }
  15908. inline void set_verify_client(ctx_t ctx, bool require) {
  15909. if (!ctx) { return; }
  15910. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15911. wctx->verify_client = require;
  15912. if (require) {
  15913. wolfSSL_CTX_set_verify(
  15914. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15915. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  15916. } else {
  15917. if (wctx->has_verify_callback) {
  15918. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  15919. impl::wolfssl_verify_callback);
  15920. } else {
  15921. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  15922. }
  15923. }
  15924. }
  15925. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15926. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15927. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15928. auto session = new (std::nothrow) impl::WolfSSLSession();
  15929. if (!session) { return nullptr; }
  15930. session->sock = sock;
  15931. session->ssl = wolfSSL_new(wctx->ctx);
  15932. if (!session->ssl) {
  15933. impl::wolfssl_last_error() =
  15934. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15935. delete session;
  15936. return nullptr;
  15937. }
  15938. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  15939. return static_cast<session_t>(session);
  15940. }
  15941. inline void free_session(session_t session) {
  15942. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  15943. }
  15944. inline bool set_sni(session_t session, const char *hostname) {
  15945. if (!session || !hostname) { return false; }
  15946. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  15947. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  15948. static_cast<word16>(strlen(hostname)));
  15949. if (ret != WOLFSSL_SUCCESS) {
  15950. impl::wolfssl_last_error() =
  15951. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15952. return false;
  15953. }
  15954. // Also set hostname for verification
  15955. wolfSSL_check_domain_name(wsession->ssl, hostname);
  15956. wsession->hostname = hostname;
  15957. return true;
  15958. }
  15959. inline bool set_hostname(session_t session, const char *hostname) {
  15960. // In wolfSSL, set_hostname also sets up hostname verification
  15961. return set_sni(session, hostname);
  15962. }
  15963. inline TlsError connect(session_t session) {
  15964. TlsError err;
  15965. if (!session) {
  15966. err.code = ErrorCode::Fatal;
  15967. return err;
  15968. }
  15969. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  15970. int ret = wolfSSL_connect(wsession->ssl);
  15971. if (ret == SSL_SUCCESS) {
  15972. err.code = ErrorCode::Success;
  15973. } else {
  15974. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  15975. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  15976. err.backend_code = static_cast<uint64_t>(ssl_error);
  15977. impl::wolfssl_last_error() = err.backend_code;
  15978. }
  15979. return err;
  15980. }
  15981. inline TlsError accept(session_t session) {
  15982. TlsError err;
  15983. if (!session) {
  15984. err.code = ErrorCode::Fatal;
  15985. return err;
  15986. }
  15987. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  15988. int ret = wolfSSL_accept(wsession->ssl);
  15989. if (ret == SSL_SUCCESS) {
  15990. err.code = ErrorCode::Success;
  15991. // Capture SNI from thread-local storage after successful handshake
  15992. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  15993. impl::wolfssl_pending_sni().clear();
  15994. } else {
  15995. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  15996. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  15997. err.backend_code = static_cast<uint64_t>(ssl_error);
  15998. impl::wolfssl_last_error() = err.backend_code;
  15999. }
  16000. return err;
  16001. }
  16002. inline bool connect_nonblocking(session_t session, socket_t sock,
  16003. time_t timeout_sec, time_t timeout_usec,
  16004. TlsError *err) {
  16005. if (!session) {
  16006. if (err) { err->code = ErrorCode::Fatal; }
  16007. return false;
  16008. }
  16009. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16010. // Set socket to non-blocking mode
  16011. detail::set_nonblocking(sock, true);
  16012. auto cleanup =
  16013. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16014. int ret;
  16015. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16016. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16017. if (ssl_error == SSL_ERROR_WANT_READ) {
  16018. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16019. continue;
  16020. }
  16021. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16022. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16023. continue;
  16024. }
  16025. }
  16026. // Error or timeout
  16027. if (err) {
  16028. err->code =
  16029. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16030. err->backend_code = static_cast<uint64_t>(ssl_error);
  16031. }
  16032. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16033. return false;
  16034. }
  16035. if (err) { err->code = ErrorCode::Success; }
  16036. return true;
  16037. }
  16038. inline bool accept_nonblocking(session_t session, socket_t sock,
  16039. time_t timeout_sec, time_t timeout_usec,
  16040. TlsError *err) {
  16041. if (!session) {
  16042. if (err) { err->code = ErrorCode::Fatal; }
  16043. return false;
  16044. }
  16045. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16046. // Set socket to non-blocking mode
  16047. detail::set_nonblocking(sock, true);
  16048. auto cleanup =
  16049. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16050. int ret;
  16051. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16052. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16053. if (ssl_error == SSL_ERROR_WANT_READ) {
  16054. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16055. continue;
  16056. }
  16057. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16058. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16059. continue;
  16060. }
  16061. }
  16062. // Error or timeout
  16063. if (err) {
  16064. err->code =
  16065. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16066. err->backend_code = static_cast<uint64_t>(ssl_error);
  16067. }
  16068. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16069. return false;
  16070. }
  16071. if (err) { err->code = ErrorCode::Success; }
  16072. // Capture SNI from thread-local storage after successful handshake
  16073. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16074. impl::wolfssl_pending_sni().clear();
  16075. return true;
  16076. }
  16077. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16078. if (!session || !buf) {
  16079. err.code = ErrorCode::Fatal;
  16080. return -1;
  16081. }
  16082. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16083. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16084. if (ret > 0) {
  16085. err.code = ErrorCode::Success;
  16086. return static_cast<ssize_t>(ret);
  16087. }
  16088. if (ret == 0) {
  16089. err.code = ErrorCode::PeerClosed;
  16090. return 0;
  16091. }
  16092. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16093. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16094. err.backend_code = static_cast<uint64_t>(ssl_error);
  16095. impl::wolfssl_last_error() = err.backend_code;
  16096. return -1;
  16097. }
  16098. inline ssize_t write(session_t session, const void *buf, size_t len,
  16099. TlsError &err) {
  16100. if (!session || !buf) {
  16101. err.code = ErrorCode::Fatal;
  16102. return -1;
  16103. }
  16104. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16105. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16106. if (ret > 0) {
  16107. err.code = ErrorCode::Success;
  16108. return static_cast<ssize_t>(ret);
  16109. }
  16110. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16111. // Treat this as an error (return -1) so callers don't spin in a
  16112. // write loop adding zero to the offset.
  16113. if (ret == 0) {
  16114. err.code = ErrorCode::PeerClosed;
  16115. return -1;
  16116. }
  16117. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16118. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16119. err.backend_code = static_cast<uint64_t>(ssl_error);
  16120. impl::wolfssl_last_error() = err.backend_code;
  16121. return -1;
  16122. }
  16123. inline int pending(const_session_t session) {
  16124. if (!session) { return 0; }
  16125. auto wsession =
  16126. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16127. return wolfSSL_pending(wsession->ssl);
  16128. }
  16129. inline void shutdown(session_t session, bool graceful) {
  16130. if (!session) { return; }
  16131. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16132. if (graceful) {
  16133. int ret;
  16134. int attempts = 0;
  16135. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16136. attempts < 3) {
  16137. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16138. if (ssl_error != SSL_ERROR_WANT_READ &&
  16139. ssl_error != SSL_ERROR_WANT_WRITE) {
  16140. break;
  16141. }
  16142. attempts++;
  16143. }
  16144. } else {
  16145. wolfSSL_shutdown(wsession->ssl);
  16146. }
  16147. }
  16148. inline bool is_peer_closed(session_t session, socket_t sock) {
  16149. if (!session || sock == INVALID_SOCKET) { return true; }
  16150. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16151. // Check if there's already decrypted data available
  16152. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16153. // Set socket to non-blocking to avoid blocking on read
  16154. detail::set_nonblocking(sock, true);
  16155. auto cleanup =
  16156. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16157. // Peek 1 byte to check connection status without consuming data
  16158. unsigned char buf;
  16159. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16160. // If we got data or WANT_READ (would block), connection is alive
  16161. if (ret > 0) { return false; }
  16162. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16163. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16164. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16165. ret == 0;
  16166. }
  16167. inline cert_t get_peer_cert(const_session_t session) {
  16168. if (!session) { return nullptr; }
  16169. auto wsession =
  16170. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16171. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16172. return static_cast<cert_t>(cert);
  16173. }
  16174. inline void free_cert(cert_t cert) {
  16175. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16176. }
  16177. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16178. if (!cert || !hostname) { return false; }
  16179. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16180. std::string host_str(hostname);
  16181. // Check if hostname is an IP address
  16182. bool is_ip = impl::is_ipv4_address(host_str);
  16183. unsigned char ip_bytes[4];
  16184. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  16185. // Check Subject Alternative Names
  16186. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16187. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16188. if (san_names) {
  16189. int san_count = wolfSSL_sk_num(san_names);
  16190. for (int i = 0; i < san_count; i++) {
  16191. auto *names =
  16192. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16193. if (!names) continue;
  16194. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16195. // DNS name
  16196. unsigned char *dns_name = nullptr;
  16197. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16198. if (dns_name && dns_len > 0) {
  16199. std::string san_name(reinterpret_cast<char *>(dns_name),
  16200. static_cast<size_t>(dns_len));
  16201. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16202. if (detail::match_hostname(san_name, host_str)) {
  16203. wolfSSL_sk_free(san_names);
  16204. return true;
  16205. }
  16206. }
  16207. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16208. // IP address
  16209. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16210. int ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16211. if (ip_data && ip_len == 4 && memcmp(ip_data, ip_bytes, 4) == 0) {
  16212. wolfSSL_sk_free(san_names);
  16213. return true;
  16214. }
  16215. }
  16216. }
  16217. wolfSSL_sk_free(san_names);
  16218. }
  16219. // Fallback: Check Common Name (CN) in subject
  16220. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16221. if (subject) {
  16222. char cn[256] = {};
  16223. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16224. sizeof(cn));
  16225. if (cn_len > 0) {
  16226. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16227. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16228. }
  16229. }
  16230. return false;
  16231. }
  16232. inline uint64_t hostname_mismatch_code() {
  16233. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16234. }
  16235. inline long get_verify_result(const_session_t session) {
  16236. if (!session) { return -1; }
  16237. auto wsession =
  16238. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16239. long result = wolfSSL_get_verify_result(wsession->ssl);
  16240. return result;
  16241. }
  16242. inline std::string get_cert_subject_cn(cert_t cert) {
  16243. if (!cert) return "";
  16244. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16245. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16246. if (!subject) return "";
  16247. char cn[256] = {};
  16248. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16249. sizeof(cn));
  16250. if (cn_len <= 0) return "";
  16251. return std::string(cn, static_cast<size_t>(cn_len));
  16252. }
  16253. inline std::string get_cert_issuer_name(cert_t cert) {
  16254. if (!cert) return "";
  16255. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16256. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16257. if (!issuer) return "";
  16258. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16259. if (!name_str) return "";
  16260. std::string result(name_str);
  16261. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16262. return result;
  16263. }
  16264. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16265. sans.clear();
  16266. if (!cert) return false;
  16267. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16268. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16269. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16270. if (!san_names) return true; // No SANs is not an error
  16271. int count = wolfSSL_sk_num(san_names);
  16272. for (int i = 0; i < count; i++) {
  16273. auto *name =
  16274. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16275. if (!name) continue;
  16276. SanEntry entry;
  16277. switch (name->type) {
  16278. case WOLFSSL_GEN_DNS: {
  16279. entry.type = SanType::DNS;
  16280. unsigned char *dns_name = nullptr;
  16281. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16282. if (dns_name && dns_len > 0) {
  16283. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16284. static_cast<size_t>(dns_len));
  16285. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16286. }
  16287. break;
  16288. }
  16289. case WOLFSSL_GEN_IPADD: {
  16290. entry.type = SanType::IP;
  16291. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16292. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16293. if (ip_data && ip_len == 4) {
  16294. char buf[16];
  16295. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16296. ip_data[2], ip_data[3]);
  16297. entry.value = buf;
  16298. } else if (ip_data && ip_len == 16) {
  16299. char buf[64];
  16300. snprintf(buf, sizeof(buf),
  16301. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16302. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16303. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16304. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16305. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16306. ip_data[14], ip_data[15]);
  16307. entry.value = buf;
  16308. }
  16309. break;
  16310. }
  16311. case WOLFSSL_GEN_EMAIL:
  16312. entry.type = SanType::EMAIL;
  16313. {
  16314. unsigned char *email = nullptr;
  16315. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16316. if (email && email_len > 0) {
  16317. entry.value = std::string(reinterpret_cast<char *>(email),
  16318. static_cast<size_t>(email_len));
  16319. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16320. }
  16321. }
  16322. break;
  16323. case WOLFSSL_GEN_URI:
  16324. entry.type = SanType::URI;
  16325. {
  16326. unsigned char *uri = nullptr;
  16327. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  16328. &uri, name->d.uniformResourceIdentifier);
  16329. if (uri && uri_len > 0) {
  16330. entry.value = std::string(reinterpret_cast<char *>(uri),
  16331. static_cast<size_t>(uri_len));
  16332. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  16333. }
  16334. }
  16335. break;
  16336. default: entry.type = SanType::OTHER; break;
  16337. }
  16338. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16339. }
  16340. wolfSSL_sk_free(san_names);
  16341. return true;
  16342. }
  16343. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16344. time_t &not_after) {
  16345. if (!cert) return false;
  16346. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16347. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  16348. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  16349. if (!nb || !na) return false;
  16350. // wolfSSL_ASN1_TIME_to_tm is available
  16351. struct tm tm_nb = {}, tm_na = {};
  16352. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  16353. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  16354. #ifdef _WIN32
  16355. not_before = _mkgmtime(&tm_nb);
  16356. not_after = _mkgmtime(&tm_na);
  16357. #else
  16358. not_before = timegm(&tm_nb);
  16359. not_after = timegm(&tm_na);
  16360. #endif
  16361. return true;
  16362. }
  16363. inline std::string get_cert_serial(cert_t cert) {
  16364. if (!cert) return "";
  16365. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16366. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  16367. if (!serial_asn1) return "";
  16368. // Get the serial number data
  16369. int len = serial_asn1->length;
  16370. unsigned char *data = serial_asn1->data;
  16371. if (!data || len <= 0) return "";
  16372. std::string result;
  16373. result.reserve(static_cast<size_t>(len) * 2);
  16374. for (int i = 0; i < len; i++) {
  16375. char hex[3];
  16376. snprintf(hex, sizeof(hex), "%02X", data[i]);
  16377. result += hex;
  16378. }
  16379. return result;
  16380. }
  16381. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16382. if (!cert) return false;
  16383. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16384. int der_len = 0;
  16385. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  16386. if (!der_data || der_len <= 0) return false;
  16387. der.assign(der_data, der_data + der_len);
  16388. return true;
  16389. }
  16390. inline const char *get_sni(const_session_t session) {
  16391. if (!session) return nullptr;
  16392. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  16393. // For server: return SNI received from client during handshake
  16394. if (!wsession->sni_hostname.empty()) {
  16395. return wsession->sni_hostname.c_str();
  16396. }
  16397. // For client: return the hostname set via set_sni
  16398. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  16399. return nullptr;
  16400. }
  16401. inline uint64_t peek_error() {
  16402. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16403. }
  16404. inline uint64_t get_error() {
  16405. uint64_t err = impl::wolfssl_last_error();
  16406. impl::wolfssl_last_error() = 0;
  16407. return err;
  16408. }
  16409. inline std::string error_string(uint64_t code) {
  16410. char buf[256];
  16411. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  16412. return std::string(buf);
  16413. }
  16414. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16415. if (!pem || len == 0) { return nullptr; }
  16416. // Validate by attempting to load into a temporary ctx
  16417. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  16418. if (!tmp_ctx) { return nullptr; }
  16419. int ret = wolfSSL_CTX_load_verify_buffer(
  16420. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  16421. static_cast<long>(len), SSL_FILETYPE_PEM);
  16422. wolfSSL_CTX_free(tmp_ctx);
  16423. if (ret != SSL_SUCCESS) { return nullptr; }
  16424. return static_cast<ca_store_t>(
  16425. new impl::WolfSSLCAStore{std::string(pem, len)});
  16426. }
  16427. inline void free_ca_store(ca_store_t store) {
  16428. delete static_cast<impl::WolfSSLCAStore *>(store);
  16429. }
  16430. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16431. if (!ctx || !store) { return false; }
  16432. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16433. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  16434. int ret = wolfSSL_CTX_load_verify_buffer(
  16435. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  16436. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  16437. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  16438. return ret == SSL_SUCCESS;
  16439. }
  16440. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16441. certs.clear();
  16442. if (!ctx) { return 0; }
  16443. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16444. if (wctx->ca_pem_data_.empty()) { return 0; }
  16445. const std::string &pem = wctx->ca_pem_data_;
  16446. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  16447. const std::string end_marker = "-----END CERTIFICATE-----";
  16448. size_t pos = 0;
  16449. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  16450. size_t end_pos = pem.find(end_marker, pos);
  16451. if (end_pos == std::string::npos) { break; }
  16452. end_pos += end_marker.size();
  16453. std::string cert_pem = pem.substr(pos, end_pos - pos);
  16454. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  16455. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  16456. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  16457. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  16458. pos = end_pos;
  16459. }
  16460. return certs.size();
  16461. }
  16462. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16463. std::vector<std::string> names;
  16464. if (!ctx) { return names; }
  16465. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16466. if (wctx->ca_pem_data_.empty()) { return names; }
  16467. const std::string &pem = wctx->ca_pem_data_;
  16468. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  16469. const std::string end_marker = "-----END CERTIFICATE-----";
  16470. size_t pos = 0;
  16471. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  16472. size_t end_pos = pem.find(end_marker, pos);
  16473. if (end_pos == std::string::npos) { break; }
  16474. end_pos += end_marker.size();
  16475. std::string cert_pem = pem.substr(pos, end_pos - pos);
  16476. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  16477. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  16478. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  16479. if (x509) {
  16480. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16481. if (subject) {
  16482. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  16483. if (name_str) {
  16484. names.push_back(name_str);
  16485. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16486. }
  16487. }
  16488. wolfSSL_X509_free(x509);
  16489. }
  16490. pos = end_pos;
  16491. }
  16492. return names;
  16493. }
  16494. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16495. const char *key_pem, const char *password) {
  16496. if (!ctx || !cert_pem || !key_pem) { return false; }
  16497. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16498. // Load new certificate
  16499. int ret = wolfSSL_CTX_use_certificate_buffer(
  16500. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  16501. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  16502. if (ret != SSL_SUCCESS) {
  16503. impl::wolfssl_last_error() =
  16504. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16505. return false;
  16506. }
  16507. // Set password if provided
  16508. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16509. // Load new private key
  16510. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16511. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  16512. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  16513. if (ret != SSL_SUCCESS) {
  16514. impl::wolfssl_last_error() =
  16515. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16516. return false;
  16517. }
  16518. return true;
  16519. }
  16520. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16521. if (!ctx || !ca_pem) { return false; }
  16522. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16523. int ret = wolfSSL_CTX_load_verify_buffer(
  16524. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  16525. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  16526. if (ret != SSL_SUCCESS) {
  16527. impl::wolfssl_last_error() =
  16528. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16529. return false;
  16530. }
  16531. return true;
  16532. }
  16533. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16534. if (!ctx) { return false; }
  16535. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16536. impl::get_verify_callback() = std::move(callback);
  16537. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  16538. if (wctx->has_verify_callback) {
  16539. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16540. impl::wolfssl_verify_callback);
  16541. } else {
  16542. wolfSSL_CTX_set_verify(
  16543. wctx->ctx,
  16544. wctx->verify_client
  16545. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  16546. : SSL_VERIFY_NONE,
  16547. nullptr);
  16548. }
  16549. return true;
  16550. }
  16551. inline long get_verify_error(const_session_t session) {
  16552. if (!session) { return -1; }
  16553. auto *wsession =
  16554. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16555. return wolfSSL_get_verify_result(wsession->ssl);
  16556. }
  16557. inline std::string verify_error_string(long error_code) {
  16558. if (error_code == 0) { return ""; }
  16559. const char *str =
  16560. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  16561. return str ? std::string(str) : std::string();
  16562. }
  16563. } // namespace tls
  16564. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  16565. // WebSocket implementation
  16566. namespace ws {
  16567. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  16568. bool fin) {
  16569. std::lock_guard<std::mutex> lock(write_mutex_);
  16570. if (closed_) { return false; }
  16571. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  16572. }
  16573. inline ReadResult WebSocket::read(std::string &msg) {
  16574. while (!closed_) {
  16575. Opcode opcode;
  16576. std::string payload;
  16577. bool fin;
  16578. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  16579. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  16580. closed_ = true;
  16581. return Fail;
  16582. }
  16583. switch (opcode) {
  16584. case Opcode::Ping: {
  16585. std::lock_guard<std::mutex> lock(write_mutex_);
  16586. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  16587. payload.size(), true, !is_server_);
  16588. continue;
  16589. }
  16590. case Opcode::Pong: continue;
  16591. case Opcode::Close: {
  16592. if (!closed_.exchange(true)) {
  16593. // Echo close frame back
  16594. std::lock_guard<std::mutex> lock(write_mutex_);
  16595. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  16596. payload.size(), true, !is_server_);
  16597. }
  16598. return Fail;
  16599. }
  16600. case Opcode::Text:
  16601. case Opcode::Binary: {
  16602. auto result = opcode == Opcode::Text ? Text : Binary;
  16603. msg = std::move(payload);
  16604. // Handle fragmentation
  16605. if (!fin) {
  16606. while (true) {
  16607. Opcode cont_opcode;
  16608. std::string cont_payload;
  16609. bool cont_fin;
  16610. if (!impl::read_websocket_frame(
  16611. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  16612. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  16613. closed_ = true;
  16614. return Fail;
  16615. }
  16616. if (cont_opcode == Opcode::Ping) {
  16617. std::lock_guard<std::mutex> lock(write_mutex_);
  16618. detail::write_websocket_frame(
  16619. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  16620. true, !is_server_);
  16621. continue;
  16622. }
  16623. if (cont_opcode == Opcode::Pong) { continue; }
  16624. if (cont_opcode == Opcode::Close) {
  16625. if (!closed_.exchange(true)) {
  16626. std::lock_guard<std::mutex> lock(write_mutex_);
  16627. detail::write_websocket_frame(
  16628. strm_, Opcode::Close, cont_payload.data(),
  16629. cont_payload.size(), true, !is_server_);
  16630. }
  16631. return Fail;
  16632. }
  16633. // RFC 6455: continuation frames must use opcode 0x0
  16634. if (cont_opcode != Opcode::Continuation) {
  16635. closed_ = true;
  16636. return Fail;
  16637. }
  16638. msg += cont_payload;
  16639. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  16640. closed_ = true;
  16641. return Fail;
  16642. }
  16643. if (cont_fin) { break; }
  16644. }
  16645. }
  16646. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  16647. if (result == Text && !impl::is_valid_utf8(msg)) {
  16648. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  16649. return Fail;
  16650. }
  16651. return result;
  16652. }
  16653. default: closed_ = true; return Fail;
  16654. }
  16655. }
  16656. return Fail;
  16657. }
  16658. inline bool WebSocket::send(const std::string &data) {
  16659. return send_frame(Opcode::Text, data.data(), data.size());
  16660. }
  16661. inline bool WebSocket::send(const char *data, size_t len) {
  16662. return send_frame(Opcode::Binary, data, len);
  16663. }
  16664. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  16665. if (closed_.exchange(true)) { return; }
  16666. ping_cv_.notify_all();
  16667. std::string payload;
  16668. auto code = static_cast<uint16_t>(status);
  16669. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  16670. payload.push_back(static_cast<char>(code & 0xFF));
  16671. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  16672. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  16673. payload += reason.substr(0, 123);
  16674. {
  16675. std::lock_guard<std::mutex> lock(write_mutex_);
  16676. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  16677. payload.size(), true, !is_server_);
  16678. }
  16679. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  16680. // Close response before closing the TCP connection. Use a short timeout to
  16681. // avoid hanging if the peer doesn't respond.
  16682. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  16683. Opcode op;
  16684. std::string resp;
  16685. bool fin;
  16686. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  16687. if (op == Opcode::Close) { break; }
  16688. }
  16689. }
  16690. inline WebSocket::~WebSocket() {
  16691. {
  16692. std::lock_guard<std::mutex> lock(ping_mutex_);
  16693. closed_ = true;
  16694. }
  16695. ping_cv_.notify_all();
  16696. if (ping_thread_.joinable()) { ping_thread_.join(); }
  16697. }
  16698. inline void WebSocket::start_heartbeat() {
  16699. ping_thread_ = std::thread([this]() {
  16700. std::unique_lock<std::mutex> lock(ping_mutex_);
  16701. while (!closed_) {
  16702. ping_cv_.wait_for(lock, std::chrono::seconds(
  16703. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND));
  16704. if (closed_) { break; }
  16705. lock.unlock();
  16706. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  16707. closed_ = true;
  16708. break;
  16709. }
  16710. lock.lock();
  16711. }
  16712. });
  16713. }
  16714. inline const Request &WebSocket::request() const { return req_; }
  16715. inline bool WebSocket::is_open() const { return !closed_; }
  16716. // WebSocketClient implementation
  16717. inline WebSocketClient::WebSocketClient(
  16718. const std::string &scheme_host_port_path, const Headers &headers)
  16719. : headers_(headers) {
  16720. const static std::regex re(
  16721. R"(([a-z]+):\/\/(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?(\/.*))");
  16722. std::smatch m;
  16723. if (std::regex_match(scheme_host_port_path, m, re)) {
  16724. auto scheme = m[1].str();
  16725. #ifdef CPPHTTPLIB_SSL_ENABLED
  16726. if (scheme != "ws" && scheme != "wss") {
  16727. #else
  16728. if (scheme != "ws") {
  16729. #endif
  16730. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  16731. std::string msg = "'" + scheme + "' scheme is not supported.";
  16732. throw std::invalid_argument(msg);
  16733. #endif
  16734. return;
  16735. }
  16736. auto is_ssl = scheme == "wss";
  16737. host_ = m[2].str();
  16738. if (host_.empty()) { host_ = m[3].str(); }
  16739. auto port_str = m[4].str();
  16740. port_ = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  16741. path_ = m[5].str();
  16742. #ifdef CPPHTTPLIB_SSL_ENABLED
  16743. is_ssl_ = is_ssl;
  16744. #else
  16745. if (is_ssl) { return; }
  16746. #endif
  16747. is_valid_ = true;
  16748. }
  16749. }
  16750. inline WebSocketClient::~WebSocketClient() { shutdown_and_close(); }
  16751. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  16752. inline void WebSocketClient::shutdown_and_close() {
  16753. #ifdef CPPHTTPLIB_SSL_ENABLED
  16754. if (is_ssl_) {
  16755. if (tls_session_) {
  16756. tls::shutdown(tls_session_, true);
  16757. tls::free_session(tls_session_);
  16758. tls_session_ = nullptr;
  16759. }
  16760. if (tls_ctx_) {
  16761. tls::free_context(tls_ctx_);
  16762. tls_ctx_ = nullptr;
  16763. }
  16764. }
  16765. #endif
  16766. if (ws_ && ws_->is_open()) { ws_->close(); }
  16767. ws_.reset();
  16768. if (sock_ != INVALID_SOCKET) {
  16769. detail::shutdown_socket(sock_);
  16770. detail::close_socket(sock_);
  16771. sock_ = INVALID_SOCKET;
  16772. }
  16773. }
  16774. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  16775. #ifdef CPPHTTPLIB_SSL_ENABLED
  16776. if (is_ssl_) {
  16777. if (!detail::setup_client_tls_session(
  16778. host_, tls_ctx_, tls_session_, sock_,
  16779. server_certificate_verification_, ca_cert_file_path_,
  16780. ca_cert_store_, read_timeout_sec_, read_timeout_usec_)) {
  16781. return false;
  16782. }
  16783. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  16784. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  16785. write_timeout_sec_, write_timeout_usec_));
  16786. return true;
  16787. }
  16788. #endif
  16789. strm = std::unique_ptr<Stream>(
  16790. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  16791. write_timeout_sec_, write_timeout_usec_));
  16792. return true;
  16793. }
  16794. inline bool WebSocketClient::connect() {
  16795. if (!is_valid_) { return false; }
  16796. shutdown_and_close();
  16797. Error error;
  16798. sock_ = detail::create_client_socket(
  16799. host_, std::string(), port_, AF_UNSPEC, false, false, nullptr, 5, 0,
  16800. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  16801. write_timeout_usec_, std::string(), error);
  16802. if (sock_ == INVALID_SOCKET) { return false; }
  16803. std::unique_ptr<Stream> strm;
  16804. if (!create_stream(strm)) {
  16805. shutdown_and_close();
  16806. return false;
  16807. }
  16808. std::string selected_subprotocol;
  16809. if (!detail::perform_websocket_handshake(*strm, host_, port_, path_, headers_,
  16810. selected_subprotocol)) {
  16811. shutdown_and_close();
  16812. return false;
  16813. }
  16814. subprotocol_ = std::move(selected_subprotocol);
  16815. Request req;
  16816. req.method = "GET";
  16817. req.path = path_;
  16818. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false));
  16819. return true;
  16820. }
  16821. inline ReadResult WebSocketClient::read(std::string &msg) {
  16822. if (!ws_) { return Fail; }
  16823. return ws_->read(msg);
  16824. }
  16825. inline bool WebSocketClient::send(const std::string &data) {
  16826. if (!ws_) { return false; }
  16827. return ws_->send(data);
  16828. }
  16829. inline bool WebSocketClient::send(const char *data, size_t len) {
  16830. if (!ws_) { return false; }
  16831. return ws_->send(data, len);
  16832. }
  16833. inline void WebSocketClient::close(CloseStatus status,
  16834. const std::string &reason) {
  16835. if (ws_) { ws_->close(status, reason); }
  16836. }
  16837. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  16838. inline const std::string &WebSocketClient::subprotocol() const {
  16839. return subprotocol_;
  16840. }
  16841. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  16842. read_timeout_sec_ = sec;
  16843. read_timeout_usec_ = usec;
  16844. }
  16845. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  16846. write_timeout_sec_ = sec;
  16847. write_timeout_usec_ = usec;
  16848. }
  16849. #ifdef CPPHTTPLIB_SSL_ENABLED
  16850. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  16851. ca_cert_file_path_ = path;
  16852. }
  16853. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  16854. ca_cert_store_ = store;
  16855. }
  16856. inline void
  16857. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  16858. server_certificate_verification_ = enabled;
  16859. }
  16860. #endif // CPPHTTPLIB_SSL_ENABLED
  16861. } // namespace ws
  16862. // ----------------------------------------------------------------------------
  16863. } // namespace httplib
  16864. #endif // CPPHTTPLIB_HTTPLIB_H