httplib.h 660 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091
  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.43.2"
  10. #define CPPHTTPLIB_VERSION_NUM "0x002b02"
  11. #ifdef _WIN32
  12. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  13. #error \
  14. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  15. #endif
  16. #endif
  17. /*
  18. * Configuration
  19. */
  20. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  21. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  22. #endif
  23. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  24. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  25. #endif
  26. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  27. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  28. #endif
  29. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  30. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  31. #endif
  32. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  33. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  34. #endif
  35. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  36. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  37. #endif
  38. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  39. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  40. #endif
  41. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  42. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  43. #endif
  44. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  45. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  46. #endif
  47. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  60. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  61. #endif
  62. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  63. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  64. #endif
  65. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  66. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  67. #endif
  68. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  69. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  70. #endif
  71. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  72. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  73. #endif
  74. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  75. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  78. #ifdef _WIN32
  79. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  80. #else
  81. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  82. #endif
  83. #endif
  84. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  85. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  86. #endif
  87. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  88. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  89. #endif
  90. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  91. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  92. #endif
  93. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  94. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  95. #endif
  96. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  97. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  98. #endif
  99. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  100. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  101. #endif
  102. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  103. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  106. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  107. #endif
  108. #ifndef CPPHTTPLIB_TCP_NODELAY
  109. #define CPPHTTPLIB_TCP_NODELAY false
  110. #endif
  111. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  112. #define CPPHTTPLIB_IPV6_V6ONLY false
  113. #endif
  114. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  115. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  116. #endif
  117. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  118. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  119. #endif
  120. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  121. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  122. #endif
  123. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  124. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  125. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  126. ? std::thread::hardware_concurrency() - 1 \
  127. : 0))
  128. #endif
  129. #ifndef CPPHTTPLIB_THREAD_POOL_MAX_COUNT
  130. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  131. #endif
  132. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  133. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  134. #endif
  135. #ifndef CPPHTTPLIB_RECV_FLAGS
  136. #define CPPHTTPLIB_RECV_FLAGS 0
  137. #endif
  138. #ifndef CPPHTTPLIB_SEND_FLAGS
  139. #define CPPHTTPLIB_SEND_FLAGS 0
  140. #endif
  141. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  142. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  143. #endif
  144. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  145. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  146. #endif
  147. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  148. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  149. #endif
  150. #ifndef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  151. #define CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND 300
  152. #endif
  153. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  154. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  155. #endif
  156. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  157. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  158. #endif
  159. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  160. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  161. #endif
  162. /*
  163. * Headers
  164. */
  165. #ifdef _WIN32
  166. #ifndef _CRT_SECURE_NO_WARNINGS
  167. #define _CRT_SECURE_NO_WARNINGS
  168. #endif //_CRT_SECURE_NO_WARNINGS
  169. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  170. #define _CRT_NONSTDC_NO_DEPRECATE
  171. #endif //_CRT_NONSTDC_NO_DEPRECATE
  172. #if defined(_MSC_VER)
  173. #if _MSC_VER < 1900
  174. #error Sorry, Visual Studio versions prior to 2015 are not supported
  175. #endif
  176. #pragma comment(lib, "ws2_32.lib")
  177. #ifndef _SSIZE_T_DEFINED
  178. using ssize_t = __int64;
  179. #define _SSIZE_T_DEFINED
  180. #endif
  181. #endif // _MSC_VER
  182. #ifndef S_ISREG
  183. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  184. #endif // S_ISREG
  185. #ifndef S_ISDIR
  186. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  187. #endif // S_ISDIR
  188. #ifndef NOMINMAX
  189. #define NOMINMAX
  190. #endif // NOMINMAX
  191. #include <io.h>
  192. #include <winsock2.h>
  193. #include <ws2tcpip.h>
  194. #if defined(__has_include)
  195. #if __has_include(<afunix.h>)
  196. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  197. #include <afunix.h>
  198. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  199. #endif
  200. #endif
  201. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  202. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  203. #endif
  204. using nfds_t = unsigned long;
  205. using socket_t = SOCKET;
  206. using socklen_t = int;
  207. #else // not _WIN32
  208. #include <arpa/inet.h>
  209. #if !defined(_AIX) && !defined(__MVS__)
  210. #include <ifaddrs.h>
  211. #endif
  212. #ifdef __MVS__
  213. #include <strings.h>
  214. #ifndef NI_MAXHOST
  215. #define NI_MAXHOST 1025
  216. #endif
  217. #endif
  218. #include <net/if.h>
  219. #include <netdb.h>
  220. #include <netinet/in.h>
  221. #ifdef __linux__
  222. #include <resolv.h>
  223. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  224. #endif
  225. #include <csignal>
  226. #include <netinet/tcp.h>
  227. #include <poll.h>
  228. #include <pthread.h>
  229. #include <sys/mman.h>
  230. #include <sys/socket.h>
  231. #include <sys/un.h>
  232. #include <unistd.h>
  233. using socket_t = int;
  234. #ifndef INVALID_SOCKET
  235. #define INVALID_SOCKET (-1)
  236. #endif
  237. #endif //_WIN32
  238. #if defined(__APPLE__)
  239. #include <TargetConditionals.h>
  240. #endif
  241. #include <algorithm>
  242. #include <array>
  243. #include <atomic>
  244. #include <cassert>
  245. #include <cctype>
  246. #include <chrono>
  247. #include <climits>
  248. #include <condition_variable>
  249. #include <cstdlib>
  250. #include <cstring>
  251. #include <errno.h>
  252. #include <exception>
  253. #include <fcntl.h>
  254. #include <fstream>
  255. #include <functional>
  256. #include <iomanip>
  257. #include <iostream>
  258. #include <list>
  259. #include <map>
  260. #include <memory>
  261. #include <mutex>
  262. #include <random>
  263. #include <regex>
  264. #include <set>
  265. #include <sstream>
  266. #include <string>
  267. #include <sys/stat.h>
  268. #include <system_error>
  269. #include <thread>
  270. #include <unordered_map>
  271. #include <unordered_set>
  272. #include <utility>
  273. // On macOS with a TLS backend, enable Keychain root certificates by default
  274. // unless the user explicitly opts out.
  275. #if defined(__APPLE__) && defined(__clang__) && \
  276. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  277. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  278. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  279. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  280. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  281. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  282. #endif
  283. #endif
  284. // On Windows, enable Schannel certificate verification by default
  285. // unless the user explicitly opts out.
  286. #if defined(_WIN32) && \
  287. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  288. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  289. #endif
  290. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  291. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  292. #if TARGET_OS_MAC && defined(__clang__)
  293. #include <CFNetwork/CFHost.h>
  294. #include <CoreFoundation/CoreFoundation.h>
  295. #endif
  296. #endif
  297. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  298. #ifdef _WIN32
  299. #include <wincrypt.h>
  300. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  301. // used
  302. #undef X509_NAME
  303. #undef X509_CERT_PAIR
  304. #undef X509_EXTENSIONS
  305. #undef PKCS7_SIGNER_INFO
  306. #ifdef _MSC_VER
  307. #pragma comment(lib, "crypt32.lib")
  308. #endif
  309. #endif // _WIN32
  310. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  311. #if TARGET_OS_MAC
  312. #include <Security/Security.h>
  313. #endif
  314. #endif
  315. #include <openssl/err.h>
  316. #include <openssl/evp.h>
  317. #include <openssl/ssl.h>
  318. #include <openssl/x509v3.h>
  319. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  320. #include <openssl/applink.c>
  321. #endif
  322. #include <iostream>
  323. #include <sstream>
  324. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  325. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  326. #error Please use OpenSSL or a current version of BoringSSL
  327. #endif
  328. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  329. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  330. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  331. #endif
  332. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  333. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  334. #include <mbedtls/ctr_drbg.h>
  335. #include <mbedtls/entropy.h>
  336. #include <mbedtls/error.h>
  337. #include <mbedtls/md5.h>
  338. #include <mbedtls/net_sockets.h>
  339. #include <mbedtls/oid.h>
  340. #include <mbedtls/pk.h>
  341. #include <mbedtls/sha1.h>
  342. #include <mbedtls/sha256.h>
  343. #include <mbedtls/sha512.h>
  344. #include <mbedtls/ssl.h>
  345. #include <mbedtls/x509_crt.h>
  346. #ifdef _WIN32
  347. #include <wincrypt.h>
  348. #ifdef _MSC_VER
  349. #pragma comment(lib, "crypt32.lib")
  350. #endif
  351. #endif // _WIN32
  352. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  353. #if TARGET_OS_MAC
  354. #include <Security/Security.h>
  355. #endif
  356. #endif
  357. // Mbed TLS 3.x API compatibility
  358. #if MBEDTLS_VERSION_MAJOR >= 3
  359. #define CPPHTTPLIB_MBEDTLS_V3
  360. #endif
  361. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  362. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  363. #include <wolfssl/options.h>
  364. #include <wolfssl/openssl/x509v3.h>
  365. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  366. #ifndef WOLFSSL_GEN_EMAIL
  367. #define WOLFSSL_GEN_EMAIL 1
  368. #endif
  369. #ifndef WOLFSSL_GEN_DNS
  370. #define WOLFSSL_GEN_DNS 2
  371. #endif
  372. #ifndef WOLFSSL_GEN_URI
  373. #define WOLFSSL_GEN_URI 6
  374. #endif
  375. #ifndef WOLFSSL_GEN_IPADD
  376. #define WOLFSSL_GEN_IPADD 7
  377. #endif
  378. #include <wolfssl/ssl.h>
  379. #include <wolfssl/wolfcrypt/hash.h>
  380. #include <wolfssl/wolfcrypt/md5.h>
  381. #include <wolfssl/wolfcrypt/sha256.h>
  382. #include <wolfssl/wolfcrypt/sha512.h>
  383. #ifdef _WIN32
  384. #include <wincrypt.h>
  385. #ifdef _MSC_VER
  386. #pragma comment(lib, "crypt32.lib")
  387. #endif
  388. #endif // _WIN32
  389. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  390. #if TARGET_OS_MAC
  391. #include <Security/Security.h>
  392. #endif
  393. #endif
  394. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  395. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  396. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  397. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  398. #define CPPHTTPLIB_SSL_ENABLED
  399. #endif
  400. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  401. #include <zlib.h>
  402. #endif
  403. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  404. #include <brotli/decode.h>
  405. #include <brotli/encode.h>
  406. #endif
  407. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  408. #include <zstd.h>
  409. #endif
  410. /*
  411. * Declaration
  412. */
  413. namespace httplib {
  414. namespace ws {
  415. class WebSocket;
  416. } // namespace ws
  417. namespace detail {
  418. /*
  419. * Backport std::make_unique from C++14.
  420. *
  421. * NOTE: This code came up with the following stackoverflow post:
  422. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  423. *
  424. */
  425. template <class T, class... Args>
  426. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  427. make_unique(Args &&...args) {
  428. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  429. }
  430. template <class T>
  431. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  432. make_unique(std::size_t n) {
  433. typedef typename std::remove_extent<T>::type RT;
  434. return std::unique_ptr<T>(new RT[n]);
  435. }
  436. namespace case_ignore {
  437. inline unsigned char to_lower(int c) {
  438. const static unsigned char table[256] = {
  439. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  440. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  441. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  442. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  443. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  444. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  445. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  446. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  447. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  448. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  449. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  450. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  451. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  452. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  453. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  454. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  455. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  456. 255,
  457. };
  458. return table[(unsigned char)(char)c];
  459. }
  460. inline std::string to_lower(const std::string &s) {
  461. std::string result = s;
  462. std::transform(
  463. result.begin(), result.end(), result.begin(),
  464. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  465. return result;
  466. }
  467. inline bool equal(const std::string &a, const std::string &b) {
  468. return a.size() == b.size() &&
  469. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  470. return to_lower(ca) == to_lower(cb);
  471. });
  472. }
  473. struct equal_to {
  474. bool operator()(const std::string &a, const std::string &b) const {
  475. return equal(a, b);
  476. }
  477. };
  478. struct hash {
  479. size_t operator()(const std::string &key) const {
  480. return hash_core(key.data(), key.size(), 0);
  481. }
  482. size_t hash_core(const char *s, size_t l, size_t h) const {
  483. return (l == 0) ? h
  484. : hash_core(s + 1, l - 1,
  485. // Unsets the 6 high bits of h, therefore no
  486. // overflow happens
  487. (((std::numeric_limits<size_t>::max)() >> 6) &
  488. h * 33) ^
  489. static_cast<unsigned char>(to_lower(*s)));
  490. }
  491. };
  492. template <typename T>
  493. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  494. detail::case_ignore::equal_to>;
  495. } // namespace case_ignore
  496. // This is based on
  497. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  498. struct scope_exit {
  499. explicit scope_exit(std::function<void(void)> &&f)
  500. : exit_function(std::move(f)), execute_on_destruction{true} {}
  501. scope_exit(scope_exit &&rhs) noexcept
  502. : exit_function(std::move(rhs.exit_function)),
  503. execute_on_destruction{rhs.execute_on_destruction} {
  504. rhs.release();
  505. }
  506. ~scope_exit() {
  507. if (execute_on_destruction) { this->exit_function(); }
  508. }
  509. void release() { this->execute_on_destruction = false; }
  510. private:
  511. scope_exit(const scope_exit &) = delete;
  512. void operator=(const scope_exit &) = delete;
  513. scope_exit &operator=(scope_exit &&) = delete;
  514. std::function<void(void)> exit_function;
  515. bool execute_on_destruction;
  516. };
  517. // Simple from_chars implementation for integer and double types (C++17
  518. // substitute)
  519. template <typename T> struct from_chars_result {
  520. const char *ptr;
  521. std::errc ec;
  522. };
  523. template <typename T>
  524. inline from_chars_result<T> from_chars(const char *first, const char *last,
  525. T &value, int base = 10) {
  526. value = 0;
  527. const char *p = first;
  528. bool negative = false;
  529. if (p != last && *p == '-') {
  530. negative = true;
  531. ++p;
  532. }
  533. if (p == last) { return {first, std::errc::invalid_argument}; }
  534. T result = 0;
  535. for (; p != last; ++p) {
  536. char c = *p;
  537. int digit = -1;
  538. if ('0' <= c && c <= '9') {
  539. digit = c - '0';
  540. } else if ('a' <= c && c <= 'z') {
  541. digit = c - 'a' + 10;
  542. } else if ('A' <= c && c <= 'Z') {
  543. digit = c - 'A' + 10;
  544. } else {
  545. break;
  546. }
  547. if (digit < 0 || digit >= base) { break; }
  548. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  549. return {p, std::errc::result_out_of_range};
  550. }
  551. result = result * base + digit;
  552. }
  553. if (p == first || (negative && p == first + 1)) {
  554. return {first, std::errc::invalid_argument};
  555. }
  556. value = negative ? -result : result;
  557. return {p, std::errc{}};
  558. }
  559. // from_chars for double (simple wrapper for strtod)
  560. inline from_chars_result<double> from_chars(const char *first, const char *last,
  561. double &value) {
  562. std::string s(first, last);
  563. char *endptr = nullptr;
  564. errno = 0;
  565. value = std::strtod(s.c_str(), &endptr);
  566. if (endptr == s.c_str()) { return {first, std::errc::invalid_argument}; }
  567. if (errno == ERANGE) {
  568. return {first + (endptr - s.c_str()), std::errc::result_out_of_range};
  569. }
  570. return {first + (endptr - s.c_str()), std::errc{}};
  571. }
  572. inline bool parse_port(const char *s, size_t len, int &port) {
  573. int val = 0;
  574. auto r = from_chars(s, s + len, val);
  575. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  576. port = val;
  577. return true;
  578. }
  579. inline bool parse_port(const std::string &s, int &port) {
  580. return parse_port(s.data(), s.size(), port);
  581. }
  582. struct UrlComponents {
  583. std::string scheme;
  584. std::string host;
  585. std::string port;
  586. std::string path;
  587. std::string query;
  588. };
  589. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  590. uc = {};
  591. size_t pos = 0;
  592. auto sep = url.find("://");
  593. if (sep != std::string::npos) {
  594. uc.scheme = url.substr(0, sep);
  595. // Scheme must be [a-z]+ only
  596. if (uc.scheme.empty()) { return false; }
  597. for (auto c : uc.scheme) {
  598. if (c < 'a' || c > 'z') { return false; }
  599. }
  600. pos = sep + 3;
  601. } else if (url.compare(0, 2, "//") == 0) {
  602. pos = 2;
  603. }
  604. auto has_authority_prefix = pos > 0;
  605. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  606. url[0] != '?' && url[0] != '#');
  607. if (has_authority) {
  608. if (pos < url.size() && url[pos] == '[') {
  609. auto close = url.find(']', pos);
  610. if (close == std::string::npos) { return false; }
  611. uc.host = url.substr(pos + 1, close - pos - 1);
  612. // IPv6 host must be [a-fA-F0-9:]+ only
  613. if (uc.host.empty()) { return false; }
  614. for (auto c : uc.host) {
  615. if (!((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') ||
  616. (c >= '0' && c <= '9') || c == ':')) {
  617. return false;
  618. }
  619. }
  620. pos = close + 1;
  621. } else {
  622. auto end = url.find_first_of(":/?#", pos);
  623. if (end == std::string::npos) { end = url.size(); }
  624. uc.host = url.substr(pos, end - pos);
  625. pos = end;
  626. }
  627. if (pos < url.size() && url[pos] == ':') {
  628. ++pos;
  629. auto end = url.find_first_of("/?#", pos);
  630. if (end == std::string::npos) { end = url.size(); }
  631. uc.port = url.substr(pos, end - pos);
  632. pos = end;
  633. }
  634. // Without :// or //, the entire input must be consumed as host[:port].
  635. // If there is leftover (path, query, etc.), this is not a valid
  636. // host[:port] string — clear and reparse as a plain path.
  637. if (!has_authority_prefix && pos < url.size()) {
  638. uc.host.clear();
  639. uc.port.clear();
  640. pos = 0;
  641. }
  642. }
  643. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  644. auto end = url.find_first_of("?#", pos);
  645. if (end == std::string::npos) { end = url.size(); }
  646. uc.path = url.substr(pos, end - pos);
  647. pos = end;
  648. }
  649. if (pos < url.size() && url[pos] == '?') {
  650. auto end = url.find('#', pos);
  651. if (end == std::string::npos) { end = url.size(); }
  652. uc.query = url.substr(pos, end - pos);
  653. }
  654. return true;
  655. }
  656. } // namespace detail
  657. enum class SSLVerifierResponse {
  658. // no decision has been made, use the built-in certificate verifier
  659. NoDecisionMade,
  660. // connection certificate is verified and accepted
  661. CertificateAccepted,
  662. // connection certificate was processed but is rejected
  663. CertificateRejected
  664. };
  665. enum StatusCode {
  666. // Information responses
  667. Continue_100 = 100,
  668. SwitchingProtocol_101 = 101,
  669. Processing_102 = 102,
  670. EarlyHints_103 = 103,
  671. // Successful responses
  672. OK_200 = 200,
  673. Created_201 = 201,
  674. Accepted_202 = 202,
  675. NonAuthoritativeInformation_203 = 203,
  676. NoContent_204 = 204,
  677. ResetContent_205 = 205,
  678. PartialContent_206 = 206,
  679. MultiStatus_207 = 207,
  680. AlreadyReported_208 = 208,
  681. IMUsed_226 = 226,
  682. // Redirection messages
  683. MultipleChoices_300 = 300,
  684. MovedPermanently_301 = 301,
  685. Found_302 = 302,
  686. SeeOther_303 = 303,
  687. NotModified_304 = 304,
  688. UseProxy_305 = 305,
  689. unused_306 = 306,
  690. TemporaryRedirect_307 = 307,
  691. PermanentRedirect_308 = 308,
  692. // Client error responses
  693. BadRequest_400 = 400,
  694. Unauthorized_401 = 401,
  695. PaymentRequired_402 = 402,
  696. Forbidden_403 = 403,
  697. NotFound_404 = 404,
  698. MethodNotAllowed_405 = 405,
  699. NotAcceptable_406 = 406,
  700. ProxyAuthenticationRequired_407 = 407,
  701. RequestTimeout_408 = 408,
  702. Conflict_409 = 409,
  703. Gone_410 = 410,
  704. LengthRequired_411 = 411,
  705. PreconditionFailed_412 = 412,
  706. PayloadTooLarge_413 = 413,
  707. UriTooLong_414 = 414,
  708. UnsupportedMediaType_415 = 415,
  709. RangeNotSatisfiable_416 = 416,
  710. ExpectationFailed_417 = 417,
  711. ImATeapot_418 = 418,
  712. MisdirectedRequest_421 = 421,
  713. UnprocessableContent_422 = 422,
  714. Locked_423 = 423,
  715. FailedDependency_424 = 424,
  716. TooEarly_425 = 425,
  717. UpgradeRequired_426 = 426,
  718. PreconditionRequired_428 = 428,
  719. TooManyRequests_429 = 429,
  720. RequestHeaderFieldsTooLarge_431 = 431,
  721. UnavailableForLegalReasons_451 = 451,
  722. // Server error responses
  723. InternalServerError_500 = 500,
  724. NotImplemented_501 = 501,
  725. BadGateway_502 = 502,
  726. ServiceUnavailable_503 = 503,
  727. GatewayTimeout_504 = 504,
  728. HttpVersionNotSupported_505 = 505,
  729. VariantAlsoNegotiates_506 = 506,
  730. InsufficientStorage_507 = 507,
  731. LoopDetected_508 = 508,
  732. NotExtended_510 = 510,
  733. NetworkAuthenticationRequired_511 = 511,
  734. };
  735. using Headers =
  736. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  737. detail::case_ignore::equal_to>;
  738. using Params = std::multimap<std::string, std::string>;
  739. using Match = std::smatch;
  740. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  741. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  742. /*
  743. * detail: type-erased storage used by UserData.
  744. * ABI-stable regardless of C++ standard — always uses this custom
  745. * implementation instead of std::any.
  746. */
  747. namespace detail {
  748. using any_type_id = const void *;
  749. template <typename T> any_type_id any_typeid() noexcept {
  750. static const char id = 0;
  751. return &id;
  752. }
  753. struct any_storage {
  754. virtual ~any_storage() = default;
  755. virtual std::unique_ptr<any_storage> clone() const = 0;
  756. virtual any_type_id type_id() const noexcept = 0;
  757. };
  758. template <typename T> struct any_value final : any_storage {
  759. T value;
  760. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  761. std::unique_ptr<any_storage> clone() const override {
  762. return std::unique_ptr<any_storage>(new any_value<T>(value));
  763. }
  764. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  765. };
  766. } // namespace detail
  767. class UserData {
  768. public:
  769. UserData() = default;
  770. UserData(UserData &&) noexcept = default;
  771. UserData &operator=(UserData &&) noexcept = default;
  772. UserData(const UserData &o) {
  773. for (const auto &e : o.entries_) {
  774. if (e.second) { entries_[e.first] = e.second->clone(); }
  775. }
  776. }
  777. UserData &operator=(const UserData &o) {
  778. if (this != &o) {
  779. entries_.clear();
  780. for (const auto &e : o.entries_) {
  781. if (e.second) { entries_[e.first] = e.second->clone(); }
  782. }
  783. }
  784. return *this;
  785. }
  786. template <typename T> void set(const std::string &key, T &&value) {
  787. using D = typename std::decay<T>::type;
  788. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  789. }
  790. template <typename T> T *get(const std::string &key) noexcept {
  791. auto it = entries_.find(key);
  792. if (it == entries_.end() || !it->second) { return nullptr; }
  793. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  794. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  795. }
  796. template <typename T> const T *get(const std::string &key) const noexcept {
  797. auto it = entries_.find(key);
  798. if (it == entries_.end() || !it->second) { return nullptr; }
  799. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  800. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  801. }
  802. bool has(const std::string &key) const noexcept {
  803. return entries_.find(key) != entries_.end();
  804. }
  805. void erase(const std::string &key) { entries_.erase(key); }
  806. void clear() noexcept { entries_.clear(); }
  807. private:
  808. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  809. entries_;
  810. };
  811. struct Response;
  812. using ResponseHandler = std::function<bool(const Response &response)>;
  813. struct FormData {
  814. std::string name;
  815. std::string content;
  816. std::string filename;
  817. std::string content_type;
  818. Headers headers;
  819. };
  820. struct FormField {
  821. std::string name;
  822. std::string content;
  823. Headers headers;
  824. };
  825. using FormFields = std::multimap<std::string, FormField>;
  826. using FormFiles = std::multimap<std::string, FormData>;
  827. struct MultipartFormData {
  828. FormFields fields; // Text fields from multipart
  829. FormFiles files; // Files from multipart
  830. // Text field access
  831. std::string get_field(const std::string &key, size_t id = 0) const;
  832. std::vector<std::string> get_fields(const std::string &key) const;
  833. bool has_field(const std::string &key) const;
  834. size_t get_field_count(const std::string &key) const;
  835. // File access
  836. FormData get_file(const std::string &key, size_t id = 0) const;
  837. std::vector<FormData> get_files(const std::string &key) const;
  838. bool has_file(const std::string &key) const;
  839. size_t get_file_count(const std::string &key) const;
  840. };
  841. struct UploadFormData {
  842. std::string name;
  843. std::string content;
  844. std::string filename;
  845. std::string content_type;
  846. };
  847. using UploadFormDataItems = std::vector<UploadFormData>;
  848. class DataSink {
  849. public:
  850. DataSink() : os(&sb_), sb_(*this) {}
  851. DataSink(const DataSink &) = delete;
  852. DataSink &operator=(const DataSink &) = delete;
  853. DataSink(DataSink &&) = delete;
  854. DataSink &operator=(DataSink &&) = delete;
  855. std::function<bool(const char *data, size_t data_len)> write;
  856. std::function<bool()> is_writable;
  857. std::function<void()> done;
  858. std::function<void(const Headers &trailer)> done_with_trailer;
  859. std::ostream os;
  860. private:
  861. class data_sink_streambuf final : public std::streambuf {
  862. public:
  863. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  864. protected:
  865. std::streamsize xsputn(const char *s, std::streamsize n) override {
  866. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  867. return 0;
  868. }
  869. private:
  870. DataSink &sink_;
  871. };
  872. data_sink_streambuf sb_;
  873. };
  874. using ContentProvider =
  875. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  876. using ContentProviderWithoutLength =
  877. std::function<bool(size_t offset, DataSink &sink)>;
  878. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  879. struct FormDataProvider {
  880. std::string name;
  881. ContentProviderWithoutLength provider;
  882. std::string filename;
  883. std::string content_type;
  884. };
  885. using FormDataProviderItems = std::vector<FormDataProvider>;
  886. inline FormDataProvider
  887. make_file_provider(const std::string &name, const std::string &filepath,
  888. const std::string &filename = std::string(),
  889. const std::string &content_type = std::string()) {
  890. FormDataProvider fdp;
  891. fdp.name = name;
  892. fdp.filename = filename.empty() ? filepath : filename;
  893. fdp.content_type = content_type;
  894. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  895. std::ifstream f(filepath, std::ios::binary);
  896. if (!f) { return false; }
  897. if (offset > 0) {
  898. f.seekg(static_cast<std::streamoff>(offset));
  899. if (!f.good()) {
  900. sink.done();
  901. return true;
  902. }
  903. }
  904. char buf[8192];
  905. f.read(buf, sizeof(buf));
  906. auto n = static_cast<size_t>(f.gcount());
  907. if (n > 0) { return sink.write(buf, n); }
  908. sink.done(); // EOF
  909. return true;
  910. };
  911. return fdp;
  912. }
  913. inline std::pair<size_t, ContentProvider>
  914. make_file_body(const std::string &filepath) {
  915. size_t size = 0;
  916. {
  917. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  918. if (!f) { return {0, ContentProvider{}}; }
  919. size = static_cast<size_t>(f.tellg());
  920. }
  921. ContentProvider provider = [filepath](size_t offset, size_t length,
  922. DataSink &sink) -> bool {
  923. std::ifstream f(filepath, std::ios::binary);
  924. if (!f) { return false; }
  925. f.seekg(static_cast<std::streamoff>(offset));
  926. if (!f.good()) { return false; }
  927. char buf[8192];
  928. while (length > 0) {
  929. auto to_read = (std::min)(sizeof(buf), length);
  930. f.read(buf, static_cast<std::streamsize>(to_read));
  931. auto n = static_cast<size_t>(f.gcount());
  932. if (n == 0) { break; }
  933. if (!sink.write(buf, n)) { return false; }
  934. length -= n;
  935. }
  936. return true;
  937. };
  938. return {size, std::move(provider)};
  939. }
  940. using ContentReceiverWithProgress = std::function<bool(
  941. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  942. using ContentReceiver =
  943. std::function<bool(const char *data, size_t data_length)>;
  944. using FormDataHeader = std::function<bool(const FormData &file)>;
  945. class ContentReader {
  946. public:
  947. using Reader = std::function<bool(ContentReceiver receiver)>;
  948. using FormDataReader =
  949. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  950. ContentReader(Reader reader, FormDataReader multipart_reader)
  951. : reader_(std::move(reader)),
  952. formdata_reader_(std::move(multipart_reader)) {}
  953. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  954. return formdata_reader_(std::move(header), std::move(receiver));
  955. }
  956. bool operator()(ContentReceiver receiver) const {
  957. return reader_(std::move(receiver));
  958. }
  959. Reader reader_;
  960. FormDataReader formdata_reader_;
  961. };
  962. using Range = std::pair<ssize_t, ssize_t>;
  963. using Ranges = std::vector<Range>;
  964. #ifdef CPPHTTPLIB_SSL_ENABLED
  965. // TLS abstraction layer - public type definitions and API
  966. namespace tls {
  967. // Opaque handles (defined as void* for abstraction)
  968. using ctx_t = void *;
  969. using session_t = void *;
  970. using const_session_t = const void *; // For read-only session access
  971. using cert_t = void *;
  972. using ca_store_t = void *;
  973. // TLS versions
  974. enum class Version {
  975. TLS1_2 = 0x0303,
  976. TLS1_3 = 0x0304,
  977. };
  978. // Subject Alternative Names (SAN) entry types
  979. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  980. // SAN entry structure
  981. struct SanEntry {
  982. SanType type;
  983. std::string value;
  984. };
  985. // Verification context for certificate verification callback
  986. struct VerifyContext {
  987. session_t session; // TLS session handle
  988. cert_t cert; // Current certificate being verified
  989. int depth; // Certificate chain depth (0 = leaf)
  990. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  991. long error_code; // Backend-specific error code (0 = no error)
  992. const char *error_string; // Human-readable error description
  993. // Certificate introspection methods
  994. std::string subject_cn() const;
  995. std::string issuer_name() const;
  996. bool check_hostname(const char *hostname) const;
  997. std::vector<SanEntry> sans() const;
  998. bool validity(time_t &not_before, time_t &not_after) const;
  999. std::string serial() const;
  1000. };
  1001. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1002. // TlsError codes for TLS operations (backend-independent)
  1003. enum class ErrorCode : int {
  1004. Success = 0,
  1005. WantRead, // Non-blocking: need to wait for read
  1006. WantWrite, // Non-blocking: need to wait for write
  1007. PeerClosed, // Peer closed the connection
  1008. Fatal, // Unrecoverable error
  1009. SyscallError, // System call error (check sys_errno)
  1010. CertVerifyFailed, // Certificate verification failed
  1011. HostnameMismatch, // Hostname verification failed
  1012. };
  1013. // TLS error information
  1014. struct TlsError {
  1015. ErrorCode code = ErrorCode::Fatal;
  1016. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1017. int sys_errno = 0; // errno when SyscallError
  1018. // Convert verification error code to human-readable string
  1019. static std::string verify_error_to_string(long error_code);
  1020. };
  1021. // RAII wrapper for peer certificate
  1022. class PeerCert {
  1023. public:
  1024. PeerCert();
  1025. PeerCert(PeerCert &&other) noexcept;
  1026. PeerCert &operator=(PeerCert &&other) noexcept;
  1027. ~PeerCert();
  1028. PeerCert(const PeerCert &) = delete;
  1029. PeerCert &operator=(const PeerCert &) = delete;
  1030. explicit operator bool() const;
  1031. std::string subject_cn() const;
  1032. std::string issuer_name() const;
  1033. bool check_hostname(const char *hostname) const;
  1034. std::vector<SanEntry> sans() const;
  1035. bool validity(time_t &not_before, time_t &not_after) const;
  1036. std::string serial() const;
  1037. private:
  1038. explicit PeerCert(cert_t cert);
  1039. cert_t cert_ = nullptr;
  1040. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1041. };
  1042. // Callback for TLS context setup (used by SSLServer constructor)
  1043. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1044. } // namespace tls
  1045. #endif
  1046. struct Request {
  1047. std::string method;
  1048. std::string path;
  1049. std::string matched_route;
  1050. Params params;
  1051. Headers headers;
  1052. Headers trailers;
  1053. std::string body;
  1054. std::string remote_addr;
  1055. int remote_port = -1;
  1056. std::string local_addr;
  1057. int local_port = -1;
  1058. // for server
  1059. std::string version;
  1060. std::string target;
  1061. MultipartFormData form;
  1062. Ranges ranges;
  1063. Match matches;
  1064. std::unordered_map<std::string, std::string> path_params;
  1065. std::function<bool()> is_connection_closed = []() { return true; };
  1066. // for client
  1067. std::vector<std::string> accept_content_types;
  1068. ResponseHandler response_handler;
  1069. ContentReceiverWithProgress content_receiver;
  1070. DownloadProgress download_progress;
  1071. UploadProgress upload_progress;
  1072. bool has_header(const std::string &key) const;
  1073. std::string get_header_value(const std::string &key, const char *def = "",
  1074. size_t id = 0) const;
  1075. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1076. size_t id = 0) const;
  1077. size_t get_header_value_count(const std::string &key) const;
  1078. void set_header(const std::string &key, const std::string &val);
  1079. bool has_trailer(const std::string &key) const;
  1080. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1081. size_t get_trailer_value_count(const std::string &key) const;
  1082. bool has_param(const std::string &key) const;
  1083. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1084. std::vector<std::string> get_param_values(const std::string &key) const;
  1085. size_t get_param_value_count(const std::string &key) const;
  1086. bool is_multipart_form_data() const;
  1087. // private members...
  1088. bool body_consumed_ = false;
  1089. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1090. size_t content_length_ = 0;
  1091. ContentProvider content_provider_;
  1092. bool is_chunked_content_provider_ = false;
  1093. size_t authorization_count_ = 0;
  1094. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1095. (std::chrono::steady_clock::time_point::min)();
  1096. #ifdef CPPHTTPLIB_SSL_ENABLED
  1097. tls::const_session_t ssl = nullptr;
  1098. tls::PeerCert peer_cert() const;
  1099. std::string sni() const;
  1100. #endif
  1101. };
  1102. struct Response {
  1103. std::string version;
  1104. int status = -1;
  1105. std::string reason;
  1106. Headers headers;
  1107. Headers trailers;
  1108. std::string body;
  1109. std::string location; // Redirect location
  1110. // User-defined context — set by pre-routing/pre-request handlers and read
  1111. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1112. UserData user_data;
  1113. bool has_header(const std::string &key) const;
  1114. std::string get_header_value(const std::string &key, const char *def = "",
  1115. size_t id = 0) const;
  1116. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1117. size_t id = 0) const;
  1118. size_t get_header_value_count(const std::string &key) const;
  1119. void set_header(const std::string &key, const std::string &val);
  1120. bool has_trailer(const std::string &key) const;
  1121. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1122. size_t get_trailer_value_count(const std::string &key) const;
  1123. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1124. void set_content(const char *s, size_t n, const std::string &content_type);
  1125. void set_content(const std::string &s, const std::string &content_type);
  1126. void set_content(std::string &&s, const std::string &content_type);
  1127. void set_content_provider(
  1128. size_t length, const std::string &content_type, ContentProvider provider,
  1129. ContentProviderResourceReleaser resource_releaser = nullptr);
  1130. void set_content_provider(
  1131. const std::string &content_type, ContentProviderWithoutLength provider,
  1132. ContentProviderResourceReleaser resource_releaser = nullptr);
  1133. void set_chunked_content_provider(
  1134. const std::string &content_type, ContentProviderWithoutLength provider,
  1135. ContentProviderResourceReleaser resource_releaser = nullptr);
  1136. void set_file_content(const std::string &path,
  1137. const std::string &content_type);
  1138. void set_file_content(const std::string &path);
  1139. Response() = default;
  1140. Response(const Response &) = default;
  1141. Response &operator=(const Response &) = default;
  1142. Response(Response &&) = default;
  1143. Response &operator=(Response &&) = default;
  1144. ~Response() {
  1145. if (content_provider_resource_releaser_) {
  1146. content_provider_resource_releaser_(content_provider_success_);
  1147. }
  1148. }
  1149. // private members...
  1150. size_t content_length_ = 0;
  1151. ContentProvider content_provider_;
  1152. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1153. bool is_chunked_content_provider_ = false;
  1154. bool content_provider_success_ = false;
  1155. std::string file_content_path_;
  1156. std::string file_content_content_type_;
  1157. };
  1158. enum class Error {
  1159. Success = 0,
  1160. Unknown,
  1161. Connection,
  1162. BindIPAddress,
  1163. Read,
  1164. Write,
  1165. ExceedRedirectCount,
  1166. Canceled,
  1167. SSLConnection,
  1168. SSLLoadingCerts,
  1169. SSLServerVerification,
  1170. SSLServerHostnameVerification,
  1171. UnsupportedMultipartBoundaryChars,
  1172. Compression,
  1173. ConnectionTimeout,
  1174. ProxyConnection,
  1175. ConnectionClosed,
  1176. Timeout,
  1177. ResourceExhaustion,
  1178. TooManyFormDataFiles,
  1179. ExceedMaxPayloadSize,
  1180. ExceedUriMaxLength,
  1181. ExceedMaxSocketDescriptorCount,
  1182. InvalidRequestLine,
  1183. InvalidHTTPMethod,
  1184. InvalidHTTPVersion,
  1185. InvalidHeaders,
  1186. MultipartParsing,
  1187. OpenFile,
  1188. Listen,
  1189. GetSockName,
  1190. UnsupportedAddressFamily,
  1191. HTTPParsing,
  1192. InvalidRangeHeader,
  1193. // For internal use only
  1194. SSLPeerCouldBeClosed_,
  1195. };
  1196. std::string to_string(Error error);
  1197. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1198. class Stream {
  1199. public:
  1200. virtual ~Stream() = default;
  1201. virtual bool is_readable() const = 0;
  1202. virtual bool wait_readable() const = 0;
  1203. virtual bool wait_writable() const = 0;
  1204. virtual bool is_peer_alive() const { return wait_writable(); }
  1205. virtual ssize_t read(char *ptr, size_t size) = 0;
  1206. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1207. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1208. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1209. virtual socket_t socket() const = 0;
  1210. virtual time_t duration() const = 0;
  1211. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1212. (void)sec;
  1213. (void)usec;
  1214. }
  1215. ssize_t write(const char *ptr);
  1216. ssize_t write(const std::string &s);
  1217. Error get_error() const { return error_; }
  1218. protected:
  1219. Error error_ = Error::Success;
  1220. };
  1221. class TaskQueue {
  1222. public:
  1223. TaskQueue() = default;
  1224. virtual ~TaskQueue() = default;
  1225. virtual bool enqueue(std::function<void()> fn) = 0;
  1226. virtual void shutdown() = 0;
  1227. virtual void on_idle() {}
  1228. };
  1229. class ThreadPool final : public TaskQueue {
  1230. public:
  1231. explicit ThreadPool(size_t n, size_t max_n = 0, size_t mqr = 0);
  1232. ThreadPool(const ThreadPool &) = delete;
  1233. ~ThreadPool() override = default;
  1234. bool enqueue(std::function<void()> fn) override;
  1235. void shutdown() override;
  1236. private:
  1237. void worker(bool is_dynamic);
  1238. void move_to_finished(std::thread::id id);
  1239. void cleanup_finished_threads();
  1240. size_t base_thread_count_;
  1241. size_t max_thread_count_;
  1242. size_t max_queued_requests_;
  1243. size_t idle_thread_count_;
  1244. bool shutdown_;
  1245. std::list<std::function<void()>> jobs_;
  1246. std::vector<std::thread> threads_; // base threads
  1247. std::list<std::thread> dynamic_threads_; // dynamic threads
  1248. std::vector<std::thread>
  1249. finished_threads_; // exited dynamic threads awaiting join
  1250. std::condition_variable cond_;
  1251. std::mutex mutex_;
  1252. };
  1253. using Logger = std::function<void(const Request &, const Response &)>;
  1254. // Forward declaration for Error type
  1255. enum class Error;
  1256. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1257. using SocketOptions = std::function<void(socket_t sock)>;
  1258. void default_socket_options(socket_t sock);
  1259. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1260. const char *status_message(int status);
  1261. std::string to_string(Error error);
  1262. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1263. std::string get_bearer_token_auth(const Request &req);
  1264. namespace detail {
  1265. class MatcherBase {
  1266. public:
  1267. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1268. virtual ~MatcherBase() = default;
  1269. const std::string &pattern() const { return pattern_; }
  1270. // Match request path and populate its matches and
  1271. virtual bool match(Request &request) const = 0;
  1272. private:
  1273. std::string pattern_;
  1274. };
  1275. /**
  1276. * Captures parameters in request path and stores them in Request::path_params
  1277. *
  1278. * Capture name is a substring of a pattern from : to /.
  1279. * The rest of the pattern is matched against the request path directly
  1280. * Parameters are captured starting from the next character after
  1281. * the end of the last matched static pattern fragment until the next /.
  1282. *
  1283. * Example pattern:
  1284. * "/path/fragments/:capture/more/fragments/:second_capture"
  1285. * Static fragments:
  1286. * "/path/fragments/", "more/fragments/"
  1287. *
  1288. * Given the following request path:
  1289. * "/path/fragments/:1/more/fragments/:2"
  1290. * the resulting capture will be
  1291. * {{"capture", "1"}, {"second_capture", "2"}}
  1292. */
  1293. class PathParamsMatcher final : public MatcherBase {
  1294. public:
  1295. PathParamsMatcher(const std::string &pattern);
  1296. bool match(Request &request) const override;
  1297. private:
  1298. // Treat segment separators as the end of path parameter capture
  1299. // Does not need to handle query parameters as they are parsed before path
  1300. // matching
  1301. static constexpr char separator = '/';
  1302. // Contains static path fragments to match against, excluding the '/' after
  1303. // path params
  1304. // Fragments are separated by path params
  1305. std::vector<std::string> static_fragments_;
  1306. // Stores the names of the path parameters to be used as keys in the
  1307. // Request::path_params map
  1308. std::vector<std::string> param_names_;
  1309. };
  1310. /**
  1311. * Performs std::regex_match on request path
  1312. * and stores the result in Request::matches
  1313. *
  1314. * Note that regex match is performed directly on the whole request.
  1315. * This means that wildcard patterns may match multiple path segments with /:
  1316. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1317. */
  1318. class RegexMatcher final : public MatcherBase {
  1319. public:
  1320. RegexMatcher(const std::string &pattern)
  1321. : MatcherBase(pattern), regex_(pattern) {}
  1322. bool match(Request &request) const override;
  1323. private:
  1324. std::regex regex_;
  1325. };
  1326. int close_socket(socket_t sock);
  1327. ssize_t write_headers(Stream &strm, const Headers &headers);
  1328. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1329. time_t usec);
  1330. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1331. const std::string &boundary);
  1332. ContentProvider
  1333. make_multipart_content_provider(const UploadFormDataItems &items,
  1334. const std::string &boundary);
  1335. } // namespace detail
  1336. class Server {
  1337. public:
  1338. using Handler = std::function<void(const Request &, Response &)>;
  1339. using ExceptionHandler =
  1340. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1341. enum class HandlerResponse {
  1342. Handled,
  1343. Unhandled,
  1344. };
  1345. using HandlerWithResponse =
  1346. std::function<HandlerResponse(const Request &, Response &)>;
  1347. using HandlerWithContentReader = std::function<void(
  1348. const Request &, Response &, const ContentReader &content_reader)>;
  1349. using Expect100ContinueHandler =
  1350. std::function<int(const Request &, Response &)>;
  1351. using WebSocketHandler =
  1352. std::function<void(const Request &, ws::WebSocket &)>;
  1353. using SubProtocolSelector =
  1354. std::function<std::string(const std::vector<std::string> &protocols)>;
  1355. Server();
  1356. virtual ~Server();
  1357. virtual bool is_valid() const;
  1358. Server &Get(const std::string &pattern, Handler handler);
  1359. Server &Post(const std::string &pattern, Handler handler);
  1360. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1361. Server &Put(const std::string &pattern, Handler handler);
  1362. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1363. Server &Patch(const std::string &pattern, Handler handler);
  1364. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1365. Server &Delete(const std::string &pattern, Handler handler);
  1366. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1367. Server &Options(const std::string &pattern, Handler handler);
  1368. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1369. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1370. SubProtocolSelector sub_protocol_selector);
  1371. bool set_base_dir(const std::string &dir,
  1372. const std::string &mount_point = std::string());
  1373. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1374. Headers headers = Headers());
  1375. bool remove_mount_point(const std::string &mount_point);
  1376. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1377. const std::string &mime);
  1378. Server &set_default_file_mimetype(const std::string &mime);
  1379. Server &set_file_request_handler(Handler handler);
  1380. template <class ErrorHandlerFunc>
  1381. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1382. return set_error_handler_core(
  1383. std::forward<ErrorHandlerFunc>(handler),
  1384. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1385. }
  1386. Server &set_exception_handler(ExceptionHandler handler);
  1387. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1388. Server &set_post_routing_handler(Handler handler);
  1389. Server &set_pre_request_handler(HandlerWithResponse handler);
  1390. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1391. Server &set_logger(Logger logger);
  1392. Server &set_pre_compression_logger(Logger logger);
  1393. Server &set_error_logger(ErrorLogger error_logger);
  1394. Server &set_address_family(int family);
  1395. Server &set_tcp_nodelay(bool on);
  1396. Server &set_ipv6_v6only(bool on);
  1397. Server &set_socket_options(SocketOptions socket_options);
  1398. Server &set_default_headers(Headers headers);
  1399. Server &
  1400. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1401. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1402. Server &set_keep_alive_max_count(size_t count);
  1403. Server &set_keep_alive_timeout(time_t sec);
  1404. template <class Rep, class Period>
  1405. Server &
  1406. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1407. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1408. template <class Rep, class Period>
  1409. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1410. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1411. template <class Rep, class Period>
  1412. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1413. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1414. template <class Rep, class Period>
  1415. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1416. Server &set_payload_max_length(size_t length);
  1417. Server &set_websocket_ping_interval(time_t sec);
  1418. template <class Rep, class Period>
  1419. Server &set_websocket_ping_interval(
  1420. const std::chrono::duration<Rep, Period> &duration);
  1421. Server &set_websocket_max_missed_pongs(int count);
  1422. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1423. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1424. bool listen_after_bind();
  1425. bool listen(const std::string &host, int port, int socket_flags = 0);
  1426. bool is_running() const;
  1427. void wait_until_ready() const;
  1428. void stop();
  1429. void decommission();
  1430. std::function<TaskQueue *(void)> new_task_queue;
  1431. protected:
  1432. bool process_request(Stream &strm, const std::string &remote_addr,
  1433. int remote_port, const std::string &local_addr,
  1434. int local_port, bool close_connection,
  1435. bool &connection_closed,
  1436. const std::function<void(Request &)> &setup_request,
  1437. bool *websocket_upgraded = nullptr);
  1438. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1439. std::vector<std::string> trusted_proxies_;
  1440. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1441. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1442. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1443. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1444. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1445. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1446. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1447. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1448. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1449. time_t websocket_ping_interval_sec_ =
  1450. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1451. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1452. private:
  1453. using Handlers =
  1454. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1455. using HandlersForContentReader =
  1456. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1457. HandlerWithContentReader>>;
  1458. static std::unique_ptr<detail::MatcherBase>
  1459. make_matcher(const std::string &pattern);
  1460. template <typename H>
  1461. Server &add_handler(
  1462. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1463. const std::string &pattern, H handler) {
  1464. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1465. return *this;
  1466. }
  1467. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1468. Server &set_error_handler_core(Handler handler, std::false_type);
  1469. socket_t create_server_socket(const std::string &host, int port,
  1470. int socket_flags,
  1471. SocketOptions socket_options) const;
  1472. int bind_internal(const std::string &host, int port, int socket_flags);
  1473. bool listen_internal();
  1474. bool routing(Request &req, Response &res, Stream &strm);
  1475. bool handle_file_request(Request &req, Response &res);
  1476. bool check_if_not_modified(const Request &req, Response &res,
  1477. const std::string &etag, time_t mtime) const;
  1478. bool check_if_range(Request &req, const std::string &etag,
  1479. time_t mtime) const;
  1480. bool dispatch_request(Request &req, Response &res,
  1481. const Handlers &handlers) const;
  1482. bool dispatch_request_for_content_reader(
  1483. Request &req, Response &res, ContentReader content_reader,
  1484. const HandlersForContentReader &handlers) const;
  1485. bool parse_request_line(const char *s, Request &req) const;
  1486. void apply_ranges(const Request &req, Response &res,
  1487. std::string &content_type, std::string &boundary) const;
  1488. bool write_response(Stream &strm, bool close_connection, Request &req,
  1489. Response &res);
  1490. bool write_response_with_content(Stream &strm, bool close_connection,
  1491. const Request &req, Response &res);
  1492. bool write_response_core(Stream &strm, bool close_connection,
  1493. const Request &req, Response &res,
  1494. bool need_apply_ranges);
  1495. bool write_content_with_provider(Stream &strm, const Request &req,
  1496. Response &res, const std::string &boundary,
  1497. const std::string &content_type);
  1498. bool read_content(Stream &strm, Request &req, Response &res);
  1499. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1500. Response &res,
  1501. ContentReceiver receiver,
  1502. FormDataHeader multipart_header,
  1503. ContentReceiver multipart_receiver);
  1504. bool read_content_core(Stream &strm, Request &req, Response &res,
  1505. ContentReceiver receiver,
  1506. FormDataHeader multipart_header,
  1507. ContentReceiver multipart_receiver) const;
  1508. virtual bool process_and_close_socket(socket_t sock);
  1509. void output_log(const Request &req, const Response &res) const;
  1510. void output_pre_compression_log(const Request &req,
  1511. const Response &res) const;
  1512. void output_error_log(const Error &err, const Request *req) const;
  1513. std::atomic<bool> is_running_{false};
  1514. std::atomic<bool> is_decommissioned{false};
  1515. struct MountPointEntry {
  1516. std::string mount_point;
  1517. std::string base_dir;
  1518. std::string resolved_base_dir;
  1519. Headers headers;
  1520. };
  1521. std::vector<MountPointEntry> base_dirs_;
  1522. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1523. std::string default_file_mimetype_ = "application/octet-stream";
  1524. Handler file_request_handler_;
  1525. Handlers get_handlers_;
  1526. Handlers post_handlers_;
  1527. HandlersForContentReader post_handlers_for_content_reader_;
  1528. Handlers put_handlers_;
  1529. HandlersForContentReader put_handlers_for_content_reader_;
  1530. Handlers patch_handlers_;
  1531. HandlersForContentReader patch_handlers_for_content_reader_;
  1532. Handlers delete_handlers_;
  1533. HandlersForContentReader delete_handlers_for_content_reader_;
  1534. Handlers options_handlers_;
  1535. struct WebSocketHandlerEntry {
  1536. std::unique_ptr<detail::MatcherBase> matcher;
  1537. WebSocketHandler handler;
  1538. SubProtocolSelector sub_protocol_selector;
  1539. };
  1540. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1541. WebSocketHandlers websocket_handlers_;
  1542. HandlerWithResponse error_handler_;
  1543. ExceptionHandler exception_handler_;
  1544. HandlerWithResponse pre_routing_handler_;
  1545. Handler post_routing_handler_;
  1546. HandlerWithResponse pre_request_handler_;
  1547. Expect100ContinueHandler expect_100_continue_handler_;
  1548. mutable std::mutex logger_mutex_;
  1549. Logger logger_;
  1550. Logger pre_compression_logger_;
  1551. ErrorLogger error_logger_;
  1552. int address_family_ = AF_UNSPEC;
  1553. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1554. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1555. SocketOptions socket_options_ = default_socket_options;
  1556. Headers default_headers_;
  1557. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1558. detail::write_headers;
  1559. };
  1560. class Result {
  1561. public:
  1562. Result() = default;
  1563. Result(std::unique_ptr<Response> &&res, Error err,
  1564. Headers &&request_headers = Headers{})
  1565. : res_(std::move(res)), err_(err),
  1566. request_headers_(std::move(request_headers)) {}
  1567. // Response
  1568. operator bool() const { return res_ != nullptr; }
  1569. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1570. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1571. const Response &value() const { return *res_; }
  1572. Response &value() { return *res_; }
  1573. const Response &operator*() const { return *res_; }
  1574. Response &operator*() { return *res_; }
  1575. const Response *operator->() const { return res_.get(); }
  1576. Response *operator->() { return res_.get(); }
  1577. // Error
  1578. Error error() const { return err_; }
  1579. // Request Headers
  1580. bool has_request_header(const std::string &key) const;
  1581. std::string get_request_header_value(const std::string &key,
  1582. const char *def = "",
  1583. size_t id = 0) const;
  1584. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1585. size_t id = 0) const;
  1586. size_t get_request_header_value_count(const std::string &key) const;
  1587. private:
  1588. std::unique_ptr<Response> res_;
  1589. Error err_ = Error::Unknown;
  1590. Headers request_headers_;
  1591. #ifdef CPPHTTPLIB_SSL_ENABLED
  1592. public:
  1593. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1594. int ssl_error)
  1595. : res_(std::move(res)), err_(err),
  1596. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1597. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1598. int ssl_error, uint64_t ssl_backend_error)
  1599. : res_(std::move(res)), err_(err),
  1600. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1601. ssl_backend_error_(ssl_backend_error) {}
  1602. int ssl_error() const { return ssl_error_; }
  1603. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1604. private:
  1605. int ssl_error_ = 0;
  1606. uint64_t ssl_backend_error_ = 0;
  1607. #endif
  1608. };
  1609. struct ClientConnection {
  1610. socket_t sock = INVALID_SOCKET;
  1611. bool is_open() const { return sock != INVALID_SOCKET; }
  1612. ClientConnection() = default;
  1613. ~ClientConnection();
  1614. ClientConnection(const ClientConnection &) = delete;
  1615. ClientConnection &operator=(const ClientConnection &) = delete;
  1616. ClientConnection(ClientConnection &&other) noexcept
  1617. : sock(other.sock)
  1618. #ifdef CPPHTTPLIB_SSL_ENABLED
  1619. ,
  1620. session(other.session)
  1621. #endif
  1622. {
  1623. other.sock = INVALID_SOCKET;
  1624. #ifdef CPPHTTPLIB_SSL_ENABLED
  1625. other.session = nullptr;
  1626. #endif
  1627. }
  1628. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1629. if (this != &other) {
  1630. sock = other.sock;
  1631. other.sock = INVALID_SOCKET;
  1632. #ifdef CPPHTTPLIB_SSL_ENABLED
  1633. session = other.session;
  1634. other.session = nullptr;
  1635. #endif
  1636. }
  1637. return *this;
  1638. }
  1639. #ifdef CPPHTTPLIB_SSL_ENABLED
  1640. tls::session_t session = nullptr;
  1641. #endif
  1642. };
  1643. namespace detail {
  1644. struct ChunkedDecoder;
  1645. struct BodyReader {
  1646. Stream *stream = nullptr;
  1647. bool has_content_length = false;
  1648. size_t content_length = 0;
  1649. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1650. size_t bytes_read = 0;
  1651. bool chunked = false;
  1652. bool eof = false;
  1653. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1654. Error last_error = Error::Success;
  1655. ssize_t read(char *buf, size_t len);
  1656. bool has_error() const { return last_error != Error::Success; }
  1657. };
  1658. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1659. size_t len) {
  1660. (void)stream;
  1661. return br.read(buf, len);
  1662. }
  1663. class decompressor;
  1664. } // namespace detail
  1665. class ClientImpl {
  1666. public:
  1667. explicit ClientImpl(const std::string &host);
  1668. explicit ClientImpl(const std::string &host, int port);
  1669. explicit ClientImpl(const std::string &host, int port,
  1670. const std::string &client_cert_path,
  1671. const std::string &client_key_path);
  1672. virtual ~ClientImpl();
  1673. virtual bool is_valid() const;
  1674. struct StreamHandle {
  1675. std::unique_ptr<Response> response;
  1676. Error error = Error::Success;
  1677. StreamHandle() = default;
  1678. StreamHandle(const StreamHandle &) = delete;
  1679. StreamHandle &operator=(const StreamHandle &) = delete;
  1680. StreamHandle(StreamHandle &&) = default;
  1681. StreamHandle &operator=(StreamHandle &&) = default;
  1682. ~StreamHandle() = default;
  1683. bool is_valid() const {
  1684. return response != nullptr && error == Error::Success;
  1685. }
  1686. ssize_t read(char *buf, size_t len);
  1687. void parse_trailers_if_needed();
  1688. Error get_read_error() const { return body_reader_.last_error; }
  1689. bool has_read_error() const { return body_reader_.has_error(); }
  1690. bool trailers_parsed_ = false;
  1691. private:
  1692. friend class ClientImpl;
  1693. ssize_t read_with_decompression(char *buf, size_t len);
  1694. std::unique_ptr<ClientConnection> connection_;
  1695. std::unique_ptr<Stream> socket_stream_;
  1696. Stream *stream_ = nullptr;
  1697. detail::BodyReader body_reader_;
  1698. std::unique_ptr<detail::decompressor> decompressor_;
  1699. std::string decompress_buffer_;
  1700. size_t decompress_offset_ = 0;
  1701. size_t decompressed_bytes_read_ = 0;
  1702. };
  1703. // clang-format off
  1704. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1705. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1706. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1707. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1708. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1709. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1710. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1711. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1712. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1713. Result Head(const std::string &path);
  1714. Result Head(const std::string &path, const Headers &headers);
  1715. Result Post(const std::string &path);
  1716. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1717. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1718. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1719. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1720. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1721. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1722. Result Post(const std::string &path, const Params &params);
  1723. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1724. Result Post(const std::string &path, const Headers &headers);
  1725. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1726. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1727. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1728. 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);
  1729. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1730. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1731. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1732. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1733. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1734. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1735. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1736. Result Put(const std::string &path);
  1737. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1738. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1739. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1740. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1741. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1742. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1743. Result Put(const std::string &path, const Params &params);
  1744. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1745. Result Put(const std::string &path, const Headers &headers);
  1746. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1747. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1748. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1749. 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);
  1750. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1751. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1752. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1753. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1754. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1755. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1756. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1757. Result Patch(const std::string &path);
  1758. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1759. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1760. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1761. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1762. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1763. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1764. Result Patch(const std::string &path, const Params &params);
  1765. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1766. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1767. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1768. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1769. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1770. 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);
  1771. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1772. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1773. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1774. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1775. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1776. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1777. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1778. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1779. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1780. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1781. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1782. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1783. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1784. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1785. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1786. Result Options(const std::string &path);
  1787. Result Options(const std::string &path, const Headers &headers);
  1788. // clang-format on
  1789. // Streaming API: Open a stream for reading response body incrementally
  1790. // Socket ownership is transferred to StreamHandle for true streaming
  1791. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1792. StreamHandle open_stream(const std::string &method, const std::string &path,
  1793. const Params &params = {},
  1794. const Headers &headers = {},
  1795. const std::string &body = {},
  1796. const std::string &content_type = {});
  1797. bool send(Request &req, Response &res, Error &error);
  1798. Result send(const Request &req);
  1799. void stop();
  1800. std::string host() const;
  1801. int port() const;
  1802. size_t is_socket_open() const;
  1803. socket_t socket() const;
  1804. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1805. void set_default_headers(Headers headers);
  1806. void
  1807. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1808. void set_address_family(int family);
  1809. void set_tcp_nodelay(bool on);
  1810. void set_ipv6_v6only(bool on);
  1811. void set_socket_options(SocketOptions socket_options);
  1812. void set_connection_timeout(time_t sec, time_t usec = 0);
  1813. template <class Rep, class Period>
  1814. void
  1815. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1816. void set_read_timeout(time_t sec, time_t usec = 0);
  1817. template <class Rep, class Period>
  1818. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1819. void set_write_timeout(time_t sec, time_t usec = 0);
  1820. template <class Rep, class Period>
  1821. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1822. void set_max_timeout(time_t msec);
  1823. template <class Rep, class Period>
  1824. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1825. void set_basic_auth(const std::string &username, const std::string &password);
  1826. void set_bearer_token_auth(const std::string &token);
  1827. void set_keep_alive(bool on);
  1828. void set_follow_location(bool on);
  1829. void set_path_encode(bool on);
  1830. void set_compress(bool on);
  1831. void set_decompress(bool on);
  1832. void set_payload_max_length(size_t length);
  1833. void set_interface(const std::string &intf);
  1834. void set_proxy(const std::string &host, int port);
  1835. void set_proxy_basic_auth(const std::string &username,
  1836. const std::string &password);
  1837. void set_proxy_bearer_token_auth(const std::string &token);
  1838. void set_logger(Logger logger);
  1839. void set_error_logger(ErrorLogger error_logger);
  1840. protected:
  1841. struct Socket {
  1842. socket_t sock = INVALID_SOCKET;
  1843. // For Mbed TLS compatibility: start_time for request timeout tracking
  1844. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1845. bool is_open() const { return sock != INVALID_SOCKET; }
  1846. #ifdef CPPHTTPLIB_SSL_ENABLED
  1847. tls::session_t ssl = nullptr;
  1848. #endif
  1849. };
  1850. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1851. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1852. virtual bool setup_proxy_connection(
  1853. Socket &socket,
  1854. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1855. Response &res, bool &success, Error &error);
  1856. // All of:
  1857. // shutdown_ssl
  1858. // shutdown_socket
  1859. // close_socket
  1860. // should ONLY be called when socket_mutex_ is locked.
  1861. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1862. // with a DIFFERENT thread sending requests using that socket.
  1863. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1864. void shutdown_socket(Socket &socket) const;
  1865. void close_socket(Socket &socket);
  1866. bool process_request(Stream &strm, Request &req, Response &res,
  1867. bool close_connection, Error &error);
  1868. bool write_content_with_provider(Stream &strm, const Request &req,
  1869. Error &error) const;
  1870. void copy_settings(const ClientImpl &rhs);
  1871. void output_log(const Request &req, const Response &res) const;
  1872. void output_error_log(const Error &err, const Request *req) const;
  1873. // Socket endpoint information
  1874. const std::string host_;
  1875. const int port_;
  1876. // Current open socket
  1877. Socket socket_;
  1878. mutable std::mutex socket_mutex_;
  1879. std::recursive_mutex request_mutex_;
  1880. // These are all protected under socket_mutex
  1881. size_t socket_requests_in_flight_ = 0;
  1882. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1883. bool socket_should_be_closed_when_request_is_done_ = false;
  1884. // Hostname-IP map
  1885. std::map<std::string, std::string> addr_map_;
  1886. // Default headers
  1887. Headers default_headers_;
  1888. // Header writer
  1889. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1890. detail::write_headers;
  1891. // Settings
  1892. std::string client_cert_path_;
  1893. std::string client_key_path_;
  1894. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1895. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1896. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1897. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1898. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1899. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1900. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1901. std::string basic_auth_username_;
  1902. std::string basic_auth_password_;
  1903. std::string bearer_token_auth_token_;
  1904. bool keep_alive_ = false;
  1905. bool follow_location_ = false;
  1906. bool path_encode_ = true;
  1907. int address_family_ = AF_UNSPEC;
  1908. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1909. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1910. SocketOptions socket_options_ = nullptr;
  1911. bool compress_ = false;
  1912. bool decompress_ = true;
  1913. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1914. bool has_payload_max_length_ = false;
  1915. std::string interface_;
  1916. std::string proxy_host_;
  1917. int proxy_port_ = -1;
  1918. std::string proxy_basic_auth_username_;
  1919. std::string proxy_basic_auth_password_;
  1920. std::string proxy_bearer_token_auth_token_;
  1921. mutable std::mutex logger_mutex_;
  1922. Logger logger_;
  1923. ErrorLogger error_logger_;
  1924. private:
  1925. bool send_(Request &req, Response &res, Error &error);
  1926. Result send_(Request &&req);
  1927. socket_t create_client_socket(Error &error) const;
  1928. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1929. bool skip_100_continue = true) const;
  1930. bool write_request(Stream &strm, Request &req, bool close_connection,
  1931. Error &error, bool skip_body = false);
  1932. bool write_request_body(Stream &strm, Request &req, Error &error);
  1933. void prepare_default_headers(Request &r, bool for_stream,
  1934. const std::string &ct);
  1935. bool redirect(Request &req, Response &res, Error &error);
  1936. bool create_redirect_client(const std::string &scheme,
  1937. const std::string &host, int port, Request &req,
  1938. Response &res, const std::string &path,
  1939. const std::string &location, Error &error);
  1940. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1941. bool handle_request(Stream &strm, Request &req, Response &res,
  1942. bool close_connection, Error &error);
  1943. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1944. Request &req, const char *body, size_t content_length,
  1945. ContentProvider content_provider,
  1946. ContentProviderWithoutLength content_provider_without_length,
  1947. const std::string &content_type, ContentReceiver content_receiver,
  1948. Error &error);
  1949. Result send_with_content_provider_and_receiver(
  1950. const std::string &method, const std::string &path,
  1951. const Headers &headers, const char *body, size_t content_length,
  1952. ContentProvider content_provider,
  1953. ContentProviderWithoutLength content_provider_without_length,
  1954. const std::string &content_type, ContentReceiver content_receiver,
  1955. UploadProgress progress);
  1956. ContentProviderWithoutLength get_multipart_content_provider(
  1957. const std::string &boundary, const UploadFormDataItems &items,
  1958. const FormDataProviderItems &provider_items) const;
  1959. virtual bool
  1960. process_socket(const Socket &socket,
  1961. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1962. std::function<bool(Stream &strm)> callback);
  1963. virtual bool is_ssl() const;
  1964. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1965. #ifdef CPPHTTPLIB_SSL_ENABLED
  1966. public:
  1967. void set_digest_auth(const std::string &username,
  1968. const std::string &password);
  1969. void set_proxy_digest_auth(const std::string &username,
  1970. const std::string &password);
  1971. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1972. const std::string &ca_cert_dir_path = std::string());
  1973. void enable_server_certificate_verification(bool enabled);
  1974. void enable_server_hostname_verification(bool enabled);
  1975. protected:
  1976. std::string digest_auth_username_;
  1977. std::string digest_auth_password_;
  1978. std::string proxy_digest_auth_username_;
  1979. std::string proxy_digest_auth_password_;
  1980. std::string ca_cert_file_path_;
  1981. std::string ca_cert_dir_path_;
  1982. bool server_certificate_verification_ = true;
  1983. bool server_hostname_verification_ = true;
  1984. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  1985. int last_ssl_error_ = 0;
  1986. uint64_t last_backend_error_ = 0;
  1987. #endif
  1988. };
  1989. class Client {
  1990. public:
  1991. // Universal interface
  1992. explicit Client(const std::string &scheme_host_port);
  1993. explicit Client(const std::string &scheme_host_port,
  1994. const std::string &client_cert_path,
  1995. const std::string &client_key_path);
  1996. // HTTP only interface
  1997. explicit Client(const std::string &host, int port);
  1998. explicit Client(const std::string &host, int port,
  1999. const std::string &client_cert_path,
  2000. const std::string &client_key_path);
  2001. Client(Client &&) = default;
  2002. Client &operator=(Client &&) = default;
  2003. ~Client();
  2004. bool is_valid() const;
  2005. // clang-format off
  2006. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2007. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2008. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2009. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2010. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2011. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2012. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2013. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2014. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2015. Result Head(const std::string &path);
  2016. Result Head(const std::string &path, const Headers &headers);
  2017. Result Post(const std::string &path);
  2018. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2019. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2020. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2021. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2022. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2023. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2024. Result Post(const std::string &path, const Params &params);
  2025. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2026. Result Post(const std::string &path, const Headers &headers);
  2027. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2028. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2029. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2030. 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);
  2031. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2032. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2033. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2034. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2035. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2036. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2037. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2038. Result Put(const std::string &path);
  2039. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2040. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2041. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2042. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2043. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2044. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2045. Result Put(const std::string &path, const Params &params);
  2046. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2047. Result Put(const std::string &path, const Headers &headers);
  2048. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2049. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2050. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2051. 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);
  2052. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2053. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2054. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2055. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2056. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2057. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2058. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2059. Result Patch(const std::string &path);
  2060. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2061. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2062. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2063. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2064. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2065. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2066. Result Patch(const std::string &path, const Params &params);
  2067. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2068. Result Patch(const std::string &path, const Headers &headers);
  2069. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2070. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2071. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2072. 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);
  2073. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2074. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2075. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2076. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2077. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2078. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2079. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2080. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2081. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2082. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2083. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2084. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2085. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2086. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2087. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2088. Result Options(const std::string &path);
  2089. Result Options(const std::string &path, const Headers &headers);
  2090. // clang-format on
  2091. // Streaming API: Open a stream for reading response body incrementally
  2092. // Socket ownership is transferred to StreamHandle for true streaming
  2093. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2094. ClientImpl::StreamHandle open_stream(const std::string &method,
  2095. const std::string &path,
  2096. const Params &params = {},
  2097. const Headers &headers = {},
  2098. const std::string &body = {},
  2099. const std::string &content_type = {});
  2100. bool send(Request &req, Response &res, Error &error);
  2101. Result send(const Request &req);
  2102. void stop();
  2103. std::string host() const;
  2104. int port() const;
  2105. size_t is_socket_open() const;
  2106. socket_t socket() const;
  2107. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2108. void set_default_headers(Headers headers);
  2109. void
  2110. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2111. void set_address_family(int family);
  2112. void set_tcp_nodelay(bool on);
  2113. void set_socket_options(SocketOptions socket_options);
  2114. void set_connection_timeout(time_t sec, time_t usec = 0);
  2115. template <class Rep, class Period>
  2116. void
  2117. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2118. void set_read_timeout(time_t sec, time_t usec = 0);
  2119. template <class Rep, class Period>
  2120. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2121. void set_write_timeout(time_t sec, time_t usec = 0);
  2122. template <class Rep, class Period>
  2123. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2124. void set_max_timeout(time_t msec);
  2125. template <class Rep, class Period>
  2126. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2127. void set_basic_auth(const std::string &username, const std::string &password);
  2128. void set_bearer_token_auth(const std::string &token);
  2129. void set_keep_alive(bool on);
  2130. void set_follow_location(bool on);
  2131. void set_path_encode(bool on);
  2132. void set_compress(bool on);
  2133. void set_decompress(bool on);
  2134. void set_payload_max_length(size_t length);
  2135. void set_interface(const std::string &intf);
  2136. void set_proxy(const std::string &host, int port);
  2137. void set_proxy_basic_auth(const std::string &username,
  2138. const std::string &password);
  2139. void set_proxy_bearer_token_auth(const std::string &token);
  2140. void set_logger(Logger logger);
  2141. void set_error_logger(ErrorLogger error_logger);
  2142. private:
  2143. std::unique_ptr<ClientImpl> cli_;
  2144. #ifdef CPPHTTPLIB_SSL_ENABLED
  2145. public:
  2146. void set_digest_auth(const std::string &username,
  2147. const std::string &password);
  2148. void set_proxy_digest_auth(const std::string &username,
  2149. const std::string &password);
  2150. void enable_server_certificate_verification(bool enabled);
  2151. void enable_server_hostname_verification(bool enabled);
  2152. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2153. const std::string &ca_cert_dir_path = std::string());
  2154. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2155. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2156. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2157. void set_session_verifier(
  2158. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2159. tls::ctx_t tls_context() const;
  2160. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2161. void enable_windows_certificate_verification(bool enabled);
  2162. #endif
  2163. private:
  2164. bool is_ssl_ = false;
  2165. #endif
  2166. };
  2167. #ifdef CPPHTTPLIB_SSL_ENABLED
  2168. class SSLServer : public Server {
  2169. public:
  2170. SSLServer(const char *cert_path, const char *private_key_path,
  2171. const char *client_ca_cert_file_path = nullptr,
  2172. const char *client_ca_cert_dir_path = nullptr,
  2173. const char *private_key_password = nullptr);
  2174. struct PemMemory {
  2175. const char *cert_pem;
  2176. size_t cert_pem_len;
  2177. const char *key_pem;
  2178. size_t key_pem_len;
  2179. const char *client_ca_pem;
  2180. size_t client_ca_pem_len;
  2181. const char *private_key_password;
  2182. };
  2183. explicit SSLServer(const PemMemory &pem);
  2184. // The callback receives the ctx_t handle which can be cast to the
  2185. // appropriate backend type (SSL_CTX* for OpenSSL,
  2186. // tls::impl::MbedTlsContext* for Mbed TLS)
  2187. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2188. ~SSLServer() override;
  2189. bool is_valid() const override;
  2190. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2191. const char *client_ca_pem = nullptr,
  2192. const char *password = nullptr);
  2193. tls::ctx_t tls_context() const { return ctx_; }
  2194. int ssl_last_error() const { return last_ssl_error_; }
  2195. private:
  2196. bool process_and_close_socket(socket_t sock) override;
  2197. tls::ctx_t ctx_ = nullptr;
  2198. std::mutex ctx_mutex_;
  2199. int last_ssl_error_ = 0;
  2200. };
  2201. class SSLClient final : public ClientImpl {
  2202. public:
  2203. explicit SSLClient(const std::string &host);
  2204. explicit SSLClient(const std::string &host, int port);
  2205. explicit SSLClient(const std::string &host, int port,
  2206. const std::string &client_cert_path,
  2207. const std::string &client_key_path,
  2208. const std::string &private_key_password = std::string());
  2209. struct PemMemory {
  2210. const char *cert_pem;
  2211. size_t cert_pem_len;
  2212. const char *key_pem;
  2213. size_t key_pem_len;
  2214. const char *private_key_password;
  2215. };
  2216. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2217. ~SSLClient() override;
  2218. bool is_valid() const override;
  2219. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2220. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2221. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2222. // Post-handshake session verifier (backend-independent)
  2223. void set_session_verifier(
  2224. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2225. tls::ctx_t tls_context() const { return ctx_; }
  2226. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2227. void enable_windows_certificate_verification(bool enabled);
  2228. #endif
  2229. private:
  2230. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2231. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2232. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2233. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2234. bool
  2235. process_socket(const Socket &socket,
  2236. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2237. std::function<bool(Stream &strm)> callback) override;
  2238. bool is_ssl() const override;
  2239. bool setup_proxy_connection(
  2240. Socket &socket,
  2241. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2242. Response &res, bool &success, Error &error) override;
  2243. bool connect_with_proxy(
  2244. Socket &sock,
  2245. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2246. Response &res, bool &success, Error &error);
  2247. bool initialize_ssl(Socket &socket, Error &error);
  2248. void init_ctx();
  2249. void reset_ctx_on_error();
  2250. bool load_certs();
  2251. tls::ctx_t ctx_ = nullptr;
  2252. std::mutex ctx_mutex_;
  2253. std::once_flag initialize_cert_;
  2254. long verify_result_ = 0;
  2255. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2256. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2257. bool enable_windows_cert_verification_ = true;
  2258. #endif
  2259. friend class ClientImpl;
  2260. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2261. private:
  2262. bool verify_host(X509 *server_cert) const;
  2263. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  2264. bool verify_host_with_common_name(X509 *server_cert) const;
  2265. #endif
  2266. };
  2267. #endif // CPPHTTPLIB_SSL_ENABLED
  2268. namespace detail {
  2269. template <typename T, typename U>
  2270. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2271. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2272. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2273. duration - std::chrono::seconds(sec))
  2274. .count();
  2275. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2276. }
  2277. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2278. return N - 1;
  2279. }
  2280. inline bool is_numeric(const std::string &str) {
  2281. return !str.empty() &&
  2282. std::all_of(str.cbegin(), str.cend(),
  2283. [](unsigned char c) { return std::isdigit(c); });
  2284. }
  2285. inline size_t get_header_value_u64(const Headers &headers,
  2286. const std::string &key, size_t def,
  2287. size_t id, bool &is_invalid_value) {
  2288. is_invalid_value = false;
  2289. auto rng = headers.equal_range(key);
  2290. auto it = rng.first;
  2291. std::advance(it, static_cast<ssize_t>(id));
  2292. if (it != rng.second) {
  2293. if (is_numeric(it->second)) {
  2294. return static_cast<size_t>(std::strtoull(it->second.data(), nullptr, 10));
  2295. } else {
  2296. is_invalid_value = true;
  2297. }
  2298. }
  2299. return def;
  2300. }
  2301. inline size_t get_header_value_u64(const Headers &headers,
  2302. const std::string &key, size_t def,
  2303. size_t id) {
  2304. auto dummy = false;
  2305. return get_header_value_u64(headers, key, def, id, dummy);
  2306. }
  2307. } // namespace detail
  2308. template <class Rep, class Period>
  2309. inline Server &
  2310. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2311. detail::duration_to_sec_and_usec(
  2312. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2313. return *this;
  2314. }
  2315. template <class Rep, class Period>
  2316. inline Server &
  2317. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2318. detail::duration_to_sec_and_usec(
  2319. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2320. return *this;
  2321. }
  2322. template <class Rep, class Period>
  2323. inline Server &
  2324. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2325. detail::duration_to_sec_and_usec(
  2326. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2327. return *this;
  2328. }
  2329. template <class Rep, class Period>
  2330. inline void ClientImpl::set_connection_timeout(
  2331. const std::chrono::duration<Rep, Period> &duration) {
  2332. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2333. set_connection_timeout(sec, usec);
  2334. });
  2335. }
  2336. template <class Rep, class Period>
  2337. inline void ClientImpl::set_read_timeout(
  2338. const std::chrono::duration<Rep, Period> &duration) {
  2339. detail::duration_to_sec_and_usec(
  2340. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2341. }
  2342. template <class Rep, class Period>
  2343. inline void ClientImpl::set_write_timeout(
  2344. const std::chrono::duration<Rep, Period> &duration) {
  2345. detail::duration_to_sec_and_usec(
  2346. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2347. }
  2348. template <class Rep, class Period>
  2349. inline void ClientImpl::set_max_timeout(
  2350. const std::chrono::duration<Rep, Period> &duration) {
  2351. auto msec =
  2352. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2353. set_max_timeout(msec);
  2354. }
  2355. template <class Rep, class Period>
  2356. inline void Client::set_connection_timeout(
  2357. const std::chrono::duration<Rep, Period> &duration) {
  2358. cli_->set_connection_timeout(duration);
  2359. }
  2360. template <class Rep, class Period>
  2361. inline void
  2362. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2363. cli_->set_read_timeout(duration);
  2364. }
  2365. template <class Rep, class Period>
  2366. inline void
  2367. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2368. cli_->set_write_timeout(duration);
  2369. }
  2370. inline void Client::set_max_timeout(time_t msec) {
  2371. cli_->set_max_timeout(msec);
  2372. }
  2373. template <class Rep, class Period>
  2374. inline void
  2375. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2376. cli_->set_max_timeout(duration);
  2377. }
  2378. /*
  2379. * Forward declarations and types that will be part of the .h file if split into
  2380. * .h + .cc.
  2381. */
  2382. std::string hosted_at(const std::string &hostname);
  2383. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2384. // JavaScript-style URL encoding/decoding functions
  2385. std::string encode_uri_component(const std::string &value);
  2386. std::string encode_uri(const std::string &value);
  2387. std::string decode_uri_component(const std::string &value);
  2388. std::string decode_uri(const std::string &value);
  2389. // RFC 3986 compliant URL component encoding/decoding functions
  2390. std::string encode_path_component(const std::string &component);
  2391. std::string decode_path_component(const std::string &component);
  2392. std::string encode_query_component(const std::string &component,
  2393. bool space_as_plus = true);
  2394. std::string decode_query_component(const std::string &component,
  2395. bool plus_as_space = true);
  2396. std::string sanitize_filename(const std::string &filename);
  2397. std::string append_query_params(const std::string &path, const Params &params);
  2398. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2399. std::pair<std::string, std::string>
  2400. make_basic_authentication_header(const std::string &username,
  2401. const std::string &password,
  2402. bool is_proxy = false);
  2403. namespace detail {
  2404. #if defined(_WIN32)
  2405. inline std::wstring u8string_to_wstring(const char *s) {
  2406. if (!s) { return std::wstring(); }
  2407. auto len = static_cast<int>(strlen(s));
  2408. if (!len) { return std::wstring(); }
  2409. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2410. if (!wlen) { return std::wstring(); }
  2411. std::wstring ws;
  2412. ws.resize(wlen);
  2413. wlen = ::MultiByteToWideChar(
  2414. CP_UTF8, 0, s, len,
  2415. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2416. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2417. return ws;
  2418. }
  2419. #endif
  2420. struct FileStat {
  2421. FileStat(const std::string &path);
  2422. bool is_file() const;
  2423. bool is_dir() const;
  2424. time_t mtime() const;
  2425. size_t size() const;
  2426. private:
  2427. #if defined(_WIN32)
  2428. struct _stat st_;
  2429. #else
  2430. struct stat st_;
  2431. #endif
  2432. int ret_ = -1;
  2433. };
  2434. std::string make_host_and_port_string(const std::string &host, int port,
  2435. bool is_ssl);
  2436. std::string trim_copy(const std::string &s);
  2437. void divide(
  2438. const char *data, std::size_t size, char d,
  2439. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2440. fn);
  2441. void divide(
  2442. const std::string &str, char d,
  2443. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2444. fn);
  2445. void split(const char *b, const char *e, char d,
  2446. std::function<void(const char *, const char *)> fn);
  2447. void split(const char *b, const char *e, char d, size_t m,
  2448. std::function<void(const char *, const char *)> fn);
  2449. bool process_client_socket(
  2450. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2451. time_t write_timeout_sec, time_t write_timeout_usec,
  2452. time_t max_timeout_msec,
  2453. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2454. std::function<bool(Stream &)> callback);
  2455. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2456. int port, int address_family, bool tcp_nodelay,
  2457. bool ipv6_v6only, SocketOptions socket_options,
  2458. time_t connection_timeout_sec,
  2459. time_t connection_timeout_usec,
  2460. time_t read_timeout_sec, time_t read_timeout_usec,
  2461. time_t write_timeout_sec,
  2462. time_t write_timeout_usec,
  2463. const std::string &intf, Error &error);
  2464. const char *get_header_value(const Headers &headers, const std::string &key,
  2465. const char *def, size_t id);
  2466. std::string params_to_query_str(const Params &params);
  2467. void parse_query_text(const char *data, std::size_t size, Params &params);
  2468. void parse_query_text(const std::string &s, Params &params);
  2469. bool parse_multipart_boundary(const std::string &content_type,
  2470. std::string &boundary);
  2471. bool parse_range_header(const std::string &s, Ranges &ranges);
  2472. bool parse_accept_header(const std::string &s,
  2473. std::vector<std::string> &content_types);
  2474. int close_socket(socket_t sock);
  2475. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2476. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2477. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2478. EncodingType encoding_type(const Request &req, const Response &res);
  2479. class BufferStream final : public Stream {
  2480. public:
  2481. BufferStream() = default;
  2482. ~BufferStream() override = default;
  2483. bool is_readable() const override;
  2484. bool wait_readable() const override;
  2485. bool wait_writable() const override;
  2486. ssize_t read(char *ptr, size_t size) override;
  2487. ssize_t write(const char *ptr, size_t size) override;
  2488. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2489. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2490. socket_t socket() const override;
  2491. time_t duration() const override;
  2492. const std::string &get_buffer() const;
  2493. private:
  2494. std::string buffer;
  2495. size_t position = 0;
  2496. };
  2497. class compressor {
  2498. public:
  2499. virtual ~compressor() = default;
  2500. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2501. virtual bool compress(const char *data, size_t data_length, bool last,
  2502. Callback callback) = 0;
  2503. };
  2504. class decompressor {
  2505. public:
  2506. virtual ~decompressor() = default;
  2507. virtual bool is_valid() const = 0;
  2508. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2509. virtual bool decompress(const char *data, size_t data_length,
  2510. Callback callback) = 0;
  2511. };
  2512. class nocompressor final : public compressor {
  2513. public:
  2514. ~nocompressor() override = default;
  2515. bool compress(const char *data, size_t data_length, bool /*last*/,
  2516. Callback callback) override;
  2517. };
  2518. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2519. class gzip_compressor final : public compressor {
  2520. public:
  2521. gzip_compressor();
  2522. ~gzip_compressor() override;
  2523. bool compress(const char *data, size_t data_length, bool last,
  2524. Callback callback) override;
  2525. private:
  2526. bool is_valid_ = false;
  2527. z_stream strm_;
  2528. };
  2529. class gzip_decompressor final : public decompressor {
  2530. public:
  2531. gzip_decompressor();
  2532. ~gzip_decompressor() override;
  2533. bool is_valid() const override;
  2534. bool decompress(const char *data, size_t data_length,
  2535. Callback callback) override;
  2536. private:
  2537. bool is_valid_ = false;
  2538. z_stream strm_;
  2539. };
  2540. #endif
  2541. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2542. class brotli_compressor final : public compressor {
  2543. public:
  2544. brotli_compressor();
  2545. ~brotli_compressor();
  2546. bool compress(const char *data, size_t data_length, bool last,
  2547. Callback callback) override;
  2548. private:
  2549. BrotliEncoderState *state_ = nullptr;
  2550. };
  2551. class brotli_decompressor final : public decompressor {
  2552. public:
  2553. brotli_decompressor();
  2554. ~brotli_decompressor();
  2555. bool is_valid() const override;
  2556. bool decompress(const char *data, size_t data_length,
  2557. Callback callback) override;
  2558. private:
  2559. BrotliDecoderResult decoder_r;
  2560. BrotliDecoderState *decoder_s = nullptr;
  2561. };
  2562. #endif
  2563. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2564. class zstd_compressor : public compressor {
  2565. public:
  2566. zstd_compressor();
  2567. ~zstd_compressor();
  2568. bool compress(const char *data, size_t data_length, bool last,
  2569. Callback callback) override;
  2570. private:
  2571. ZSTD_CCtx *ctx_ = nullptr;
  2572. };
  2573. class zstd_decompressor : public decompressor {
  2574. public:
  2575. zstd_decompressor();
  2576. ~zstd_decompressor();
  2577. bool is_valid() const override;
  2578. bool decompress(const char *data, size_t data_length,
  2579. Callback callback) override;
  2580. private:
  2581. ZSTD_DCtx *ctx_ = nullptr;
  2582. };
  2583. #endif
  2584. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2585. // to store data. The call can set memory on stack for performance.
  2586. class stream_line_reader {
  2587. public:
  2588. stream_line_reader(Stream &strm, char *fixed_buffer,
  2589. size_t fixed_buffer_size);
  2590. const char *ptr() const;
  2591. size_t size() const;
  2592. bool end_with_crlf() const;
  2593. bool getline();
  2594. private:
  2595. void append(char c);
  2596. Stream &strm_;
  2597. char *fixed_buffer_;
  2598. const size_t fixed_buffer_size_;
  2599. size_t fixed_buffer_used_size_ = 0;
  2600. std::string growable_buffer_;
  2601. };
  2602. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2603. const Headers &src_headers);
  2604. struct ChunkedDecoder {
  2605. Stream &strm;
  2606. size_t chunk_remaining = 0;
  2607. bool finished = false;
  2608. char line_buf[64];
  2609. size_t last_chunk_total = 0;
  2610. size_t last_chunk_offset = 0;
  2611. explicit ChunkedDecoder(Stream &s);
  2612. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2613. size_t &out_chunk_total);
  2614. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2615. };
  2616. class mmap {
  2617. public:
  2618. mmap(const char *path);
  2619. ~mmap();
  2620. bool open(const char *path);
  2621. void close();
  2622. bool is_open() const;
  2623. size_t size() const;
  2624. const char *data() const;
  2625. private:
  2626. #if defined(_WIN32)
  2627. HANDLE hFile_ = NULL;
  2628. HANDLE hMapping_ = NULL;
  2629. #else
  2630. int fd_ = -1;
  2631. #endif
  2632. size_t size_ = 0;
  2633. void *addr_ = nullptr;
  2634. bool is_open_empty_file = false;
  2635. };
  2636. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2637. namespace fields {
  2638. bool is_token_char(char c);
  2639. bool is_token(const std::string &s);
  2640. bool is_field_name(const std::string &s);
  2641. bool is_vchar(char c);
  2642. bool is_obs_text(char c);
  2643. bool is_field_vchar(char c);
  2644. bool is_field_content(const std::string &s);
  2645. bool is_field_value(const std::string &s);
  2646. } // namespace fields
  2647. } // namespace detail
  2648. /*
  2649. * TLS Abstraction Layer Declarations
  2650. */
  2651. #ifdef CPPHTTPLIB_SSL_ENABLED
  2652. // TLS abstraction layer - backend-specific type declarations
  2653. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2654. namespace tls {
  2655. namespace impl {
  2656. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2657. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2658. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2659. struct MbedTlsContext {
  2660. mbedtls_ssl_config conf;
  2661. mbedtls_entropy_context entropy;
  2662. mbedtls_ctr_drbg_context ctr_drbg;
  2663. mbedtls_x509_crt ca_chain;
  2664. mbedtls_x509_crt own_cert;
  2665. mbedtls_pk_context own_key;
  2666. bool is_server = false;
  2667. bool verify_client = false;
  2668. bool has_verify_callback = false;
  2669. MbedTlsContext();
  2670. ~MbedTlsContext();
  2671. MbedTlsContext(const MbedTlsContext &) = delete;
  2672. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2673. };
  2674. } // namespace impl
  2675. } // namespace tls
  2676. #endif
  2677. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2678. namespace tls {
  2679. namespace impl {
  2680. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2681. // This struct is accessible via tls::impl for use in SSL context
  2682. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2683. struct WolfSSLContext {
  2684. WOLFSSL_CTX *ctx = nullptr;
  2685. bool is_server = false;
  2686. bool verify_client = false;
  2687. bool has_verify_callback = false;
  2688. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2689. WolfSSLContext();
  2690. ~WolfSSLContext();
  2691. WolfSSLContext(const WolfSSLContext &) = delete;
  2692. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2693. };
  2694. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2695. struct WolfSSLCAStore {
  2696. std::string pem_data;
  2697. };
  2698. } // namespace impl
  2699. } // namespace tls
  2700. #endif
  2701. #endif // CPPHTTPLIB_SSL_ENABLED
  2702. namespace stream {
  2703. class Result {
  2704. public:
  2705. Result();
  2706. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2707. Result(Result &&other) noexcept;
  2708. Result &operator=(Result &&other) noexcept;
  2709. Result(const Result &) = delete;
  2710. Result &operator=(const Result &) = delete;
  2711. // Response info
  2712. bool is_valid() const;
  2713. explicit operator bool() const;
  2714. int status() const;
  2715. const Headers &headers() const;
  2716. std::string get_header_value(const std::string &key,
  2717. const char *def = "") const;
  2718. bool has_header(const std::string &key) const;
  2719. Error error() const;
  2720. Error read_error() const;
  2721. bool has_read_error() const;
  2722. // Stream reading
  2723. bool next();
  2724. const char *data() const;
  2725. size_t size() const;
  2726. std::string read_all();
  2727. private:
  2728. ClientImpl::StreamHandle handle_;
  2729. std::string buffer_;
  2730. size_t current_size_ = 0;
  2731. size_t chunk_size_;
  2732. bool finished_ = false;
  2733. };
  2734. // GET
  2735. template <typename ClientType>
  2736. inline Result Get(ClientType &cli, const std::string &path,
  2737. size_t chunk_size = 8192) {
  2738. return Result{cli.open_stream("GET", path), chunk_size};
  2739. }
  2740. template <typename ClientType>
  2741. inline Result Get(ClientType &cli, const std::string &path,
  2742. const Headers &headers, size_t chunk_size = 8192) {
  2743. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2744. }
  2745. template <typename ClientType>
  2746. inline Result Get(ClientType &cli, const std::string &path,
  2747. const Params &params, size_t chunk_size = 8192) {
  2748. return Result{cli.open_stream("GET", path, params), chunk_size};
  2749. }
  2750. template <typename ClientType>
  2751. inline Result Get(ClientType &cli, const std::string &path,
  2752. const Params &params, const Headers &headers,
  2753. size_t chunk_size = 8192) {
  2754. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2755. }
  2756. // POST
  2757. template <typename ClientType>
  2758. inline Result Post(ClientType &cli, const std::string &path,
  2759. const std::string &body, const std::string &content_type,
  2760. size_t chunk_size = 8192) {
  2761. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2762. chunk_size};
  2763. }
  2764. template <typename ClientType>
  2765. inline Result Post(ClientType &cli, const std::string &path,
  2766. const Headers &headers, const std::string &body,
  2767. const std::string &content_type, size_t chunk_size = 8192) {
  2768. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2769. chunk_size};
  2770. }
  2771. template <typename ClientType>
  2772. inline Result Post(ClientType &cli, const std::string &path,
  2773. const Params &params, const std::string &body,
  2774. const std::string &content_type, size_t chunk_size = 8192) {
  2775. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2776. chunk_size};
  2777. }
  2778. template <typename ClientType>
  2779. inline Result Post(ClientType &cli, const std::string &path,
  2780. const Params &params, const Headers &headers,
  2781. const std::string &body, const std::string &content_type,
  2782. size_t chunk_size = 8192) {
  2783. return Result{
  2784. cli.open_stream("POST", path, params, headers, body, content_type),
  2785. chunk_size};
  2786. }
  2787. // PUT
  2788. template <typename ClientType>
  2789. inline Result Put(ClientType &cli, const std::string &path,
  2790. const std::string &body, const std::string &content_type,
  2791. size_t chunk_size = 8192) {
  2792. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2793. chunk_size};
  2794. }
  2795. template <typename ClientType>
  2796. inline Result Put(ClientType &cli, const std::string &path,
  2797. const Headers &headers, const std::string &body,
  2798. const std::string &content_type, size_t chunk_size = 8192) {
  2799. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2800. chunk_size};
  2801. }
  2802. template <typename ClientType>
  2803. inline Result Put(ClientType &cli, const std::string &path,
  2804. const Params &params, const std::string &body,
  2805. const std::string &content_type, size_t chunk_size = 8192) {
  2806. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2807. chunk_size};
  2808. }
  2809. template <typename ClientType>
  2810. inline Result Put(ClientType &cli, const std::string &path,
  2811. const Params &params, const Headers &headers,
  2812. const std::string &body, const std::string &content_type,
  2813. size_t chunk_size = 8192) {
  2814. return Result{
  2815. cli.open_stream("PUT", path, params, headers, body, content_type),
  2816. chunk_size};
  2817. }
  2818. // PATCH
  2819. template <typename ClientType>
  2820. inline Result Patch(ClientType &cli, const std::string &path,
  2821. const std::string &body, const std::string &content_type,
  2822. size_t chunk_size = 8192) {
  2823. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2824. chunk_size};
  2825. }
  2826. template <typename ClientType>
  2827. inline Result Patch(ClientType &cli, const std::string &path,
  2828. const Headers &headers, const std::string &body,
  2829. const std::string &content_type, size_t chunk_size = 8192) {
  2830. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2831. chunk_size};
  2832. }
  2833. template <typename ClientType>
  2834. inline Result Patch(ClientType &cli, const std::string &path,
  2835. const Params &params, const std::string &body,
  2836. const std::string &content_type, size_t chunk_size = 8192) {
  2837. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2838. chunk_size};
  2839. }
  2840. template <typename ClientType>
  2841. inline Result Patch(ClientType &cli, const std::string &path,
  2842. const Params &params, const Headers &headers,
  2843. const std::string &body, const std::string &content_type,
  2844. size_t chunk_size = 8192) {
  2845. return Result{
  2846. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2847. chunk_size};
  2848. }
  2849. // DELETE
  2850. template <typename ClientType>
  2851. inline Result Delete(ClientType &cli, const std::string &path,
  2852. size_t chunk_size = 8192) {
  2853. return Result{cli.open_stream("DELETE", path), chunk_size};
  2854. }
  2855. template <typename ClientType>
  2856. inline Result Delete(ClientType &cli, const std::string &path,
  2857. const Headers &headers, size_t chunk_size = 8192) {
  2858. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2859. }
  2860. template <typename ClientType>
  2861. inline Result Delete(ClientType &cli, const std::string &path,
  2862. const std::string &body, const std::string &content_type,
  2863. size_t chunk_size = 8192) {
  2864. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2865. chunk_size};
  2866. }
  2867. template <typename ClientType>
  2868. inline Result Delete(ClientType &cli, const std::string &path,
  2869. const Headers &headers, const std::string &body,
  2870. const std::string &content_type,
  2871. size_t chunk_size = 8192) {
  2872. return Result{
  2873. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2874. chunk_size};
  2875. }
  2876. template <typename ClientType>
  2877. inline Result Delete(ClientType &cli, const std::string &path,
  2878. const Params &params, size_t chunk_size = 8192) {
  2879. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2880. }
  2881. template <typename ClientType>
  2882. inline Result Delete(ClientType &cli, const std::string &path,
  2883. const Params &params, const Headers &headers,
  2884. size_t chunk_size = 8192) {
  2885. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2886. }
  2887. template <typename ClientType>
  2888. inline Result Delete(ClientType &cli, const std::string &path,
  2889. const Params &params, const std::string &body,
  2890. const std::string &content_type,
  2891. size_t chunk_size = 8192) {
  2892. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2893. chunk_size};
  2894. }
  2895. template <typename ClientType>
  2896. inline Result Delete(ClientType &cli, const std::string &path,
  2897. const Params &params, const Headers &headers,
  2898. const std::string &body, const std::string &content_type,
  2899. size_t chunk_size = 8192) {
  2900. return Result{
  2901. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2902. chunk_size};
  2903. }
  2904. // HEAD
  2905. template <typename ClientType>
  2906. inline Result Head(ClientType &cli, const std::string &path,
  2907. size_t chunk_size = 8192) {
  2908. return Result{cli.open_stream("HEAD", path), chunk_size};
  2909. }
  2910. template <typename ClientType>
  2911. inline Result Head(ClientType &cli, const std::string &path,
  2912. const Headers &headers, size_t chunk_size = 8192) {
  2913. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2914. }
  2915. template <typename ClientType>
  2916. inline Result Head(ClientType &cli, const std::string &path,
  2917. const Params &params, size_t chunk_size = 8192) {
  2918. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2919. }
  2920. template <typename ClientType>
  2921. inline Result Head(ClientType &cli, const std::string &path,
  2922. const Params &params, const Headers &headers,
  2923. size_t chunk_size = 8192) {
  2924. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2925. }
  2926. // OPTIONS
  2927. template <typename ClientType>
  2928. inline Result Options(ClientType &cli, const std::string &path,
  2929. size_t chunk_size = 8192) {
  2930. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2931. }
  2932. template <typename ClientType>
  2933. inline Result Options(ClientType &cli, const std::string &path,
  2934. const Headers &headers, size_t chunk_size = 8192) {
  2935. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2936. }
  2937. template <typename ClientType>
  2938. inline Result Options(ClientType &cli, const std::string &path,
  2939. const Params &params, size_t chunk_size = 8192) {
  2940. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2941. }
  2942. template <typename ClientType>
  2943. inline Result Options(ClientType &cli, const std::string &path,
  2944. const Params &params, const Headers &headers,
  2945. size_t chunk_size = 8192) {
  2946. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2947. }
  2948. } // namespace stream
  2949. namespace sse {
  2950. struct SSEMessage {
  2951. std::string event; // Event type (default: "message")
  2952. std::string data; // Event payload
  2953. std::string id; // Event ID for Last-Event-ID header
  2954. SSEMessage();
  2955. void clear();
  2956. };
  2957. class SSEClient {
  2958. public:
  2959. using MessageHandler = std::function<void(const SSEMessage &)>;
  2960. using ErrorHandler = std::function<void(Error)>;
  2961. using OpenHandler = std::function<void()>;
  2962. SSEClient(Client &client, const std::string &path);
  2963. SSEClient(Client &client, const std::string &path, const Headers &headers);
  2964. ~SSEClient();
  2965. SSEClient(const SSEClient &) = delete;
  2966. SSEClient &operator=(const SSEClient &) = delete;
  2967. // Event handlers
  2968. SSEClient &on_message(MessageHandler handler);
  2969. SSEClient &on_event(const std::string &type, MessageHandler handler);
  2970. SSEClient &on_open(OpenHandler handler);
  2971. SSEClient &on_error(ErrorHandler handler);
  2972. SSEClient &set_reconnect_interval(int ms);
  2973. SSEClient &set_max_reconnect_attempts(int n);
  2974. // Update headers (thread-safe)
  2975. SSEClient &set_headers(const Headers &headers);
  2976. // State accessors
  2977. bool is_connected() const;
  2978. const std::string &last_event_id() const;
  2979. // Blocking start - runs event loop with auto-reconnect
  2980. void start();
  2981. // Non-blocking start - runs in background thread
  2982. void start_async();
  2983. // Stop the client (thread-safe)
  2984. void stop();
  2985. private:
  2986. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  2987. void run_event_loop();
  2988. void dispatch_event(const SSEMessage &msg);
  2989. bool should_reconnect(int count) const;
  2990. void wait_for_reconnect();
  2991. // Client and path
  2992. Client &client_;
  2993. std::string path_;
  2994. Headers headers_;
  2995. mutable std::mutex headers_mutex_;
  2996. // Callbacks
  2997. MessageHandler on_message_;
  2998. std::map<std::string, MessageHandler> event_handlers_;
  2999. OpenHandler on_open_;
  3000. ErrorHandler on_error_;
  3001. // Configuration
  3002. int reconnect_interval_ms_ = 3000;
  3003. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3004. // State
  3005. std::atomic<bool> running_{false};
  3006. std::atomic<bool> connected_{false};
  3007. std::string last_event_id_;
  3008. // Async support
  3009. std::thread async_thread_;
  3010. };
  3011. } // namespace sse
  3012. namespace ws {
  3013. enum class Opcode : uint8_t {
  3014. Continuation = 0x0,
  3015. Text = 0x1,
  3016. Binary = 0x2,
  3017. Close = 0x8,
  3018. Ping = 0x9,
  3019. Pong = 0xA,
  3020. };
  3021. enum class CloseStatus : uint16_t {
  3022. Normal = 1000,
  3023. GoingAway = 1001,
  3024. ProtocolError = 1002,
  3025. UnsupportedData = 1003,
  3026. NoStatus = 1005,
  3027. Abnormal = 1006,
  3028. InvalidPayload = 1007,
  3029. PolicyViolation = 1008,
  3030. MessageTooBig = 1009,
  3031. MandatoryExtension = 1010,
  3032. InternalError = 1011,
  3033. };
  3034. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3035. class WebSocket {
  3036. public:
  3037. WebSocket(const WebSocket &) = delete;
  3038. WebSocket &operator=(const WebSocket &) = delete;
  3039. ~WebSocket();
  3040. ReadResult read(std::string &msg);
  3041. bool send(const std::string &data);
  3042. bool send(const char *data, size_t len);
  3043. void close(CloseStatus status = CloseStatus::Normal,
  3044. const std::string &reason = "");
  3045. const Request &request() const;
  3046. bool is_open() const;
  3047. private:
  3048. friend class httplib::Server;
  3049. friend class WebSocketClient;
  3050. WebSocket(
  3051. Stream &strm, const Request &req, bool is_server,
  3052. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3053. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3054. : strm_(strm), req_(req), is_server_(is_server),
  3055. ping_interval_sec_(ping_interval_sec),
  3056. max_missed_pongs_(max_missed_pongs) {
  3057. start_heartbeat();
  3058. }
  3059. WebSocket(
  3060. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3061. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3062. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3063. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3064. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3065. max_missed_pongs_(max_missed_pongs) {
  3066. start_heartbeat();
  3067. }
  3068. void start_heartbeat();
  3069. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3070. Stream &strm_;
  3071. std::unique_ptr<Stream> owned_strm_;
  3072. Request req_;
  3073. bool is_server_;
  3074. time_t ping_interval_sec_;
  3075. int max_missed_pongs_;
  3076. int unacked_pings_ = 0;
  3077. std::atomic<bool> closed_{false};
  3078. std::mutex write_mutex_;
  3079. std::thread ping_thread_;
  3080. std::mutex ping_mutex_;
  3081. std::condition_variable ping_cv_;
  3082. };
  3083. class WebSocketClient {
  3084. public:
  3085. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3086. const Headers &headers = {});
  3087. ~WebSocketClient();
  3088. WebSocketClient(const WebSocketClient &) = delete;
  3089. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3090. bool is_valid() const;
  3091. bool connect();
  3092. ReadResult read(std::string &msg);
  3093. bool send(const std::string &data);
  3094. bool send(const char *data, size_t len);
  3095. void close(CloseStatus status = CloseStatus::Normal,
  3096. const std::string &reason = "");
  3097. bool is_open() const;
  3098. const std::string &subprotocol() const;
  3099. void set_read_timeout(time_t sec, time_t usec = 0);
  3100. void set_write_timeout(time_t sec, time_t usec = 0);
  3101. void set_websocket_ping_interval(time_t sec);
  3102. void set_websocket_max_missed_pongs(int count);
  3103. void set_tcp_nodelay(bool on);
  3104. void set_address_family(int family);
  3105. void set_ipv6_v6only(bool on);
  3106. void set_socket_options(SocketOptions socket_options);
  3107. void set_connection_timeout(time_t sec, time_t usec = 0);
  3108. void set_interface(const std::string &intf);
  3109. #ifdef CPPHTTPLIB_SSL_ENABLED
  3110. void set_ca_cert_path(const std::string &path);
  3111. void set_ca_cert_store(tls::ca_store_t store);
  3112. void enable_server_certificate_verification(bool enabled);
  3113. #endif
  3114. private:
  3115. void shutdown_and_close();
  3116. bool create_stream(std::unique_ptr<Stream> &strm);
  3117. std::string host_;
  3118. int port_;
  3119. std::string path_;
  3120. Headers headers_;
  3121. std::string subprotocol_;
  3122. bool is_valid_ = false;
  3123. socket_t sock_ = INVALID_SOCKET;
  3124. std::unique_ptr<WebSocket> ws_;
  3125. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3126. time_t read_timeout_usec_ = 0;
  3127. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3128. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3129. time_t websocket_ping_interval_sec_ =
  3130. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3131. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3132. int address_family_ = AF_UNSPEC;
  3133. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3134. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3135. SocketOptions socket_options_ = nullptr;
  3136. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3137. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3138. std::string interface_;
  3139. #ifdef CPPHTTPLIB_SSL_ENABLED
  3140. bool is_ssl_ = false;
  3141. tls::ctx_t tls_ctx_ = nullptr;
  3142. tls::session_t tls_session_ = nullptr;
  3143. std::string ca_cert_file_path_;
  3144. tls::ca_store_t ca_cert_store_ = nullptr;
  3145. bool server_certificate_verification_ = true;
  3146. #endif
  3147. };
  3148. namespace impl {
  3149. bool is_valid_utf8(const std::string &s);
  3150. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3151. bool &fin, bool expect_masked, size_t max_len);
  3152. } // namespace impl
  3153. } // namespace ws
  3154. // ----------------------------------------------------------------------------
  3155. /*
  3156. * Implementation that will be part of the .cc file if split into .h + .cc.
  3157. */
  3158. namespace stream {
  3159. // stream::Result implementations
  3160. inline Result::Result() : chunk_size_(8192) {}
  3161. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3162. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3163. inline Result::Result(Result &&other) noexcept
  3164. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3165. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3166. finished_(other.finished_) {
  3167. other.current_size_ = 0;
  3168. other.finished_ = true;
  3169. }
  3170. inline Result &Result::operator=(Result &&other) noexcept {
  3171. if (this != &other) {
  3172. handle_ = std::move(other.handle_);
  3173. buffer_ = std::move(other.buffer_);
  3174. current_size_ = other.current_size_;
  3175. chunk_size_ = other.chunk_size_;
  3176. finished_ = other.finished_;
  3177. other.current_size_ = 0;
  3178. other.finished_ = true;
  3179. }
  3180. return *this;
  3181. }
  3182. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3183. inline Result::operator bool() const { return is_valid(); }
  3184. inline int Result::status() const {
  3185. return handle_.response ? handle_.response->status : -1;
  3186. }
  3187. inline const Headers &Result::headers() const {
  3188. static const Headers empty_headers;
  3189. return handle_.response ? handle_.response->headers : empty_headers;
  3190. }
  3191. inline std::string Result::get_header_value(const std::string &key,
  3192. const char *def) const {
  3193. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3194. }
  3195. inline bool Result::has_header(const std::string &key) const {
  3196. return handle_.response ? handle_.response->has_header(key) : false;
  3197. }
  3198. inline Error Result::error() const { return handle_.error; }
  3199. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3200. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3201. inline bool Result::next() {
  3202. if (!handle_.is_valid() || finished_) { return false; }
  3203. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3204. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3205. if (n > 0) {
  3206. current_size_ = static_cast<size_t>(n);
  3207. return true;
  3208. }
  3209. current_size_ = 0;
  3210. finished_ = true;
  3211. return false;
  3212. }
  3213. inline const char *Result::data() const { return buffer_.data(); }
  3214. inline size_t Result::size() const { return current_size_; }
  3215. inline std::string Result::read_all() {
  3216. std::string result;
  3217. while (next()) {
  3218. result.append(data(), size());
  3219. }
  3220. return result;
  3221. }
  3222. } // namespace stream
  3223. namespace sse {
  3224. // SSEMessage implementations
  3225. inline SSEMessage::SSEMessage() : event("message") {}
  3226. inline void SSEMessage::clear() {
  3227. event = "message";
  3228. data.clear();
  3229. id.clear();
  3230. }
  3231. // SSEClient implementations
  3232. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3233. : client_(client), path_(path) {}
  3234. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3235. const Headers &headers)
  3236. : client_(client), path_(path), headers_(headers) {}
  3237. inline SSEClient::~SSEClient() { stop(); }
  3238. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3239. on_message_ = std::move(handler);
  3240. return *this;
  3241. }
  3242. inline SSEClient &SSEClient::on_event(const std::string &type,
  3243. MessageHandler handler) {
  3244. event_handlers_[type] = std::move(handler);
  3245. return *this;
  3246. }
  3247. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3248. on_open_ = std::move(handler);
  3249. return *this;
  3250. }
  3251. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3252. on_error_ = std::move(handler);
  3253. return *this;
  3254. }
  3255. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3256. reconnect_interval_ms_ = ms;
  3257. return *this;
  3258. }
  3259. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3260. max_reconnect_attempts_ = n;
  3261. return *this;
  3262. }
  3263. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3264. std::lock_guard<std::mutex> lock(headers_mutex_);
  3265. headers_ = headers;
  3266. return *this;
  3267. }
  3268. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3269. inline const std::string &SSEClient::last_event_id() const {
  3270. return last_event_id_;
  3271. }
  3272. inline void SSEClient::start() {
  3273. running_.store(true);
  3274. run_event_loop();
  3275. }
  3276. inline void SSEClient::start_async() {
  3277. running_.store(true);
  3278. async_thread_ = std::thread([this]() { run_event_loop(); });
  3279. }
  3280. inline void SSEClient::stop() {
  3281. running_.store(false);
  3282. client_.stop(); // Cancel any pending operations
  3283. if (async_thread_.joinable()) { async_thread_.join(); }
  3284. }
  3285. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3286. int &retry_ms) {
  3287. // Blank line signals end of event
  3288. if (line.empty() || line == "\r") { return true; }
  3289. // Lines starting with ':' are comments (ignored)
  3290. if (!line.empty() && line[0] == ':') { return false; }
  3291. // Find the colon separator
  3292. auto colon_pos = line.find(':');
  3293. if (colon_pos == std::string::npos) {
  3294. // Line with no colon is treated as field name with empty value
  3295. return false;
  3296. }
  3297. auto field = line.substr(0, colon_pos);
  3298. std::string value;
  3299. // Value starts after colon, skip optional single space
  3300. if (colon_pos + 1 < line.size()) {
  3301. auto value_start = colon_pos + 1;
  3302. if (line[value_start] == ' ') { value_start++; }
  3303. value = line.substr(value_start);
  3304. // Remove trailing \r if present
  3305. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3306. }
  3307. // Handle known fields
  3308. if (field == "event") {
  3309. msg.event = value;
  3310. } else if (field == "data") {
  3311. // Multiple data lines are concatenated with newlines
  3312. if (!msg.data.empty()) { msg.data += "\n"; }
  3313. msg.data += value;
  3314. } else if (field == "id") {
  3315. // Empty id is valid (clears the last event ID)
  3316. msg.id = value;
  3317. } else if (field == "retry") {
  3318. // Parse retry interval in milliseconds
  3319. {
  3320. int v = 0;
  3321. auto res =
  3322. detail::from_chars(value.data(), value.data() + value.size(), v);
  3323. if (res.ec == std::errc{}) { retry_ms = v; }
  3324. }
  3325. }
  3326. // Unknown fields are ignored per SSE spec
  3327. return false;
  3328. }
  3329. inline void SSEClient::run_event_loop() {
  3330. auto reconnect_count = 0;
  3331. while (running_.load()) {
  3332. // Build headers, including Last-Event-ID if we have one
  3333. Headers request_headers;
  3334. {
  3335. std::lock_guard<std::mutex> lock(headers_mutex_);
  3336. request_headers = headers_;
  3337. }
  3338. if (!last_event_id_.empty()) {
  3339. request_headers.emplace("Last-Event-ID", last_event_id_);
  3340. }
  3341. // Open streaming connection
  3342. auto result = stream::Get(client_, path_, request_headers);
  3343. // Connection error handling
  3344. if (!result) {
  3345. connected_.store(false);
  3346. if (on_error_) { on_error_(result.error()); }
  3347. if (!should_reconnect(reconnect_count)) { break; }
  3348. wait_for_reconnect();
  3349. reconnect_count++;
  3350. continue;
  3351. }
  3352. if (result.status() != StatusCode::OK_200) {
  3353. connected_.store(false);
  3354. if (on_error_) { on_error_(Error::Connection); }
  3355. // For certain errors, don't reconnect.
  3356. // Note: 401 is intentionally absent so that handlers can refresh
  3357. // credentials via set_headers() and let the client reconnect.
  3358. if (result.status() == StatusCode::NoContent_204 ||
  3359. result.status() == StatusCode::NotFound_404 ||
  3360. result.status() == StatusCode::Forbidden_403) {
  3361. break;
  3362. }
  3363. if (!should_reconnect(reconnect_count)) { break; }
  3364. wait_for_reconnect();
  3365. reconnect_count++;
  3366. continue;
  3367. }
  3368. // Connection successful
  3369. connected_.store(true);
  3370. reconnect_count = 0;
  3371. if (on_open_) { on_open_(); }
  3372. // Event receiving loop
  3373. std::string buffer;
  3374. SSEMessage current_msg;
  3375. while (running_.load() && result.next()) {
  3376. buffer.append(result.data(), result.size());
  3377. // Process complete lines in the buffer
  3378. size_t line_start = 0;
  3379. size_t newline_pos;
  3380. while ((newline_pos = buffer.find('\n', line_start)) !=
  3381. std::string::npos) {
  3382. auto line = buffer.substr(line_start, newline_pos - line_start);
  3383. line_start = newline_pos + 1;
  3384. // Parse the line and check if event is complete
  3385. auto event_complete =
  3386. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3387. if (event_complete && !current_msg.data.empty()) {
  3388. // Update last_event_id for reconnection
  3389. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3390. // Dispatch event to appropriate handler
  3391. dispatch_event(current_msg);
  3392. current_msg.clear();
  3393. }
  3394. }
  3395. // Keep unprocessed data in buffer
  3396. buffer.erase(0, line_start);
  3397. }
  3398. // Connection ended
  3399. connected_.store(false);
  3400. if (!running_.load()) { break; }
  3401. // Check for read errors
  3402. if (result.has_read_error()) {
  3403. if (on_error_) { on_error_(result.read_error()); }
  3404. }
  3405. if (!should_reconnect(reconnect_count)) { break; }
  3406. wait_for_reconnect();
  3407. reconnect_count++;
  3408. }
  3409. connected_.store(false);
  3410. }
  3411. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3412. // Check for specific event type handler first
  3413. auto it = event_handlers_.find(msg.event);
  3414. if (it != event_handlers_.end()) {
  3415. it->second(msg);
  3416. return;
  3417. }
  3418. // Fall back to generic message handler
  3419. if (on_message_) { on_message_(msg); }
  3420. }
  3421. inline bool SSEClient::should_reconnect(int count) const {
  3422. if (!running_.load()) { return false; }
  3423. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3424. return count < max_reconnect_attempts_;
  3425. }
  3426. inline void SSEClient::wait_for_reconnect() {
  3427. // Use small increments to check running_ flag frequently
  3428. auto waited = 0;
  3429. while (running_.load() && waited < reconnect_interval_ms_) {
  3430. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3431. waited += 100;
  3432. }
  3433. }
  3434. } // namespace sse
  3435. #ifdef CPPHTTPLIB_SSL_ENABLED
  3436. /*
  3437. * TLS abstraction layer - internal function declarations
  3438. * These are implementation details and not part of the public API.
  3439. */
  3440. namespace tls {
  3441. // Client context
  3442. ctx_t create_client_context();
  3443. void free_context(ctx_t ctx);
  3444. bool set_min_version(ctx_t ctx, Version version);
  3445. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3446. bool load_ca_file(ctx_t ctx, const char *file_path);
  3447. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3448. bool load_system_certs(ctx_t ctx);
  3449. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3450. const char *password);
  3451. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3452. const char *key_path, const char *password);
  3453. // Server context
  3454. ctx_t create_server_context();
  3455. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3456. const char *password);
  3457. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3458. const char *key_path, const char *password);
  3459. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3460. void set_verify_client(ctx_t ctx, bool require);
  3461. // Session management
  3462. session_t create_session(ctx_t ctx, socket_t sock);
  3463. void free_session(session_t session);
  3464. bool set_sni(session_t session, const char *hostname);
  3465. bool set_hostname(session_t session, const char *hostname);
  3466. // Handshake (non-blocking capable)
  3467. TlsError connect(session_t session);
  3468. TlsError accept(session_t session);
  3469. // Handshake with timeout (blocking until timeout)
  3470. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3471. time_t timeout_usec, TlsError *err);
  3472. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3473. time_t timeout_usec, TlsError *err);
  3474. // I/O (non-blocking capable)
  3475. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3476. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3477. int pending(const_session_t session);
  3478. void shutdown(session_t session, bool graceful);
  3479. // Connection state
  3480. bool is_peer_closed(session_t session, socket_t sock);
  3481. // Certificate verification
  3482. cert_t get_peer_cert(const_session_t session);
  3483. void free_cert(cert_t cert);
  3484. bool verify_hostname(cert_t cert, const char *hostname);
  3485. uint64_t hostname_mismatch_code();
  3486. long get_verify_result(const_session_t session);
  3487. // Certificate introspection
  3488. std::string get_cert_subject_cn(cert_t cert);
  3489. std::string get_cert_issuer_name(cert_t cert);
  3490. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3491. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3492. std::string get_cert_serial(cert_t cert);
  3493. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3494. const char *get_sni(const_session_t session);
  3495. // CA store management
  3496. ca_store_t create_ca_store(const char *pem, size_t len);
  3497. void free_ca_store(ca_store_t store);
  3498. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3499. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3500. std::vector<std::string> get_ca_names(ctx_t ctx);
  3501. // Dynamic certificate update (for servers)
  3502. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3503. const char *password);
  3504. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3505. // Certificate verification callback
  3506. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3507. long get_verify_error(const_session_t session);
  3508. std::string verify_error_string(long error_code);
  3509. // TlsError information
  3510. uint64_t peek_error();
  3511. uint64_t get_error();
  3512. std::string error_string(uint64_t code);
  3513. } // namespace tls
  3514. #endif // CPPHTTPLIB_SSL_ENABLED
  3515. /*
  3516. * Group 1: detail namespace - Non-SSL utilities
  3517. */
  3518. namespace detail {
  3519. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3520. const void *optval, socklen_t optlen) {
  3521. return setsockopt(sock, level, optname,
  3522. #ifdef _WIN32
  3523. reinterpret_cast<const char *>(optval),
  3524. #else
  3525. optval,
  3526. #endif
  3527. optlen) == 0;
  3528. }
  3529. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3530. time_t sec, time_t usec) {
  3531. #ifdef _WIN32
  3532. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3533. #else
  3534. timeval timeout;
  3535. timeout.tv_sec = static_cast<long>(sec);
  3536. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3537. #endif
  3538. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3539. }
  3540. inline bool is_hex(char c, int &v) {
  3541. if (isdigit(c)) {
  3542. v = c - '0';
  3543. return true;
  3544. } else if ('A' <= c && c <= 'F') {
  3545. v = c - 'A' + 10;
  3546. return true;
  3547. } else if ('a' <= c && c <= 'f') {
  3548. v = c - 'a' + 10;
  3549. return true;
  3550. }
  3551. return false;
  3552. }
  3553. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3554. int &val) {
  3555. if (i >= s.size()) { return false; }
  3556. val = 0;
  3557. for (; cnt; i++, cnt--) {
  3558. if (!s[i]) { return false; }
  3559. auto v = 0;
  3560. if (is_hex(s[i], v)) {
  3561. val = val * 16 + v;
  3562. } else {
  3563. return false;
  3564. }
  3565. }
  3566. return true;
  3567. }
  3568. inline std::string from_i_to_hex(size_t n) {
  3569. static const auto charset = "0123456789abcdef";
  3570. std::string ret;
  3571. do {
  3572. ret = charset[n & 15] + ret;
  3573. n >>= 4;
  3574. } while (n > 0);
  3575. return ret;
  3576. }
  3577. inline std::string compute_etag(const FileStat &fs) {
  3578. if (!fs.is_file()) { return std::string(); }
  3579. // If mtime cannot be determined (negative value indicates an error
  3580. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3581. // value like 0 could collide with a real file that legitimately has
  3582. // mtime == 0 (epoch) and lead to misleading validators.
  3583. auto mtime_raw = fs.mtime();
  3584. if (mtime_raw < 0) { return std::string(); }
  3585. auto mtime = static_cast<size_t>(mtime_raw);
  3586. auto size = fs.size();
  3587. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3588. from_i_to_hex(size) + "\"";
  3589. }
  3590. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3591. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3592. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3593. inline std::string file_mtime_to_http_date(time_t mtime) {
  3594. if (mtime < 0) { return std::string(); }
  3595. struct tm tm_buf;
  3596. #ifdef _WIN32
  3597. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3598. #else
  3599. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3600. #endif
  3601. char buf[64];
  3602. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3603. return std::string();
  3604. }
  3605. return std::string(buf);
  3606. }
  3607. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3608. inline time_t parse_http_date(const std::string &date_str) {
  3609. struct tm tm_buf;
  3610. // Create a classic locale object once for all parsing attempts
  3611. const std::locale classic_locale = std::locale::classic();
  3612. // Try to parse using std::get_time (C++11, cross-platform)
  3613. auto try_parse = [&](const char *fmt) -> bool {
  3614. std::istringstream ss(date_str);
  3615. ss.imbue(classic_locale);
  3616. memset(&tm_buf, 0, sizeof(tm_buf));
  3617. ss >> std::get_time(&tm_buf, fmt);
  3618. return !ss.fail();
  3619. };
  3620. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3621. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3622. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3623. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3624. // asctime format: "Sun Nov 6 08:49:37 1994"
  3625. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3626. return static_cast<time_t>(-1);
  3627. }
  3628. }
  3629. }
  3630. #ifdef _WIN32
  3631. return _mkgmtime(&tm_buf);
  3632. #elif defined _AIX
  3633. return mktime(&tm_buf);
  3634. #else
  3635. return timegm(&tm_buf);
  3636. #endif
  3637. }
  3638. inline bool is_weak_etag(const std::string &s) {
  3639. // Check if the string is a weak ETag (starts with 'W/"')
  3640. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3641. }
  3642. inline bool is_strong_etag(const std::string &s) {
  3643. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3644. // chars)
  3645. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3646. }
  3647. inline size_t to_utf8(int code, char *buff) {
  3648. if (code < 0x0080) {
  3649. buff[0] = static_cast<char>(code & 0x7F);
  3650. return 1;
  3651. } else if (code < 0x0800) {
  3652. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3653. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3654. return 2;
  3655. } else if (code < 0xD800) {
  3656. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3657. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3658. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3659. return 3;
  3660. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3661. return 0;
  3662. } else if (code < 0x10000) {
  3663. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3664. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3665. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3666. return 3;
  3667. } else if (code < 0x110000) {
  3668. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3669. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3670. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3671. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3672. return 4;
  3673. }
  3674. // NOTREACHED
  3675. return 0;
  3676. }
  3677. } // namespace detail
  3678. namespace ws {
  3679. namespace impl {
  3680. inline bool is_valid_utf8(const std::string &s) {
  3681. size_t i = 0;
  3682. auto n = s.size();
  3683. while (i < n) {
  3684. auto c = static_cast<unsigned char>(s[i]);
  3685. size_t len;
  3686. uint32_t cp;
  3687. if (c < 0x80) {
  3688. i++;
  3689. continue;
  3690. } else if ((c & 0xE0) == 0xC0) {
  3691. len = 2;
  3692. cp = c & 0x1F;
  3693. } else if ((c & 0xF0) == 0xE0) {
  3694. len = 3;
  3695. cp = c & 0x0F;
  3696. } else if ((c & 0xF8) == 0xF0) {
  3697. len = 4;
  3698. cp = c & 0x07;
  3699. } else {
  3700. return false;
  3701. }
  3702. if (i + len > n) { return false; }
  3703. for (size_t j = 1; j < len; j++) {
  3704. auto b = static_cast<unsigned char>(s[i + j]);
  3705. if ((b & 0xC0) != 0x80) { return false; }
  3706. cp = (cp << 6) | (b & 0x3F);
  3707. }
  3708. // Overlong encoding check
  3709. if (len == 2 && cp < 0x80) { return false; }
  3710. if (len == 3 && cp < 0x800) { return false; }
  3711. if (len == 4 && cp < 0x10000) { return false; }
  3712. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3713. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3714. if (cp > 0x10FFFF) { return false; }
  3715. i += len;
  3716. }
  3717. return true;
  3718. }
  3719. } // namespace impl
  3720. } // namespace ws
  3721. namespace detail {
  3722. // NOTE: This code came up with the following stackoverflow post:
  3723. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3724. inline std::string base64_encode(const std::string &in) {
  3725. static const auto lookup =
  3726. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3727. std::string out;
  3728. out.reserve(in.size());
  3729. auto val = 0;
  3730. auto valb = -6;
  3731. for (auto c : in) {
  3732. val = (val << 8) + static_cast<uint8_t>(c);
  3733. valb += 8;
  3734. while (valb >= 0) {
  3735. out.push_back(lookup[(val >> valb) & 0x3F]);
  3736. valb -= 6;
  3737. }
  3738. }
  3739. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3740. while (out.size() % 4) {
  3741. out.push_back('=');
  3742. }
  3743. return out;
  3744. }
  3745. inline std::string sha1(const std::string &input) {
  3746. // RFC 3174 SHA-1 implementation
  3747. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3748. return (x << n) | (x >> (32 - n));
  3749. };
  3750. uint32_t h0 = 0x67452301;
  3751. uint32_t h1 = 0xEFCDAB89;
  3752. uint32_t h2 = 0x98BADCFE;
  3753. uint32_t h3 = 0x10325476;
  3754. uint32_t h4 = 0xC3D2E1F0;
  3755. // Pre-processing: adding padding bits
  3756. std::string msg = input;
  3757. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3758. msg.push_back(static_cast<char>(0x80));
  3759. while (msg.size() % 64 != 56) {
  3760. msg.push_back(0);
  3761. }
  3762. // Append original length in bits as 64-bit big-endian
  3763. for (int i = 56; i >= 0; i -= 8) {
  3764. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3765. }
  3766. // Process each 512-bit chunk
  3767. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3768. uint32_t w[80];
  3769. for (size_t i = 0; i < 16; i++) {
  3770. w[i] =
  3771. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3772. << 24) |
  3773. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3774. << 16) |
  3775. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3776. << 8) |
  3777. (static_cast<uint32_t>(
  3778. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3779. }
  3780. for (int i = 16; i < 80; i++) {
  3781. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3782. }
  3783. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3784. for (int i = 0; i < 80; i++) {
  3785. uint32_t f, k;
  3786. if (i < 20) {
  3787. f = (b & c) | ((~b) & d);
  3788. k = 0x5A827999;
  3789. } else if (i < 40) {
  3790. f = b ^ c ^ d;
  3791. k = 0x6ED9EBA1;
  3792. } else if (i < 60) {
  3793. f = (b & c) | (b & d) | (c & d);
  3794. k = 0x8F1BBCDC;
  3795. } else {
  3796. f = b ^ c ^ d;
  3797. k = 0xCA62C1D6;
  3798. }
  3799. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3800. e = d;
  3801. d = c;
  3802. c = left_rotate(b, 30);
  3803. b = a;
  3804. a = temp;
  3805. }
  3806. h0 += a;
  3807. h1 += b;
  3808. h2 += c;
  3809. h3 += d;
  3810. h4 += e;
  3811. }
  3812. // Produce the final hash as a 20-byte binary string
  3813. std::string hash(20, '\0');
  3814. for (size_t i = 0; i < 4; i++) {
  3815. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3816. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3817. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3818. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3819. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3820. }
  3821. return hash;
  3822. }
  3823. inline std::string websocket_accept_key(const std::string &client_key) {
  3824. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3825. return base64_encode(sha1(client_key + magic));
  3826. }
  3827. inline bool is_websocket_upgrade(const Request &req) {
  3828. if (req.method != "GET") { return false; }
  3829. // Check Upgrade: websocket (case-insensitive)
  3830. auto upgrade_it = req.headers.find("Upgrade");
  3831. if (upgrade_it == req.headers.end()) { return false; }
  3832. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3833. if (upgrade_val != "websocket") { return false; }
  3834. // Check Connection header contains "Upgrade"
  3835. auto connection_it = req.headers.find("Connection");
  3836. if (connection_it == req.headers.end()) { return false; }
  3837. auto connection_val = case_ignore::to_lower(connection_it->second);
  3838. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3839. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3840. // RFC 6455 Section 4.2.1
  3841. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3842. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3843. return false;
  3844. }
  3845. static const std::string b64chars =
  3846. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3847. for (size_t i = 0; i < 22; i++) {
  3848. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3849. }
  3850. // Check Sec-WebSocket-Version: 13
  3851. auto version = req.get_header_value("Sec-WebSocket-Version");
  3852. if (version != "13") { return false; }
  3853. return true;
  3854. }
  3855. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  3856. const char *data, size_t len, bool fin,
  3857. bool mask) {
  3858. // First byte: FIN + opcode
  3859. uint8_t header[2];
  3860. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  3861. (static_cast<uint8_t>(opcode) & 0x0F));
  3862. // Second byte: MASK + payload length
  3863. if (len < 126) {
  3864. header[1] = static_cast<uint8_t>(len);
  3865. if (mask) { header[1] |= 0x80; }
  3866. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3867. } else if (len <= 0xFFFF) {
  3868. header[1] = 126;
  3869. if (mask) { header[1] |= 0x80; }
  3870. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3871. uint8_t ext[2];
  3872. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  3873. ext[1] = static_cast<uint8_t>(len & 0xFF);
  3874. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  3875. } else {
  3876. header[1] = 127;
  3877. if (mask) { header[1] |= 0x80; }
  3878. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3879. uint8_t ext[8];
  3880. for (int i = 7; i >= 0; i--) {
  3881. ext[7 - i] =
  3882. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  3883. }
  3884. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  3885. }
  3886. if (mask) {
  3887. // Generate random mask key
  3888. thread_local std::mt19937 rng(std::random_device{}());
  3889. uint8_t mask_key[4];
  3890. auto r = rng();
  3891. std::memcpy(mask_key, &r, 4);
  3892. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  3893. // Write masked payload in chunks
  3894. const size_t chunk_size = 4096;
  3895. std::vector<char> buf((std::min)(len, chunk_size));
  3896. for (size_t offset = 0; offset < len; offset += chunk_size) {
  3897. size_t n = (std::min)(chunk_size, len - offset);
  3898. for (size_t i = 0; i < n; i++) {
  3899. buf[i] =
  3900. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  3901. }
  3902. if (strm.write(buf.data(), n) < 0) { return false; }
  3903. }
  3904. } else {
  3905. if (len > 0) {
  3906. if (strm.write(data, len) < 0) { return false; }
  3907. }
  3908. }
  3909. return true;
  3910. }
  3911. } // namespace detail
  3912. namespace ws {
  3913. namespace impl {
  3914. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  3915. std::string &payload, bool &fin,
  3916. bool expect_masked, size_t max_len) {
  3917. // Read first 2 bytes
  3918. uint8_t header[2];
  3919. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  3920. fin = (header[0] & 0x80) != 0;
  3921. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  3922. if (header[0] & 0x70) { return false; }
  3923. opcode = static_cast<Opcode>(header[0] & 0x0F);
  3924. bool masked = (header[1] & 0x80) != 0;
  3925. uint64_t payload_len = header[1] & 0x7F;
  3926. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  3927. // MUST have a payload length of 125 bytes or less
  3928. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  3929. if (is_control) {
  3930. if (!fin) { return false; }
  3931. if (payload_len > 125) { return false; }
  3932. }
  3933. if (masked != expect_masked) { return false; }
  3934. // Extended payload length
  3935. if (payload_len == 126) {
  3936. uint8_t ext[2];
  3937. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  3938. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  3939. } else if (payload_len == 127) {
  3940. uint8_t ext[8];
  3941. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  3942. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  3943. if (ext[0] & 0x80) { return false; }
  3944. payload_len = 0;
  3945. for (int i = 0; i < 8; i++) {
  3946. payload_len = (payload_len << 8) | ext[i];
  3947. }
  3948. }
  3949. if (payload_len > max_len) { return false; }
  3950. // Read mask key if present
  3951. uint8_t mask_key[4] = {0};
  3952. if (masked) {
  3953. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  3954. }
  3955. // Read payload
  3956. payload.resize(static_cast<size_t>(payload_len));
  3957. if (payload_len > 0) {
  3958. size_t total_read = 0;
  3959. while (total_read < payload_len) {
  3960. auto n = strm.read(&payload[total_read],
  3961. static_cast<size_t>(payload_len - total_read));
  3962. if (n <= 0) { return false; }
  3963. total_read += static_cast<size_t>(n);
  3964. }
  3965. }
  3966. // Unmask if needed
  3967. if (masked) {
  3968. for (size_t i = 0; i < payload.size(); i++) {
  3969. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  3970. }
  3971. }
  3972. return true;
  3973. }
  3974. } // namespace impl
  3975. } // namespace ws
  3976. namespace detail {
  3977. inline bool is_valid_path(const std::string &path) {
  3978. size_t level = 0;
  3979. size_t i = 0;
  3980. // Skip slash
  3981. while (i < path.size() && path[i] == '/') {
  3982. i++;
  3983. }
  3984. while (i < path.size()) {
  3985. // Read component
  3986. auto beg = i;
  3987. while (i < path.size() && path[i] != '/') {
  3988. if (path[i] == '\0') {
  3989. return false;
  3990. } else if (path[i] == '\\') {
  3991. return false;
  3992. }
  3993. i++;
  3994. }
  3995. auto len = i - beg;
  3996. assert(len > 0);
  3997. if (!path.compare(beg, len, ".")) {
  3998. ;
  3999. } else if (!path.compare(beg, len, "..")) {
  4000. if (level == 0) { return false; }
  4001. level--;
  4002. } else {
  4003. level++;
  4004. }
  4005. // Skip slash
  4006. while (i < path.size() && path[i] == '/') {
  4007. i++;
  4008. }
  4009. }
  4010. return true;
  4011. }
  4012. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4013. #if defined(_WIN32)
  4014. char buf[_MAX_PATH];
  4015. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4016. resolved = buf;
  4017. #elif defined(PATH_MAX)
  4018. char buf[PATH_MAX];
  4019. if (realpath(path, buf) == nullptr) { return false; }
  4020. resolved = buf;
  4021. #else
  4022. auto buf = realpath(path, nullptr);
  4023. auto guard = scope_exit([&]() { std::free(buf); });
  4024. if (buf == nullptr) { return false; }
  4025. resolved = buf;
  4026. #endif
  4027. return true;
  4028. }
  4029. inline bool is_path_within_base(const std::string &resolved_path,
  4030. const std::string &resolved_base) {
  4031. #if defined(_WIN32)
  4032. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4033. resolved_base.size()) == 0;
  4034. #else
  4035. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4036. resolved_base.size()) == 0;
  4037. #endif
  4038. }
  4039. inline FileStat::FileStat(const std::string &path) {
  4040. #if defined(_WIN32)
  4041. auto wpath = u8string_to_wstring(path.c_str());
  4042. ret_ = _wstat(wpath.c_str(), &st_);
  4043. #else
  4044. ret_ = stat(path.c_str(), &st_);
  4045. #endif
  4046. }
  4047. inline bool FileStat::is_file() const {
  4048. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4049. }
  4050. inline bool FileStat::is_dir() const {
  4051. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4052. }
  4053. inline time_t FileStat::mtime() const {
  4054. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4055. : static_cast<time_t>(-1);
  4056. }
  4057. inline size_t FileStat::size() const {
  4058. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4059. }
  4060. inline std::string encode_path(const std::string &s) {
  4061. std::string result;
  4062. result.reserve(s.size());
  4063. for (size_t i = 0; s[i]; i++) {
  4064. switch (s[i]) {
  4065. case ' ': result += "%20"; break;
  4066. case '+': result += "%2B"; break;
  4067. case '\r': result += "%0D"; break;
  4068. case '\n': result += "%0A"; break;
  4069. case '\'': result += "%27"; break;
  4070. case ',': result += "%2C"; break;
  4071. // case ':': result += "%3A"; break; // ok? probably...
  4072. case ';': result += "%3B"; break;
  4073. default:
  4074. auto c = static_cast<uint8_t>(s[i]);
  4075. if (c >= 0x80) {
  4076. result += '%';
  4077. char hex[4];
  4078. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4079. assert(len == 2);
  4080. result.append(hex, static_cast<size_t>(len));
  4081. } else {
  4082. result += s[i];
  4083. }
  4084. break;
  4085. }
  4086. }
  4087. return result;
  4088. }
  4089. inline std::string file_extension(const std::string &path) {
  4090. std::smatch m;
  4091. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4092. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4093. return std::string();
  4094. }
  4095. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4096. template <typename T>
  4097. inline bool parse_header(const char *beg, const char *end, T fn);
  4098. template <typename T>
  4099. inline bool parse_header(const char *beg, const char *end, T fn) {
  4100. // Skip trailing spaces and tabs.
  4101. while (beg < end && is_space_or_tab(end[-1])) {
  4102. end--;
  4103. }
  4104. auto p = beg;
  4105. while (p < end && *p != ':') {
  4106. p++;
  4107. }
  4108. auto name = std::string(beg, p);
  4109. if (!detail::fields::is_field_name(name)) { return false; }
  4110. if (p == end) { return false; }
  4111. auto key_end = p;
  4112. if (*p++ != ':') { return false; }
  4113. while (p < end && is_space_or_tab(*p)) {
  4114. p++;
  4115. }
  4116. if (p <= end) {
  4117. auto key_len = key_end - beg;
  4118. if (!key_len) { return false; }
  4119. auto key = std::string(beg, key_end);
  4120. auto val = std::string(p, end);
  4121. if (!detail::fields::is_field_value(val)) { return false; }
  4122. if (case_ignore::equal(key, "Location") ||
  4123. case_ignore::equal(key, "Referer")) {
  4124. fn(key, val);
  4125. } else {
  4126. fn(key, decode_path_component(val));
  4127. }
  4128. return true;
  4129. }
  4130. return false;
  4131. }
  4132. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4133. const Headers &src_headers) {
  4134. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4135. // transfer coding is complete when a chunk with a chunk-size of zero is
  4136. // received, possibly followed by a trailer section, and finally terminated by
  4137. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4138. //
  4139. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4140. // doesn't care for the existence of the final CRLF. In other words, it seems
  4141. // to be ok whether the final CRLF exists or not in the chunked data.
  4142. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4143. //
  4144. // According to the reference code in RFC 9112, cpp-httplib now allows
  4145. // chunked transfer coding data without the final CRLF.
  4146. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4147. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4148. "transfer-encoding",
  4149. "content-length",
  4150. "host",
  4151. "authorization",
  4152. "www-authenticate",
  4153. "proxy-authenticate",
  4154. "proxy-authorization",
  4155. "cookie",
  4156. "set-cookie",
  4157. "cache-control",
  4158. "expect",
  4159. "max-forwards",
  4160. "pragma",
  4161. "range",
  4162. "te",
  4163. "age",
  4164. "expires",
  4165. "date",
  4166. "location",
  4167. "retry-after",
  4168. "vary",
  4169. "warning",
  4170. "content-encoding",
  4171. "content-type",
  4172. "content-range",
  4173. "trailer"};
  4174. case_ignore::unordered_set<std::string> declared_trailers;
  4175. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4176. if (trailer_header && std::strlen(trailer_header)) {
  4177. auto len = std::strlen(trailer_header);
  4178. split(trailer_header, trailer_header + len, ',',
  4179. [&](const char *b, const char *e) {
  4180. const char *kbeg = b;
  4181. const char *kend = e;
  4182. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4183. ++kbeg;
  4184. }
  4185. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4186. --kend;
  4187. }
  4188. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4189. if (!key.empty() &&
  4190. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4191. declared_trailers.insert(key);
  4192. }
  4193. });
  4194. }
  4195. size_t trailer_header_count = 0;
  4196. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4197. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4198. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4199. constexpr auto line_terminator_len = 2;
  4200. auto line_beg = line_reader.ptr();
  4201. auto line_end =
  4202. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4203. if (!parse_header(line_beg, line_end,
  4204. [&](const std::string &key, const std::string &val) {
  4205. if (declared_trailers.find(key) !=
  4206. declared_trailers.end()) {
  4207. dest.emplace(key, val);
  4208. trailer_header_count++;
  4209. }
  4210. })) {
  4211. return false;
  4212. }
  4213. if (!line_reader.getline()) { return false; }
  4214. }
  4215. return true;
  4216. }
  4217. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4218. size_t right) {
  4219. while (b + left < e && is_space_or_tab(b[left])) {
  4220. left++;
  4221. }
  4222. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4223. right--;
  4224. }
  4225. return std::make_pair(left, right);
  4226. }
  4227. inline std::string trim_copy(const std::string &s) {
  4228. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4229. return s.substr(r.first, r.second - r.first);
  4230. }
  4231. inline std::string trim_double_quotes_copy(const std::string &s) {
  4232. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4233. return s.substr(1, s.size() - 2);
  4234. }
  4235. return s;
  4236. }
  4237. inline void
  4238. divide(const char *data, std::size_t size, char d,
  4239. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4240. fn) {
  4241. const auto it = std::find(data, data + size, d);
  4242. const auto found = static_cast<std::size_t>(it != data + size);
  4243. const auto lhs_data = data;
  4244. const auto lhs_size = static_cast<std::size_t>(it - data);
  4245. const auto rhs_data = it + found;
  4246. const auto rhs_size = size - lhs_size - found;
  4247. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4248. }
  4249. inline void
  4250. divide(const std::string &str, char d,
  4251. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4252. fn) {
  4253. divide(str.data(), str.size(), d, std::move(fn));
  4254. }
  4255. inline void split(const char *b, const char *e, char d,
  4256. std::function<void(const char *, const char *)> fn) {
  4257. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4258. }
  4259. inline void split(const char *b, const char *e, char d, size_t m,
  4260. std::function<void(const char *, const char *)> fn) {
  4261. size_t i = 0;
  4262. size_t beg = 0;
  4263. size_t count = 1;
  4264. while (e ? (b + i < e) : (b[i] != '\0')) {
  4265. if (b[i] == d && count < m) {
  4266. auto r = trim(b, e, beg, i);
  4267. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4268. beg = i + 1;
  4269. count++;
  4270. }
  4271. i++;
  4272. }
  4273. if (i) {
  4274. auto r = trim(b, e, beg, i);
  4275. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4276. }
  4277. }
  4278. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4279. std::function<bool(const char *, const char *)> fn) {
  4280. size_t i = 0;
  4281. size_t beg = 0;
  4282. size_t count = 1;
  4283. while (e ? (b + i < e) : (b[i] != '\0')) {
  4284. if (b[i] == d && count < m) {
  4285. auto r = trim(b, e, beg, i);
  4286. if (r.first < r.second) {
  4287. auto found = fn(&b[r.first], &b[r.second]);
  4288. if (found) { return true; }
  4289. }
  4290. beg = i + 1;
  4291. count++;
  4292. }
  4293. i++;
  4294. }
  4295. if (i) {
  4296. auto r = trim(b, e, beg, i);
  4297. if (r.first < r.second) {
  4298. auto found = fn(&b[r.first], &b[r.second]);
  4299. if (found) { return true; }
  4300. }
  4301. }
  4302. return false;
  4303. }
  4304. inline bool split_find(const char *b, const char *e, char d,
  4305. std::function<bool(const char *, const char *)> fn) {
  4306. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4307. std::move(fn));
  4308. }
  4309. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4310. size_t fixed_buffer_size)
  4311. : strm_(strm), fixed_buffer_(fixed_buffer),
  4312. fixed_buffer_size_(fixed_buffer_size) {}
  4313. inline const char *stream_line_reader::ptr() const {
  4314. if (growable_buffer_.empty()) {
  4315. return fixed_buffer_;
  4316. } else {
  4317. return growable_buffer_.data();
  4318. }
  4319. }
  4320. inline size_t stream_line_reader::size() const {
  4321. if (growable_buffer_.empty()) {
  4322. return fixed_buffer_used_size_;
  4323. } else {
  4324. return growable_buffer_.size();
  4325. }
  4326. }
  4327. inline bool stream_line_reader::end_with_crlf() const {
  4328. auto end = ptr() + size();
  4329. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4330. }
  4331. inline bool stream_line_reader::getline() {
  4332. fixed_buffer_used_size_ = 0;
  4333. growable_buffer_.clear();
  4334. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4335. char prev_byte = 0;
  4336. #endif
  4337. for (size_t i = 0;; i++) {
  4338. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4339. // Treat exceptionally long lines as an error to
  4340. // prevent infinite loops/memory exhaustion
  4341. return false;
  4342. }
  4343. char byte;
  4344. auto n = strm_.read(&byte, 1);
  4345. if (n < 0) {
  4346. return false;
  4347. } else if (n == 0) {
  4348. if (i == 0) {
  4349. return false;
  4350. } else {
  4351. break;
  4352. }
  4353. }
  4354. append(byte);
  4355. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4356. if (byte == '\n') { break; }
  4357. #else
  4358. if (prev_byte == '\r' && byte == '\n') { break; }
  4359. prev_byte = byte;
  4360. #endif
  4361. }
  4362. return true;
  4363. }
  4364. inline void stream_line_reader::append(char c) {
  4365. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4366. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4367. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4368. } else {
  4369. if (growable_buffer_.empty()) {
  4370. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4371. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4372. }
  4373. growable_buffer_ += c;
  4374. }
  4375. }
  4376. inline mmap::mmap(const char *path) { open(path); }
  4377. inline mmap::~mmap() { close(); }
  4378. inline bool mmap::open(const char *path) {
  4379. close();
  4380. #if defined(_WIN32)
  4381. auto wpath = u8string_to_wstring(path);
  4382. if (wpath.empty()) { return false; }
  4383. hFile_ =
  4384. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4385. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4386. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4387. LARGE_INTEGER size{};
  4388. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4389. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4390. // See:
  4391. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4392. if (static_cast<ULONGLONG>(size.QuadPart) >
  4393. (std::numeric_limits<decltype(size_)>::max)()) {
  4394. // `size_t` might be 32-bits, on 32-bits Windows.
  4395. return false;
  4396. }
  4397. size_ = static_cast<size_t>(size.QuadPart);
  4398. hMapping_ =
  4399. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4400. // Special treatment for an empty file...
  4401. if (hMapping_ == NULL && size_ == 0) {
  4402. close();
  4403. is_open_empty_file = true;
  4404. return true;
  4405. }
  4406. if (hMapping_ == NULL) {
  4407. close();
  4408. return false;
  4409. }
  4410. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4411. if (addr_ == nullptr) {
  4412. close();
  4413. return false;
  4414. }
  4415. #else
  4416. fd_ = ::open(path, O_RDONLY);
  4417. if (fd_ == -1) { return false; }
  4418. struct stat sb;
  4419. if (fstat(fd_, &sb) == -1) {
  4420. close();
  4421. return false;
  4422. }
  4423. size_ = static_cast<size_t>(sb.st_size);
  4424. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4425. // Special treatment for an empty file...
  4426. if (addr_ == MAP_FAILED && size_ == 0) {
  4427. close();
  4428. is_open_empty_file = true;
  4429. return false;
  4430. }
  4431. #endif
  4432. return true;
  4433. }
  4434. inline bool mmap::is_open() const {
  4435. return is_open_empty_file ? true : addr_ != nullptr;
  4436. }
  4437. inline size_t mmap::size() const { return size_; }
  4438. inline const char *mmap::data() const {
  4439. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4440. }
  4441. inline void mmap::close() {
  4442. #if defined(_WIN32)
  4443. if (addr_) {
  4444. ::UnmapViewOfFile(addr_);
  4445. addr_ = nullptr;
  4446. }
  4447. if (hMapping_) {
  4448. ::CloseHandle(hMapping_);
  4449. hMapping_ = NULL;
  4450. }
  4451. if (hFile_ != INVALID_HANDLE_VALUE) {
  4452. ::CloseHandle(hFile_);
  4453. hFile_ = INVALID_HANDLE_VALUE;
  4454. }
  4455. is_open_empty_file = false;
  4456. #else
  4457. if (addr_ != nullptr) {
  4458. munmap(addr_, size_);
  4459. addr_ = nullptr;
  4460. }
  4461. if (fd_ != -1) {
  4462. ::close(fd_);
  4463. fd_ = -1;
  4464. }
  4465. #endif
  4466. size_ = 0;
  4467. }
  4468. inline int close_socket(socket_t sock) {
  4469. #ifdef _WIN32
  4470. return closesocket(sock);
  4471. #else
  4472. return close(sock);
  4473. #endif
  4474. }
  4475. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4476. ssize_t res = 0;
  4477. while (true) {
  4478. res = fn();
  4479. if (res < 0 && errno == EINTR) {
  4480. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4481. continue;
  4482. }
  4483. break;
  4484. }
  4485. return res;
  4486. }
  4487. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4488. return handle_EINTR([&]() {
  4489. return recv(sock,
  4490. #ifdef _WIN32
  4491. static_cast<char *>(ptr), static_cast<int>(size),
  4492. #else
  4493. ptr, size,
  4494. #endif
  4495. flags);
  4496. });
  4497. }
  4498. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4499. int flags) {
  4500. return handle_EINTR([&]() {
  4501. return send(sock,
  4502. #ifdef _WIN32
  4503. static_cast<const char *>(ptr), static_cast<int>(size),
  4504. #else
  4505. ptr, size,
  4506. #endif
  4507. flags);
  4508. });
  4509. }
  4510. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4511. #ifdef _WIN32
  4512. return ::WSAPoll(fds, nfds, timeout);
  4513. #else
  4514. return ::poll(fds, nfds, timeout);
  4515. #endif
  4516. }
  4517. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4518. time_t usec) {
  4519. struct pollfd pfd;
  4520. pfd.fd = sock;
  4521. pfd.events = events;
  4522. pfd.revents = 0;
  4523. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4524. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4525. }
  4526. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4527. return select_impl(sock, POLLIN, sec, usec);
  4528. }
  4529. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4530. return select_impl(sock, POLLOUT, sec, usec);
  4531. }
  4532. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4533. time_t usec) {
  4534. struct pollfd pfd_read;
  4535. pfd_read.fd = sock;
  4536. pfd_read.events = POLLIN | POLLOUT;
  4537. pfd_read.revents = 0;
  4538. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4539. auto poll_res =
  4540. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4541. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4542. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4543. auto error = 0;
  4544. socklen_t len = sizeof(error);
  4545. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4546. reinterpret_cast<char *>(&error), &len);
  4547. auto successful = res >= 0 && !error;
  4548. return successful ? Error::Success : Error::Connection;
  4549. }
  4550. return Error::Connection;
  4551. }
  4552. inline bool is_socket_alive(socket_t sock) {
  4553. const auto val = detail::select_read(sock, 0, 0);
  4554. if (val == 0) {
  4555. return true;
  4556. } else if (val < 0 && errno == EBADF) {
  4557. return false;
  4558. }
  4559. char buf[1];
  4560. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4561. }
  4562. class SocketStream final : public Stream {
  4563. public:
  4564. SocketStream(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 = 0,
  4567. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4568. (std::chrono::steady_clock::time_point::min)());
  4569. ~SocketStream() override;
  4570. bool is_readable() const override;
  4571. bool wait_readable() const override;
  4572. bool wait_writable() const override;
  4573. bool is_peer_alive() const override;
  4574. ssize_t read(char *ptr, size_t size) override;
  4575. ssize_t write(const char *ptr, size_t size) override;
  4576. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4577. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4578. socket_t socket() const override;
  4579. time_t duration() const override;
  4580. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4581. private:
  4582. socket_t sock_;
  4583. time_t read_timeout_sec_;
  4584. time_t read_timeout_usec_;
  4585. time_t write_timeout_sec_;
  4586. time_t write_timeout_usec_;
  4587. time_t max_timeout_msec_;
  4588. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4589. std::vector<char> read_buff_;
  4590. size_t read_buff_off_ = 0;
  4591. size_t read_buff_content_size_ = 0;
  4592. static const size_t read_buff_size_ = 1024l * 4;
  4593. };
  4594. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4595. time_t keep_alive_timeout_sec) {
  4596. using namespace std::chrono;
  4597. const auto interval_usec =
  4598. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4599. // Avoid expensive `steady_clock::now()` call for the first time
  4600. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4601. const auto start = steady_clock::now() - microseconds{interval_usec};
  4602. const auto timeout = seconds{keep_alive_timeout_sec};
  4603. while (true) {
  4604. if (svr_sock == INVALID_SOCKET) {
  4605. break; // Server socket is closed
  4606. }
  4607. auto val = select_read(sock, 0, interval_usec);
  4608. if (val < 0) {
  4609. break; // Ssocket error
  4610. } else if (val == 0) {
  4611. if (steady_clock::now() - start > timeout) {
  4612. break; // Timeout
  4613. }
  4614. } else {
  4615. return true; // Ready for read
  4616. }
  4617. }
  4618. return false;
  4619. }
  4620. template <typename T>
  4621. inline bool
  4622. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4623. size_t keep_alive_max_count,
  4624. time_t keep_alive_timeout_sec, T callback) {
  4625. assert(keep_alive_max_count > 0);
  4626. auto ret = false;
  4627. auto count = keep_alive_max_count;
  4628. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4629. auto close_connection = count == 1;
  4630. auto connection_closed = false;
  4631. ret = callback(close_connection, connection_closed);
  4632. if (!ret || connection_closed) { break; }
  4633. count--;
  4634. }
  4635. return ret;
  4636. }
  4637. template <typename T>
  4638. inline bool
  4639. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4640. size_t keep_alive_max_count,
  4641. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4642. time_t read_timeout_usec, time_t write_timeout_sec,
  4643. time_t write_timeout_usec, T callback) {
  4644. return process_server_socket_core(
  4645. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4646. [&](bool close_connection, bool &connection_closed) {
  4647. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4648. write_timeout_sec, write_timeout_usec);
  4649. return callback(strm, close_connection, connection_closed);
  4650. });
  4651. }
  4652. inline bool process_client_socket(
  4653. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4654. time_t write_timeout_sec, time_t write_timeout_usec,
  4655. time_t max_timeout_msec,
  4656. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4657. std::function<bool(Stream &)> callback) {
  4658. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4659. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4660. start_time);
  4661. return callback(strm);
  4662. }
  4663. inline int shutdown_socket(socket_t sock) {
  4664. #ifdef _WIN32
  4665. return shutdown(sock, SD_BOTH);
  4666. #else
  4667. return shutdown(sock, SHUT_RDWR);
  4668. #endif
  4669. }
  4670. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4671. if (s.size() > 1 && s[0] == '\0') {
  4672. auto ret = s;
  4673. ret[0] = '@';
  4674. return ret;
  4675. }
  4676. return s;
  4677. }
  4678. inline std::string
  4679. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4680. if (s.size() > 1 && s[0] == '@') {
  4681. auto ret = s;
  4682. ret[0] = '\0';
  4683. return ret;
  4684. }
  4685. return s;
  4686. }
  4687. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4688. const struct addrinfo *hints,
  4689. struct addrinfo **res, time_t timeout_sec) {
  4690. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4691. if (timeout_sec <= 0) {
  4692. // No timeout specified, use standard getaddrinfo
  4693. return getaddrinfo(node, service, hints, res);
  4694. }
  4695. #ifdef _WIN32
  4696. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4697. OVERLAPPED overlapped = {0};
  4698. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4699. if (!event) { return EAI_FAIL; }
  4700. overlapped.hEvent = event;
  4701. PADDRINFOEXW result_addrinfo = nullptr;
  4702. HANDLE cancel_handle = nullptr;
  4703. ADDRINFOEXW hints_ex = {0};
  4704. if (hints) {
  4705. hints_ex.ai_flags = hints->ai_flags;
  4706. hints_ex.ai_family = hints->ai_family;
  4707. hints_ex.ai_socktype = hints->ai_socktype;
  4708. hints_ex.ai_protocol = hints->ai_protocol;
  4709. }
  4710. auto wnode = u8string_to_wstring(node);
  4711. auto wservice = u8string_to_wstring(service);
  4712. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4713. hints ? &hints_ex : nullptr, &result_addrinfo,
  4714. nullptr, &overlapped, nullptr, &cancel_handle);
  4715. if (ret == WSA_IO_PENDING) {
  4716. auto wait_result =
  4717. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4718. if (wait_result == WAIT_TIMEOUT) {
  4719. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4720. ::CloseHandle(event);
  4721. return EAI_AGAIN;
  4722. }
  4723. DWORD bytes_returned;
  4724. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4725. &bytes_returned, FALSE)) {
  4726. ::CloseHandle(event);
  4727. return ::WSAGetLastError();
  4728. }
  4729. }
  4730. ::CloseHandle(event);
  4731. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4732. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4733. return 0;
  4734. }
  4735. return ret;
  4736. #elif TARGET_OS_MAC && defined(__clang__)
  4737. if (!node) { return EAI_NONAME; }
  4738. // macOS implementation using CFHost API for asynchronous DNS resolution
  4739. CFStringRef hostname_ref = CFStringCreateWithCString(
  4740. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4741. if (!hostname_ref) { return EAI_MEMORY; }
  4742. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4743. CFRelease(hostname_ref);
  4744. if (!host_ref) { return EAI_MEMORY; }
  4745. // Set up context for callback
  4746. struct CFHostContext {
  4747. bool completed = false;
  4748. bool success = false;
  4749. CFArrayRef addresses = nullptr;
  4750. std::mutex mutex;
  4751. std::condition_variable cv;
  4752. } context;
  4753. CFHostClientContext client_context;
  4754. memset(&client_context, 0, sizeof(client_context));
  4755. client_context.info = &context;
  4756. // Set callback
  4757. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4758. const CFStreamError *error, void *info) {
  4759. auto ctx = static_cast<CFHostContext *>(info);
  4760. std::lock_guard<std::mutex> lock(ctx->mutex);
  4761. if (error && error->error != 0) {
  4762. ctx->success = false;
  4763. } else {
  4764. Boolean hasBeenResolved;
  4765. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4766. if (ctx->addresses && hasBeenResolved) {
  4767. CFRetain(ctx->addresses);
  4768. ctx->success = true;
  4769. } else {
  4770. ctx->success = false;
  4771. }
  4772. }
  4773. ctx->completed = true;
  4774. ctx->cv.notify_one();
  4775. };
  4776. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4777. CFRelease(host_ref);
  4778. return EAI_SYSTEM;
  4779. }
  4780. // Schedule on run loop
  4781. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4782. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4783. // Start resolution
  4784. CFStreamError stream_error;
  4785. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4786. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4787. CFRelease(host_ref);
  4788. return EAI_FAIL;
  4789. }
  4790. // Wait for completion with timeout
  4791. auto timeout_time =
  4792. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4793. bool timed_out = false;
  4794. {
  4795. std::unique_lock<std::mutex> lock(context.mutex);
  4796. while (!context.completed) {
  4797. auto now = std::chrono::steady_clock::now();
  4798. if (now >= timeout_time) {
  4799. timed_out = true;
  4800. break;
  4801. }
  4802. // Run the runloop for a short time
  4803. lock.unlock();
  4804. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4805. lock.lock();
  4806. }
  4807. }
  4808. // Clean up
  4809. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4810. CFHostSetClient(host_ref, nullptr, nullptr);
  4811. if (timed_out || !context.completed) {
  4812. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4813. CFRelease(host_ref);
  4814. return EAI_AGAIN;
  4815. }
  4816. if (!context.success || !context.addresses) {
  4817. CFRelease(host_ref);
  4818. return EAI_NODATA;
  4819. }
  4820. // Convert CFArray to addrinfo
  4821. CFIndex count = CFArrayGetCount(context.addresses);
  4822. if (count == 0) {
  4823. CFRelease(context.addresses);
  4824. CFRelease(host_ref);
  4825. return EAI_NODATA;
  4826. }
  4827. struct addrinfo *result_addrinfo = nullptr;
  4828. struct addrinfo **current = &result_addrinfo;
  4829. for (CFIndex i = 0; i < count; i++) {
  4830. CFDataRef addr_data =
  4831. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4832. if (!addr_data) continue;
  4833. const struct sockaddr *sockaddr_ptr =
  4834. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4835. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4836. // Allocate addrinfo structure
  4837. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4838. if (!*current) {
  4839. freeaddrinfo(result_addrinfo);
  4840. CFRelease(context.addresses);
  4841. CFRelease(host_ref);
  4842. return EAI_MEMORY;
  4843. }
  4844. memset(*current, 0, sizeof(struct addrinfo));
  4845. // Set up addrinfo fields
  4846. (*current)->ai_family = sockaddr_ptr->sa_family;
  4847. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4848. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4849. (*current)->ai_addrlen = sockaddr_len;
  4850. // Copy sockaddr
  4851. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4852. if (!(*current)->ai_addr) {
  4853. freeaddrinfo(result_addrinfo);
  4854. CFRelease(context.addresses);
  4855. CFRelease(host_ref);
  4856. return EAI_MEMORY;
  4857. }
  4858. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4859. // Set port if service is specified
  4860. if (service && *service) {
  4861. int port = 0;
  4862. if (parse_port(service, strlen(service), port)) {
  4863. if (sockaddr_ptr->sa_family == AF_INET) {
  4864. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4865. ->sin_port = htons(static_cast<uint16_t>(port));
  4866. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4867. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4868. ->sin6_port = htons(static_cast<uint16_t>(port));
  4869. }
  4870. }
  4871. }
  4872. current = &((*current)->ai_next);
  4873. }
  4874. CFRelease(context.addresses);
  4875. CFRelease(host_ref);
  4876. *res = result_addrinfo;
  4877. return 0;
  4878. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  4879. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  4880. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  4881. // the resolver worker still references the stack-local gaicb. The cancel
  4882. // path therefore waits (gai_suspend with no timeout) for the worker to
  4883. // actually finish before letting the stack frame go. The trade-off is that
  4884. // a wedged DNS server can hold this thread for the system resolver timeout
  4885. // (~30s by default) past the caller's connection timeout.
  4886. struct gaicb request {};
  4887. struct gaicb *requests[1] = {&request};
  4888. struct sigevent sevp {};
  4889. struct timespec timeout {
  4890. timeout_sec, 0
  4891. };
  4892. request.ar_name = node;
  4893. request.ar_service = service;
  4894. request.ar_request = hints;
  4895. sevp.sigev_notify = SIGEV_NONE;
  4896. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  4897. if (rc != 0) { return rc; }
  4898. auto cleanup = scope_exit([&] {
  4899. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  4900. });
  4901. int wait_result = gai_suspend(requests, 1, &timeout);
  4902. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  4903. int gai_result = gai_error(&request);
  4904. if (gai_result == 0) {
  4905. *res = request.ar_result;
  4906. request.ar_result = nullptr;
  4907. return 0;
  4908. }
  4909. return gai_result;
  4910. }
  4911. gai_cancel(&request);
  4912. while (gai_error(&request) == EAI_INPROGRESS) {
  4913. gai_suspend(requests, 1, nullptr);
  4914. }
  4915. return wait_result;
  4916. #else
  4917. // Fallback implementation using thread-based timeout for other Unix systems.
  4918. struct GetAddrInfoState {
  4919. ~GetAddrInfoState() {
  4920. if (info) { freeaddrinfo(info); }
  4921. }
  4922. std::mutex mutex;
  4923. std::condition_variable result_cv;
  4924. bool completed = false;
  4925. int result = EAI_SYSTEM;
  4926. std::string node;
  4927. std::string service;
  4928. struct addrinfo hints;
  4929. struct addrinfo *info = nullptr;
  4930. };
  4931. // Allocate on the heap, so the resolver thread can keep using the data.
  4932. auto state = std::make_shared<GetAddrInfoState>();
  4933. if (node) { state->node = node; }
  4934. state->service = service;
  4935. state->hints = *hints;
  4936. std::thread resolve_thread([state]() {
  4937. auto thread_result =
  4938. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4939. &state->info);
  4940. std::lock_guard<std::mutex> lock(state->mutex);
  4941. state->result = thread_result;
  4942. state->completed = true;
  4943. state->result_cv.notify_one();
  4944. });
  4945. // Wait for completion or timeout
  4946. std::unique_lock<std::mutex> lock(state->mutex);
  4947. auto finished =
  4948. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4949. [&] { return state->completed; });
  4950. if (finished) {
  4951. // Operation completed within timeout
  4952. resolve_thread.join();
  4953. *res = state->info;
  4954. state->info = nullptr; // Pass ownership to caller
  4955. return state->result;
  4956. } else {
  4957. // Timeout occurred
  4958. resolve_thread.detach(); // Let the thread finish in background
  4959. return EAI_AGAIN; // Return timeout error
  4960. }
  4961. #endif
  4962. #else
  4963. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4964. return getaddrinfo(node, service, hints, res);
  4965. #endif
  4966. }
  4967. template <typename BindOrConnect>
  4968. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4969. int address_family, int socket_flags, bool tcp_nodelay,
  4970. bool ipv6_v6only, SocketOptions socket_options,
  4971. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4972. // Get address info
  4973. const char *node = nullptr;
  4974. struct addrinfo hints;
  4975. struct addrinfo *result;
  4976. memset(&hints, 0, sizeof(struct addrinfo));
  4977. hints.ai_socktype = SOCK_STREAM;
  4978. hints.ai_protocol = IPPROTO_IP;
  4979. if (!ip.empty()) {
  4980. node = ip.c_str();
  4981. // Ask getaddrinfo to convert IP in c-string to address
  4982. hints.ai_family = AF_UNSPEC;
  4983. hints.ai_flags = AI_NUMERICHOST;
  4984. } else {
  4985. if (!host.empty()) { node = host.c_str(); }
  4986. hints.ai_family = address_family;
  4987. hints.ai_flags = socket_flags;
  4988. }
  4989. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  4990. if (hints.ai_family == AF_UNIX) {
  4991. const auto addrlen = host.length();
  4992. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  4993. #ifdef SOCK_CLOEXEC
  4994. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  4995. hints.ai_protocol);
  4996. #else
  4997. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4998. #endif
  4999. if (sock != INVALID_SOCKET) {
  5000. sockaddr_un addr{};
  5001. addr.sun_family = AF_UNIX;
  5002. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5003. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5004. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5005. hints.ai_addrlen = static_cast<socklen_t>(
  5006. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5007. #ifndef SOCK_CLOEXEC
  5008. #ifndef _WIN32
  5009. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5010. #endif
  5011. #endif
  5012. if (socket_options) { socket_options(sock); }
  5013. #ifdef _WIN32
  5014. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5015. // remove the option.
  5016. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5017. #endif
  5018. bool dummy;
  5019. if (!bind_or_connect(sock, hints, dummy)) {
  5020. close_socket(sock);
  5021. sock = INVALID_SOCKET;
  5022. }
  5023. }
  5024. return sock;
  5025. }
  5026. #endif
  5027. auto service = std::to_string(port);
  5028. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5029. timeout_sec)) {
  5030. #if defined __linux__ && !defined __ANDROID__
  5031. res_init();
  5032. #endif
  5033. return INVALID_SOCKET;
  5034. }
  5035. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5036. for (auto rp = result; rp; rp = rp->ai_next) {
  5037. // Create a socket
  5038. #ifdef _WIN32
  5039. auto sock =
  5040. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5041. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5042. /**
  5043. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5044. * and above the socket creation fails on older Windows Systems.
  5045. *
  5046. * Let's try to create a socket the old way in this case.
  5047. *
  5048. * Reference:
  5049. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5050. *
  5051. * WSA_FLAG_NO_HANDLE_INHERIT:
  5052. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5053. * SP1, and later
  5054. *
  5055. */
  5056. if (sock == INVALID_SOCKET) {
  5057. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5058. }
  5059. #else
  5060. #ifdef SOCK_CLOEXEC
  5061. auto sock =
  5062. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5063. #else
  5064. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5065. #endif
  5066. #endif
  5067. if (sock == INVALID_SOCKET) { continue; }
  5068. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5069. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5070. close_socket(sock);
  5071. continue;
  5072. }
  5073. #endif
  5074. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5075. if (rp->ai_family == AF_INET6) {
  5076. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5077. }
  5078. if (socket_options) { socket_options(sock); }
  5079. // bind or connect
  5080. auto quit = false;
  5081. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5082. close_socket(sock);
  5083. if (quit) { break; }
  5084. }
  5085. return INVALID_SOCKET;
  5086. }
  5087. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5088. #ifdef _WIN32
  5089. auto flags = nonblocking ? 1UL : 0UL;
  5090. ioctlsocket(sock, FIONBIO, &flags);
  5091. #else
  5092. auto flags = fcntl(sock, F_GETFL, 0);
  5093. fcntl(sock, F_SETFL,
  5094. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5095. #endif
  5096. }
  5097. inline bool is_connection_error() {
  5098. #ifdef _WIN32
  5099. return WSAGetLastError() != WSAEWOULDBLOCK;
  5100. #else
  5101. return errno != EINPROGRESS;
  5102. #endif
  5103. }
  5104. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5105. struct addrinfo hints;
  5106. struct addrinfo *result;
  5107. memset(&hints, 0, sizeof(struct addrinfo));
  5108. hints.ai_family = AF_UNSPEC;
  5109. hints.ai_socktype = SOCK_STREAM;
  5110. hints.ai_protocol = 0;
  5111. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5112. return false;
  5113. }
  5114. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5115. auto ret = false;
  5116. for (auto rp = result; rp; rp = rp->ai_next) {
  5117. const auto &ai = *rp;
  5118. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5119. ret = true;
  5120. break;
  5121. }
  5122. }
  5123. return ret;
  5124. }
  5125. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5126. #define USE_IF2IP
  5127. #endif
  5128. #ifdef USE_IF2IP
  5129. inline std::string if2ip(int address_family, const std::string &ifn) {
  5130. struct ifaddrs *ifap;
  5131. getifaddrs(&ifap);
  5132. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5133. std::string addr_candidate;
  5134. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5135. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5136. (AF_UNSPEC == address_family ||
  5137. ifa->ifa_addr->sa_family == address_family)) {
  5138. if (ifa->ifa_addr->sa_family == AF_INET) {
  5139. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5140. char buf[INET_ADDRSTRLEN];
  5141. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5142. return std::string(buf, INET_ADDRSTRLEN);
  5143. }
  5144. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5145. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5146. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5147. char buf[INET6_ADDRSTRLEN] = {};
  5148. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5149. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5150. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5151. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5152. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5153. } else {
  5154. return std::string(buf, INET6_ADDRSTRLEN);
  5155. }
  5156. }
  5157. }
  5158. }
  5159. }
  5160. }
  5161. return addr_candidate;
  5162. }
  5163. #endif
  5164. inline socket_t create_client_socket(
  5165. const std::string &host, const std::string &ip, int port,
  5166. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5167. SocketOptions socket_options, time_t connection_timeout_sec,
  5168. time_t connection_timeout_usec, time_t read_timeout_sec,
  5169. time_t read_timeout_usec, time_t write_timeout_sec,
  5170. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5171. auto sock = create_socket(
  5172. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5173. std::move(socket_options),
  5174. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5175. if (!intf.empty()) {
  5176. #ifdef USE_IF2IP
  5177. auto ip_from_if = if2ip(address_family, intf);
  5178. if (ip_from_if.empty()) { ip_from_if = intf; }
  5179. if (!bind_ip_address(sock2, ip_from_if)) {
  5180. error = Error::BindIPAddress;
  5181. return false;
  5182. }
  5183. #endif
  5184. }
  5185. set_nonblocking(sock2, true);
  5186. auto ret =
  5187. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5188. if (ret < 0) {
  5189. if (is_connection_error()) {
  5190. error = Error::Connection;
  5191. return false;
  5192. }
  5193. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5194. connection_timeout_usec);
  5195. if (error != Error::Success) {
  5196. if (error == Error::ConnectionTimeout) { quit = true; }
  5197. return false;
  5198. }
  5199. }
  5200. set_nonblocking(sock2, false);
  5201. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5202. read_timeout_usec);
  5203. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5204. write_timeout_usec);
  5205. error = Error::Success;
  5206. return true;
  5207. },
  5208. connection_timeout_sec); // Pass DNS timeout
  5209. if (sock != INVALID_SOCKET) {
  5210. error = Error::Success;
  5211. } else {
  5212. if (error == Error::Success) { error = Error::Connection; }
  5213. }
  5214. return sock;
  5215. }
  5216. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5217. socklen_t addr_len, std::string &ip, int &port) {
  5218. if (addr.ss_family == AF_INET) {
  5219. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5220. } else if (addr.ss_family == AF_INET6) {
  5221. port =
  5222. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5223. } else {
  5224. return false;
  5225. }
  5226. std::array<char, NI_MAXHOST> ipstr{};
  5227. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5228. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5229. 0, NI_NUMERICHOST)) {
  5230. return false;
  5231. }
  5232. ip = ipstr.data();
  5233. return true;
  5234. }
  5235. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5236. struct sockaddr_storage addr;
  5237. socklen_t addr_len = sizeof(addr);
  5238. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5239. &addr_len)) {
  5240. get_ip_and_port(addr, addr_len, ip, port);
  5241. }
  5242. }
  5243. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5244. struct sockaddr_storage addr;
  5245. socklen_t addr_len = sizeof(addr);
  5246. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5247. &addr_len)) {
  5248. #ifndef _WIN32
  5249. if (addr.ss_family == AF_UNIX) {
  5250. #if defined(__linux__)
  5251. struct ucred ucred;
  5252. socklen_t len = sizeof(ucred);
  5253. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5254. port = ucred.pid;
  5255. }
  5256. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5257. pid_t pid;
  5258. socklen_t len = sizeof(pid);
  5259. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5260. port = pid;
  5261. }
  5262. #endif
  5263. return;
  5264. }
  5265. #endif
  5266. get_ip_and_port(addr, addr_len, ip, port);
  5267. }
  5268. }
  5269. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5270. unsigned int h) {
  5271. return (l == 0)
  5272. ? h
  5273. : str2tag_core(
  5274. s + 1, l - 1,
  5275. // Unsets the 6 high bits of h, therefore no overflow happens
  5276. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5277. h * 33) ^
  5278. static_cast<unsigned char>(*s));
  5279. }
  5280. inline unsigned int str2tag(const std::string &s) {
  5281. return str2tag_core(s.data(), s.size(), 0);
  5282. }
  5283. namespace udl {
  5284. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5285. return str2tag_core(s, l, 0);
  5286. }
  5287. } // namespace udl
  5288. inline std::string
  5289. find_content_type(const std::string &path,
  5290. const std::map<std::string, std::string> &user_data,
  5291. const std::string &default_content_type) {
  5292. auto ext = file_extension(path);
  5293. auto it = user_data.find(ext);
  5294. if (it != user_data.end()) { return it->second; }
  5295. using udl::operator""_t;
  5296. switch (str2tag(ext)) {
  5297. default: return default_content_type;
  5298. case "css"_t: return "text/css";
  5299. case "csv"_t: return "text/csv";
  5300. case "htm"_t:
  5301. case "html"_t: return "text/html";
  5302. case "js"_t:
  5303. case "mjs"_t: return "text/javascript";
  5304. case "txt"_t: return "text/plain";
  5305. case "vtt"_t: return "text/vtt";
  5306. case "apng"_t: return "image/apng";
  5307. case "avif"_t: return "image/avif";
  5308. case "bmp"_t: return "image/bmp";
  5309. case "gif"_t: return "image/gif";
  5310. case "png"_t: return "image/png";
  5311. case "svg"_t: return "image/svg+xml";
  5312. case "webp"_t: return "image/webp";
  5313. case "ico"_t: return "image/x-icon";
  5314. case "tif"_t: return "image/tiff";
  5315. case "tiff"_t: return "image/tiff";
  5316. case "jpg"_t:
  5317. case "jpeg"_t: return "image/jpeg";
  5318. case "mp4"_t: return "video/mp4";
  5319. case "mpeg"_t: return "video/mpeg";
  5320. case "webm"_t: return "video/webm";
  5321. case "mp3"_t: return "audio/mp3";
  5322. case "mpga"_t: return "audio/mpeg";
  5323. case "weba"_t: return "audio/webm";
  5324. case "wav"_t: return "audio/wave";
  5325. case "otf"_t: return "font/otf";
  5326. case "ttf"_t: return "font/ttf";
  5327. case "woff"_t: return "font/woff";
  5328. case "woff2"_t: return "font/woff2";
  5329. case "7z"_t: return "application/x-7z-compressed";
  5330. case "atom"_t: return "application/atom+xml";
  5331. case "pdf"_t: return "application/pdf";
  5332. case "json"_t: return "application/json";
  5333. case "rss"_t: return "application/rss+xml";
  5334. case "tar"_t: return "application/x-tar";
  5335. case "xht"_t:
  5336. case "xhtml"_t: return "application/xhtml+xml";
  5337. case "xslt"_t: return "application/xslt+xml";
  5338. case "xml"_t: return "application/xml";
  5339. case "gz"_t: return "application/gzip";
  5340. case "zip"_t: return "application/zip";
  5341. case "wasm"_t: return "application/wasm";
  5342. }
  5343. }
  5344. inline std::string
  5345. extract_media_type(const std::string &content_type,
  5346. std::map<std::string, std::string> *params = nullptr) {
  5347. // Extract type/subtype from Content-Type value (RFC 2045)
  5348. // e.g. "application/json; charset=utf-8" -> "application/json"
  5349. auto media_type = content_type;
  5350. auto semicolon_pos = media_type.find(';');
  5351. if (semicolon_pos != std::string::npos) {
  5352. auto param_str = media_type.substr(semicolon_pos + 1);
  5353. media_type = media_type.substr(0, semicolon_pos);
  5354. if (params) {
  5355. // Parse parameters: key=value pairs separated by ';'
  5356. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5357. [&](const char *b, const char *e) {
  5358. std::string key;
  5359. std::string val;
  5360. split(b, e, '=', [&](const char *b2, const char *e2) {
  5361. if (key.empty()) {
  5362. key.assign(b2, e2);
  5363. } else {
  5364. val.assign(b2, e2);
  5365. }
  5366. });
  5367. if (!key.empty()) {
  5368. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5369. }
  5370. });
  5371. }
  5372. }
  5373. // Trim whitespace from media type
  5374. return trim_copy(media_type);
  5375. }
  5376. inline bool can_compress_content_type(const std::string &content_type) {
  5377. using udl::operator""_t;
  5378. auto mime_type = extract_media_type(content_type);
  5379. auto tag = str2tag(mime_type);
  5380. switch (tag) {
  5381. case "image/svg+xml"_t:
  5382. case "application/javascript"_t:
  5383. case "application/x-javascript"_t:
  5384. case "application/json"_t:
  5385. case "application/ld+json"_t:
  5386. case "application/xml"_t:
  5387. case "application/xhtml+xml"_t:
  5388. case "application/rss+xml"_t:
  5389. case "application/atom+xml"_t:
  5390. case "application/xslt+xml"_t:
  5391. case "application/protobuf"_t: return true;
  5392. case "text/event-stream"_t: return false;
  5393. default: return !mime_type.rfind("text/", 0);
  5394. }
  5395. }
  5396. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5397. double &quality) {
  5398. quality = 1.0;
  5399. token.clear();
  5400. // Split on first ';': left = token name, right = parameters
  5401. const char *params_b = nullptr;
  5402. std::size_t params_len = 0;
  5403. divide(
  5404. b, static_cast<std::size_t>(e - b), ';',
  5405. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5406. auto r = trim(lb, lb + llen, 0, llen);
  5407. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5408. params_b = rb;
  5409. params_len = rlen;
  5410. });
  5411. if (token.empty()) { return false; }
  5412. if (params_len == 0) { return true; }
  5413. // Scan parameters for q= (stops on first match)
  5414. bool invalid = false;
  5415. split_find(params_b, params_b + params_len, ';',
  5416. (std::numeric_limits<size_t>::max)(),
  5417. [&](const char *pb, const char *pe) -> bool {
  5418. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5419. auto len = static_cast<size_t>(pe - pb);
  5420. if (len < 2) { return false; }
  5421. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5422. return false;
  5423. }
  5424. // Trim the value portion
  5425. auto r = trim(pb, pe, 2, len);
  5426. if (r.first >= r.second) {
  5427. invalid = true;
  5428. return true;
  5429. }
  5430. double v = 0.0;
  5431. auto res = from_chars(pb + r.first, pb + r.second, v);
  5432. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5433. invalid = true;
  5434. return true;
  5435. }
  5436. quality = v;
  5437. return true;
  5438. });
  5439. return !invalid;
  5440. }
  5441. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5442. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5443. return EncodingType::None;
  5444. }
  5445. const auto &s = req.get_header_value("Accept-Encoding");
  5446. if (s.empty()) { return EncodingType::None; }
  5447. // Single-pass: iterate tokens and track the best supported encoding.
  5448. // Server preference breaks ties (br > gzip > zstd).
  5449. EncodingType best = EncodingType::None;
  5450. double best_q = 0.0; // q=0 means "not acceptable"
  5451. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5452. auto priority = [](EncodingType t) -> int {
  5453. switch (t) {
  5454. case EncodingType::Brotli: return 0;
  5455. case EncodingType::Gzip: return 1;
  5456. case EncodingType::Zstd: return 2;
  5457. default: return 3;
  5458. }
  5459. };
  5460. std::string name;
  5461. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5462. double quality = 1.0;
  5463. if (!parse_quality(b, e, name, quality)) { return; }
  5464. if (quality <= 0.0) { return; }
  5465. EncodingType type = EncodingType::None;
  5466. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5467. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5468. #endif
  5469. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5470. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5471. type = EncodingType::Gzip;
  5472. }
  5473. #endif
  5474. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5475. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5476. type = EncodingType::Zstd;
  5477. }
  5478. #endif
  5479. if (type == EncodingType::None) { return; }
  5480. // Higher q-value wins; for equal q, server preference breaks ties
  5481. if (quality > best_q ||
  5482. (quality == best_q && priority(type) < priority(best))) {
  5483. best_q = quality;
  5484. best = type;
  5485. }
  5486. });
  5487. return best;
  5488. }
  5489. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  5490. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5491. if (type == EncodingType::Gzip) {
  5492. return detail::make_unique<gzip_compressor>();
  5493. }
  5494. #endif
  5495. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5496. if (type == EncodingType::Brotli) {
  5497. return detail::make_unique<brotli_compressor>();
  5498. }
  5499. #endif
  5500. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5501. if (type == EncodingType::Zstd) {
  5502. return detail::make_unique<zstd_compressor>();
  5503. }
  5504. #endif
  5505. (void)type;
  5506. return nullptr;
  5507. }
  5508. inline const char *encoding_name(EncodingType type) {
  5509. switch (type) {
  5510. case EncodingType::Gzip: return "gzip";
  5511. case EncodingType::Brotli: return "br";
  5512. case EncodingType::Zstd: return "zstd";
  5513. default: return "";
  5514. }
  5515. }
  5516. inline bool nocompressor::compress(const char *data, size_t data_length,
  5517. bool /*last*/, Callback callback) {
  5518. if (!data_length) { return true; }
  5519. return callback(data, data_length);
  5520. }
  5521. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5522. inline gzip_compressor::gzip_compressor() {
  5523. std::memset(&strm_, 0, sizeof(strm_));
  5524. strm_.zalloc = Z_NULL;
  5525. strm_.zfree = Z_NULL;
  5526. strm_.opaque = Z_NULL;
  5527. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5528. Z_DEFAULT_STRATEGY) == Z_OK;
  5529. }
  5530. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5531. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5532. bool last, Callback callback) {
  5533. assert(is_valid_);
  5534. do {
  5535. constexpr size_t max_avail_in =
  5536. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5537. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5538. (std::min)(data_length, max_avail_in));
  5539. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5540. data_length -= strm_.avail_in;
  5541. data += strm_.avail_in;
  5542. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5543. auto ret = Z_OK;
  5544. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5545. do {
  5546. strm_.avail_out = static_cast<uInt>(buff.size());
  5547. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5548. ret = deflate(&strm_, flush);
  5549. if (ret == Z_STREAM_ERROR) { return false; }
  5550. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5551. return false;
  5552. }
  5553. } while (strm_.avail_out == 0);
  5554. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5555. (flush == Z_NO_FLUSH && ret == Z_OK));
  5556. assert(strm_.avail_in == 0);
  5557. } while (data_length > 0);
  5558. return true;
  5559. }
  5560. inline gzip_decompressor::gzip_decompressor() {
  5561. std::memset(&strm_, 0, sizeof(strm_));
  5562. strm_.zalloc = Z_NULL;
  5563. strm_.zfree = Z_NULL;
  5564. strm_.opaque = Z_NULL;
  5565. // 15 is the value of wbits, which should be at the maximum possible value
  5566. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5567. // that the stream type should be automatically detected either gzip or
  5568. // deflate.
  5569. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5570. }
  5571. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5572. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5573. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5574. Callback callback) {
  5575. assert(is_valid_);
  5576. auto ret = Z_OK;
  5577. do {
  5578. constexpr size_t max_avail_in =
  5579. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5580. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5581. (std::min)(data_length, max_avail_in));
  5582. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5583. data_length -= strm_.avail_in;
  5584. data += strm_.avail_in;
  5585. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5586. while (strm_.avail_in > 0 && ret == Z_OK) {
  5587. strm_.avail_out = static_cast<uInt>(buff.size());
  5588. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5589. ret = inflate(&strm_, Z_NO_FLUSH);
  5590. assert(ret != Z_STREAM_ERROR);
  5591. switch (ret) {
  5592. case Z_NEED_DICT:
  5593. case Z_DATA_ERROR:
  5594. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5595. }
  5596. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5597. return false;
  5598. }
  5599. }
  5600. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5601. } while (data_length > 0);
  5602. return true;
  5603. }
  5604. #endif
  5605. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5606. inline brotli_compressor::brotli_compressor() {
  5607. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5608. }
  5609. inline brotli_compressor::~brotli_compressor() {
  5610. BrotliEncoderDestroyInstance(state_);
  5611. }
  5612. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5613. bool last, Callback callback) {
  5614. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5615. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5616. auto available_in = data_length;
  5617. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5618. for (;;) {
  5619. if (last) {
  5620. if (BrotliEncoderIsFinished(state_)) { break; }
  5621. } else {
  5622. if (!available_in) { break; }
  5623. }
  5624. auto available_out = buff.size();
  5625. auto next_out = buff.data();
  5626. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5627. &available_out, &next_out, nullptr)) {
  5628. return false;
  5629. }
  5630. auto output_bytes = buff.size() - available_out;
  5631. if (output_bytes) {
  5632. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5633. }
  5634. }
  5635. return true;
  5636. }
  5637. inline brotli_decompressor::brotli_decompressor() {
  5638. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5639. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5640. : BROTLI_DECODER_RESULT_ERROR;
  5641. }
  5642. inline brotli_decompressor::~brotli_decompressor() {
  5643. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5644. }
  5645. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5646. inline bool brotli_decompressor::decompress(const char *data,
  5647. size_t data_length,
  5648. Callback callback) {
  5649. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5650. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5651. return 0;
  5652. }
  5653. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5654. size_t avail_in = data_length;
  5655. size_t total_out;
  5656. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5657. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5658. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5659. char *next_out = buff.data();
  5660. size_t avail_out = buff.size();
  5661. decoder_r = BrotliDecoderDecompressStream(
  5662. decoder_s, &avail_in, &next_in, &avail_out,
  5663. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5664. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5665. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5666. }
  5667. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5668. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5669. }
  5670. #endif
  5671. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5672. inline zstd_compressor::zstd_compressor() {
  5673. ctx_ = ZSTD_createCCtx();
  5674. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5675. }
  5676. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5677. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5678. bool last, Callback callback) {
  5679. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5680. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5681. ZSTD_inBuffer input = {data, data_length, 0};
  5682. bool finished;
  5683. do {
  5684. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5685. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5686. if (ZSTD_isError(remaining)) { return false; }
  5687. if (!callback(buff.data(), output.pos)) { return false; }
  5688. finished = last ? (remaining == 0) : (input.pos == input.size);
  5689. } while (!finished);
  5690. return true;
  5691. }
  5692. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5693. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5694. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5695. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5696. Callback callback) {
  5697. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5698. ZSTD_inBuffer input = {data, data_length, 0};
  5699. while (input.pos < input.size) {
  5700. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5701. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5702. if (ZSTD_isError(remaining)) { return false; }
  5703. if (!callback(buff.data(), output.pos)) { return false; }
  5704. }
  5705. return true;
  5706. }
  5707. #endif
  5708. inline std::unique_ptr<decompressor>
  5709. create_decompressor(const std::string &encoding) {
  5710. std::unique_ptr<decompressor> decompressor;
  5711. if (encoding == "gzip" || encoding == "deflate") {
  5712. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5713. decompressor = detail::make_unique<gzip_decompressor>();
  5714. #endif
  5715. } else if (encoding.find("br") != std::string::npos) {
  5716. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5717. decompressor = detail::make_unique<brotli_decompressor>();
  5718. #endif
  5719. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5720. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5721. decompressor = detail::make_unique<zstd_decompressor>();
  5722. #endif
  5723. }
  5724. return decompressor;
  5725. }
  5726. // Returns the best available compressor and its Content-Encoding name.
  5727. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5728. inline std::pair<std::unique_ptr<compressor>, const char *>
  5729. create_compressor() {
  5730. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5731. return {detail::make_unique<brotli_compressor>(), "br"};
  5732. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5733. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5734. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5735. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5736. #else
  5737. return {nullptr, nullptr};
  5738. #endif
  5739. }
  5740. inline bool is_prohibited_header_name(const std::string &name) {
  5741. using udl::operator""_t;
  5742. switch (str2tag(name)) {
  5743. case "REMOTE_ADDR"_t:
  5744. case "REMOTE_PORT"_t:
  5745. case "LOCAL_ADDR"_t:
  5746. case "LOCAL_PORT"_t: return true;
  5747. default: return false;
  5748. }
  5749. }
  5750. inline bool has_header(const Headers &headers, const std::string &key) {
  5751. if (is_prohibited_header_name(key)) { return false; }
  5752. return headers.find(key) != headers.end();
  5753. }
  5754. inline const char *get_header_value(const Headers &headers,
  5755. const std::string &key, const char *def,
  5756. size_t id) {
  5757. if (is_prohibited_header_name(key)) {
  5758. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5759. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5760. throw std::invalid_argument(msg);
  5761. #else
  5762. return "";
  5763. #endif
  5764. }
  5765. auto rng = headers.equal_range(key);
  5766. auto it = rng.first;
  5767. std::advance(it, static_cast<ssize_t>(id));
  5768. if (it != rng.second) { return it->second.c_str(); }
  5769. return def;
  5770. }
  5771. inline size_t get_header_value_count(const Headers &headers,
  5772. const std::string &key) {
  5773. auto r = headers.equal_range(key);
  5774. return static_cast<size_t>(std::distance(r.first, r.second));
  5775. }
  5776. template <typename Map>
  5777. inline typename Map::mapped_type
  5778. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  5779. auto rng = m.equal_range(key);
  5780. auto it = rng.first;
  5781. std::advance(it, static_cast<ssize_t>(id));
  5782. if (it != rng.second) { return it->second; }
  5783. return typename Map::mapped_type();
  5784. }
  5785. inline void set_header(Headers &headers, const std::string &key,
  5786. const std::string &val) {
  5787. if (fields::is_field_name(key) && fields::is_field_value(val)) {
  5788. headers.emplace(key, val);
  5789. }
  5790. }
  5791. inline bool read_headers(Stream &strm, Headers &headers) {
  5792. const auto bufsiz = 2048;
  5793. char buf[bufsiz];
  5794. stream_line_reader line_reader(strm, buf, bufsiz);
  5795. size_t header_count = 0;
  5796. for (;;) {
  5797. if (!line_reader.getline()) { return false; }
  5798. // Check if the line ends with CRLF.
  5799. auto line_terminator_len = 2;
  5800. if (line_reader.end_with_crlf()) {
  5801. // Blank line indicates end of headers.
  5802. if (line_reader.size() == 2) { break; }
  5803. } else {
  5804. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5805. // Blank line indicates end of headers.
  5806. if (line_reader.size() == 1) { break; }
  5807. line_terminator_len = 1;
  5808. #else
  5809. continue; // Skip invalid line.
  5810. #endif
  5811. }
  5812. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5813. // Check header count limit
  5814. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5815. // Exclude line terminator
  5816. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5817. if (!parse_header(line_reader.ptr(), end,
  5818. [&](const std::string &key, const std::string &val) {
  5819. headers.emplace(key, val);
  5820. })) {
  5821. return false;
  5822. }
  5823. header_count++;
  5824. }
  5825. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5826. // headers that have different values to prevent request smuggling.
  5827. auto cl_range = headers.equal_range("Content-Length");
  5828. if (cl_range.first != cl_range.second) {
  5829. const auto &first_val = cl_range.first->second;
  5830. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5831. if (it->second != first_val) { return false; }
  5832. }
  5833. }
  5834. return true;
  5835. }
  5836. inline bool read_websocket_upgrade_response(Stream &strm,
  5837. const std::string &expected_accept,
  5838. std::string &selected_subprotocol) {
  5839. // Read status line
  5840. const auto bufsiz = 2048;
  5841. char buf[bufsiz];
  5842. stream_line_reader line_reader(strm, buf, bufsiz);
  5843. if (!line_reader.getline()) { return false; }
  5844. // Check for "HTTP/1.1 101"
  5845. auto line = std::string(line_reader.ptr(), line_reader.size());
  5846. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  5847. // Parse headers using existing read_headers
  5848. Headers headers;
  5849. if (!read_headers(strm, headers)) { return false; }
  5850. // Verify Upgrade: websocket (case-insensitive)
  5851. auto upgrade_it = headers.find("Upgrade");
  5852. if (upgrade_it == headers.end()) { return false; }
  5853. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  5854. if (upgrade_val != "websocket") { return false; }
  5855. // Verify Connection header contains "Upgrade" (case-insensitive)
  5856. auto connection_it = headers.find("Connection");
  5857. if (connection_it == headers.end()) { return false; }
  5858. auto connection_val = case_ignore::to_lower(connection_it->second);
  5859. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  5860. // Verify Sec-WebSocket-Accept header value
  5861. auto it = headers.find("Sec-WebSocket-Accept");
  5862. if (it == headers.end() || it->second != expected_accept) { return false; }
  5863. // Extract negotiated subprotocol
  5864. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  5865. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  5866. return true;
  5867. }
  5868. enum class ReadContentResult {
  5869. Success, // Successfully read the content
  5870. PayloadTooLarge, // The content exceeds the specified payload limit
  5871. Error // An error occurred while reading the content
  5872. };
  5873. inline ReadContentResult read_content_with_length(
  5874. Stream &strm, size_t len, DownloadProgress progress,
  5875. ContentReceiverWithProgress out,
  5876. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  5877. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5878. detail::BodyReader br;
  5879. br.stream = &strm;
  5880. br.has_content_length = true;
  5881. br.content_length = len;
  5882. br.payload_max_length = payload_max_length;
  5883. br.chunked = false;
  5884. br.bytes_read = 0;
  5885. br.last_error = Error::Success;
  5886. size_t r = 0;
  5887. while (r < len) {
  5888. auto read_len = static_cast<size_t>(len - r);
  5889. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  5890. auto n = detail::read_body_content(&strm, br, buf, to_read);
  5891. if (n <= 0) {
  5892. // Check if it was a payload size error
  5893. if (br.last_error == Error::ExceedMaxPayloadSize) {
  5894. return ReadContentResult::PayloadTooLarge;
  5895. }
  5896. return ReadContentResult::Error;
  5897. }
  5898. if (!out(buf, static_cast<size_t>(n), r, len)) {
  5899. return ReadContentResult::Error;
  5900. }
  5901. r += static_cast<size_t>(n);
  5902. if (progress) {
  5903. if (!progress(r, len)) { return ReadContentResult::Error; }
  5904. }
  5905. }
  5906. return ReadContentResult::Success;
  5907. }
  5908. inline ReadContentResult
  5909. read_content_without_length(Stream &strm, size_t payload_max_length,
  5910. ContentReceiverWithProgress out) {
  5911. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5912. size_t r = 0;
  5913. for (;;) {
  5914. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  5915. if (n == 0) { return ReadContentResult::Success; }
  5916. if (n < 0) { return ReadContentResult::Error; }
  5917. // Check if adding this data would exceed the payload limit
  5918. if (r > payload_max_length ||
  5919. payload_max_length - r < static_cast<size_t>(n)) {
  5920. return ReadContentResult::PayloadTooLarge;
  5921. }
  5922. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  5923. return ReadContentResult::Error;
  5924. }
  5925. r += static_cast<size_t>(n);
  5926. }
  5927. return ReadContentResult::Success;
  5928. }
  5929. template <typename T>
  5930. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  5931. size_t payload_max_length,
  5932. ContentReceiverWithProgress out) {
  5933. detail::ChunkedDecoder dec(strm);
  5934. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5935. size_t total_len = 0;
  5936. for (;;) {
  5937. size_t chunk_offset = 0;
  5938. size_t chunk_total = 0;
  5939. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  5940. if (n < 0) { return ReadContentResult::Error; }
  5941. if (n == 0) {
  5942. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  5943. return ReadContentResult::Error;
  5944. }
  5945. return ReadContentResult::Success;
  5946. }
  5947. if (total_len > payload_max_length ||
  5948. payload_max_length - total_len < static_cast<size_t>(n)) {
  5949. return ReadContentResult::PayloadTooLarge;
  5950. }
  5951. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  5952. return ReadContentResult::Error;
  5953. }
  5954. total_len += static_cast<size_t>(n);
  5955. }
  5956. }
  5957. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  5958. return case_ignore::equal(
  5959. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  5960. }
  5961. template <typename T, typename U>
  5962. bool prepare_content_receiver(T &x, int &status,
  5963. ContentReceiverWithProgress receiver,
  5964. bool decompress, size_t payload_max_length,
  5965. bool &exceed_payload_max_length, U callback) {
  5966. if (decompress) {
  5967. std::string encoding = x.get_header_value("Content-Encoding");
  5968. std::unique_ptr<decompressor> decompressor;
  5969. if (!encoding.empty()) {
  5970. decompressor = detail::create_decompressor(encoding);
  5971. if (!decompressor) {
  5972. // Unsupported encoding or no support compiled in
  5973. status = StatusCode::UnsupportedMediaType_415;
  5974. return false;
  5975. }
  5976. }
  5977. if (decompressor) {
  5978. if (decompressor->is_valid()) {
  5979. size_t decompressed_size = 0;
  5980. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  5981. size_t off, size_t len) {
  5982. return decompressor->decompress(
  5983. buf, n, [&](const char *buf2, size_t n2) {
  5984. // Guard against zip-bomb: check
  5985. // decompressed size against limit.
  5986. if (payload_max_length > 0 &&
  5987. (decompressed_size >= payload_max_length ||
  5988. n2 > payload_max_length - decompressed_size)) {
  5989. exceed_payload_max_length = true;
  5990. return false;
  5991. }
  5992. decompressed_size += n2;
  5993. return receiver(buf2, n2, off, len);
  5994. });
  5995. };
  5996. return callback(std::move(out));
  5997. } else {
  5998. status = StatusCode::InternalServerError_500;
  5999. return false;
  6000. }
  6001. }
  6002. }
  6003. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6004. size_t len) {
  6005. return receiver(buf, n, off, len);
  6006. };
  6007. return callback(std::move(out));
  6008. }
  6009. template <typename T>
  6010. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6011. DownloadProgress progress,
  6012. ContentReceiverWithProgress receiver, bool decompress) {
  6013. bool exceed_payload_max_length = false;
  6014. return prepare_content_receiver(
  6015. x, status, std::move(receiver), decompress, payload_max_length,
  6016. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6017. auto ret = true;
  6018. // Note: exceed_payload_max_length may also be set by the decompressor
  6019. // wrapper in prepare_content_receiver when the decompressed payload
  6020. // size exceeds the limit.
  6021. if (is_chunked_transfer_encoding(x.headers)) {
  6022. auto result = read_content_chunked(strm, x, payload_max_length, out);
  6023. if (result == ReadContentResult::Success) {
  6024. ret = true;
  6025. } else if (result == ReadContentResult::PayloadTooLarge) {
  6026. exceed_payload_max_length = true;
  6027. ret = false;
  6028. } else {
  6029. ret = false;
  6030. }
  6031. } else if (!has_header(x.headers, "Content-Length")) {
  6032. auto result =
  6033. read_content_without_length(strm, payload_max_length, out);
  6034. if (result == ReadContentResult::Success) {
  6035. ret = true;
  6036. } else if (result == ReadContentResult::PayloadTooLarge) {
  6037. exceed_payload_max_length = true;
  6038. ret = false;
  6039. } else {
  6040. ret = false;
  6041. }
  6042. } else {
  6043. auto is_invalid_value = false;
  6044. auto len = get_header_value_u64(x.headers, "Content-Length",
  6045. (std::numeric_limits<size_t>::max)(),
  6046. 0, is_invalid_value);
  6047. if (is_invalid_value) {
  6048. ret = false;
  6049. } else if (len > 0) {
  6050. auto result = read_content_with_length(
  6051. strm, len, std::move(progress), out, payload_max_length);
  6052. ret = (result == ReadContentResult::Success);
  6053. if (result == ReadContentResult::PayloadTooLarge) {
  6054. exceed_payload_max_length = true;
  6055. }
  6056. }
  6057. }
  6058. if (!ret) {
  6059. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6060. : StatusCode::BadRequest_400;
  6061. }
  6062. return ret;
  6063. });
  6064. }
  6065. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6066. const std::string &path) {
  6067. std::string s = method;
  6068. s += ' ';
  6069. s += path;
  6070. s += " HTTP/1.1\r\n";
  6071. return strm.write(s.data(), s.size());
  6072. }
  6073. inline ssize_t write_response_line(Stream &strm, int status) {
  6074. std::string s = "HTTP/1.1 ";
  6075. s += std::to_string(status);
  6076. s += ' ';
  6077. s += httplib::status_message(status);
  6078. s += "\r\n";
  6079. return strm.write(s.data(), s.size());
  6080. }
  6081. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6082. ssize_t write_len = 0;
  6083. for (const auto &x : headers) {
  6084. std::string s;
  6085. s = x.first;
  6086. s += ": ";
  6087. s += x.second;
  6088. s += "\r\n";
  6089. auto len = strm.write(s.data(), s.size());
  6090. if (len < 0) { return len; }
  6091. write_len += len;
  6092. }
  6093. auto len = strm.write("\r\n");
  6094. if (len < 0) { return len; }
  6095. write_len += len;
  6096. return write_len;
  6097. }
  6098. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6099. size_t offset = 0;
  6100. while (offset < l) {
  6101. auto length = strm.write(d + offset, l - offset);
  6102. if (length < 0) { return false; }
  6103. offset += static_cast<size_t>(length);
  6104. }
  6105. return true;
  6106. }
  6107. template <typename T>
  6108. inline bool write_content_with_progress(Stream &strm,
  6109. const ContentProvider &content_provider,
  6110. size_t offset, size_t length,
  6111. T is_shutting_down,
  6112. const UploadProgress &upload_progress,
  6113. Error &error) {
  6114. size_t end_offset = offset + length;
  6115. size_t start_offset = offset;
  6116. auto ok = true;
  6117. DataSink data_sink;
  6118. data_sink.write = [&](const char *d, size_t l) -> bool {
  6119. if (ok) {
  6120. if (write_data(strm, d, l)) {
  6121. offset += l;
  6122. if (upload_progress && length > 0) {
  6123. size_t current_written = offset - start_offset;
  6124. if (!upload_progress(current_written, length)) {
  6125. ok = false;
  6126. return false;
  6127. }
  6128. }
  6129. } else {
  6130. ok = false;
  6131. }
  6132. }
  6133. return ok;
  6134. };
  6135. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6136. while (offset < end_offset && !is_shutting_down()) {
  6137. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6138. error = Error::Write;
  6139. return false;
  6140. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6141. error = Error::Canceled;
  6142. return false;
  6143. } else if (!ok) {
  6144. error = Error::Write;
  6145. return false;
  6146. }
  6147. }
  6148. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6149. error = Error::Write;
  6150. return false;
  6151. }
  6152. error = Error::Success;
  6153. return true;
  6154. }
  6155. template <typename T>
  6156. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6157. size_t offset, size_t length, T is_shutting_down,
  6158. Error &error) {
  6159. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6160. is_shutting_down, nullptr, error);
  6161. }
  6162. template <typename T>
  6163. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6164. size_t offset, size_t length,
  6165. const T &is_shutting_down) {
  6166. auto error = Error::Success;
  6167. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6168. error);
  6169. }
  6170. template <typename T>
  6171. inline bool
  6172. write_content_without_length(Stream &strm,
  6173. const ContentProvider &content_provider,
  6174. const T &is_shutting_down) {
  6175. size_t offset = 0;
  6176. auto data_available = true;
  6177. auto ok = true;
  6178. DataSink data_sink;
  6179. data_sink.write = [&](const char *d, size_t l) -> bool {
  6180. if (ok) {
  6181. offset += l;
  6182. if (!write_data(strm, d, l)) { ok = false; }
  6183. }
  6184. return ok;
  6185. };
  6186. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6187. data_sink.done = [&](void) { data_available = false; };
  6188. while (data_available && !is_shutting_down()) {
  6189. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6190. return false;
  6191. } else if (!content_provider(offset, 0, data_sink)) {
  6192. return false;
  6193. } else if (!ok) {
  6194. return false;
  6195. }
  6196. }
  6197. return !data_available; // true only if done() was called, false if shutting
  6198. // down
  6199. }
  6200. template <typename T, typename U>
  6201. inline bool
  6202. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6203. const T &is_shutting_down, U &compressor, Error &error) {
  6204. size_t offset = 0;
  6205. auto data_available = true;
  6206. auto ok = true;
  6207. DataSink data_sink;
  6208. data_sink.write = [&](const char *d, size_t l) -> bool {
  6209. if (ok) {
  6210. data_available = l > 0;
  6211. offset += l;
  6212. std::string payload;
  6213. if (compressor.compress(d, l, false,
  6214. [&](const char *data, size_t data_len) {
  6215. payload.append(data, data_len);
  6216. return true;
  6217. })) {
  6218. if (!payload.empty()) {
  6219. // Emit chunked response header and footer for each chunk
  6220. auto chunk =
  6221. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6222. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6223. }
  6224. } else {
  6225. ok = false;
  6226. }
  6227. }
  6228. return ok;
  6229. };
  6230. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6231. auto done_with_trailer = [&](const Headers *trailer) {
  6232. if (!ok) { return; }
  6233. data_available = false;
  6234. std::string payload;
  6235. if (!compressor.compress(nullptr, 0, true,
  6236. [&](const char *data, size_t data_len) {
  6237. payload.append(data, data_len);
  6238. return true;
  6239. })) {
  6240. ok = false;
  6241. return;
  6242. }
  6243. if (!payload.empty()) {
  6244. // Emit chunked response header and footer for each chunk
  6245. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6246. if (!write_data(strm, chunk.data(), chunk.size())) {
  6247. ok = false;
  6248. return;
  6249. }
  6250. }
  6251. constexpr const char done_marker[] = "0\r\n";
  6252. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6253. // Trailer
  6254. if (trailer) {
  6255. for (const auto &kv : *trailer) {
  6256. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6257. if (!write_data(strm, field_line.data(), field_line.size())) {
  6258. ok = false;
  6259. }
  6260. }
  6261. }
  6262. constexpr const char crlf[] = "\r\n";
  6263. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6264. };
  6265. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6266. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6267. done_with_trailer(&trailer);
  6268. };
  6269. while (data_available && !is_shutting_down()) {
  6270. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6271. error = Error::Write;
  6272. return false;
  6273. } else if (!content_provider(offset, 0, data_sink)) {
  6274. error = Error::Canceled;
  6275. return false;
  6276. } else if (!ok) {
  6277. error = Error::Write;
  6278. return false;
  6279. }
  6280. }
  6281. if (data_available) { // exited due to is_shutting_down(), not done()
  6282. error = Error::Write;
  6283. return false;
  6284. }
  6285. error = Error::Success;
  6286. return true;
  6287. }
  6288. template <typename T, typename U>
  6289. inline bool write_content_chunked(Stream &strm,
  6290. const ContentProvider &content_provider,
  6291. const T &is_shutting_down, U &compressor) {
  6292. auto error = Error::Success;
  6293. return write_content_chunked(strm, content_provider, is_shutting_down,
  6294. compressor, error);
  6295. }
  6296. template <typename T>
  6297. inline bool redirect(T &cli, Request &req, Response &res,
  6298. const std::string &path, const std::string &location,
  6299. Error &error) {
  6300. Request new_req = req;
  6301. new_req.path = path;
  6302. new_req.redirect_count_ -= 1;
  6303. if (res.status == StatusCode::SeeOther_303 &&
  6304. (req.method != "GET" && req.method != "HEAD")) {
  6305. new_req.method = "GET";
  6306. new_req.body.clear();
  6307. new_req.headers.clear();
  6308. }
  6309. Response new_res;
  6310. auto ret = cli.send(new_req, new_res, error);
  6311. if (ret) {
  6312. req = std::move(new_req);
  6313. res = std::move(new_res);
  6314. if (res.location.empty()) { res.location = location; }
  6315. }
  6316. return ret;
  6317. }
  6318. inline std::string params_to_query_str(const Params &params) {
  6319. std::string query;
  6320. for (auto it = params.begin(); it != params.end(); ++it) {
  6321. if (it != params.begin()) { query += '&'; }
  6322. query += encode_query_component(it->first);
  6323. query += '=';
  6324. query += encode_query_component(it->second);
  6325. }
  6326. return query;
  6327. }
  6328. inline void parse_query_text(const char *data, std::size_t size,
  6329. Params &params) {
  6330. std::set<std::string> cache;
  6331. split(data, data + size, '&', [&](const char *b, const char *e) {
  6332. std::string kv(b, e);
  6333. if (cache.find(kv) != cache.end()) { return; }
  6334. cache.insert(std::move(kv));
  6335. std::string key;
  6336. std::string val;
  6337. divide(b, static_cast<std::size_t>(e - b), '=',
  6338. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6339. std::size_t rhs_size) {
  6340. key.assign(lhs_data, lhs_size);
  6341. val.assign(rhs_data, rhs_size);
  6342. });
  6343. if (!key.empty()) {
  6344. params.emplace(decode_query_component(key), decode_query_component(val));
  6345. }
  6346. });
  6347. }
  6348. inline void parse_query_text(const std::string &s, Params &params) {
  6349. parse_query_text(s.data(), s.size(), params);
  6350. }
  6351. // Normalize a query string by decoding and re-encoding each key/value pair
  6352. // while preserving the original parameter order. This avoids double-encoding
  6353. // and ensures consistent encoding without reordering (unlike Params which
  6354. // uses std::multimap and sorts keys).
  6355. inline std::string normalize_query_string(const std::string &query) {
  6356. std::string result;
  6357. split(query.data(), query.data() + query.size(), '&',
  6358. [&](const char *b, const char *e) {
  6359. std::string key;
  6360. std::string val;
  6361. divide(b, static_cast<std::size_t>(e - b), '=',
  6362. [&](const char *lhs_data, std::size_t lhs_size,
  6363. const char *rhs_data, std::size_t rhs_size) {
  6364. key.assign(lhs_data, lhs_size);
  6365. val.assign(rhs_data, rhs_size);
  6366. });
  6367. if (!key.empty()) {
  6368. auto dec_key = decode_query_component(key);
  6369. auto dec_val = decode_query_component(val);
  6370. if (!result.empty()) { result += '&'; }
  6371. result += encode_query_component(dec_key);
  6372. if (!val.empty() || std::find(b, e, '=') != e) {
  6373. result += '=';
  6374. result += encode_query_component(dec_val);
  6375. }
  6376. }
  6377. });
  6378. return result;
  6379. }
  6380. inline bool parse_multipart_boundary(const std::string &content_type,
  6381. std::string &boundary) {
  6382. std::map<std::string, std::string> params;
  6383. extract_media_type(content_type, &params);
  6384. auto it = params.find("boundary");
  6385. if (it == params.end()) { return false; }
  6386. boundary = it->second;
  6387. return !boundary.empty();
  6388. }
  6389. inline void parse_disposition_params(const std::string &s, Params &params) {
  6390. std::set<std::string> cache;
  6391. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6392. std::string kv(b, e);
  6393. if (cache.find(kv) != cache.end()) { return; }
  6394. cache.insert(kv);
  6395. std::string key;
  6396. std::string val;
  6397. split(b, e, '=', [&](const char *b2, const char *e2) {
  6398. if (key.empty()) {
  6399. key.assign(b2, e2);
  6400. } else {
  6401. val.assign(b2, e2);
  6402. }
  6403. });
  6404. if (!key.empty()) {
  6405. params.emplace(trim_double_quotes_copy((key)),
  6406. trim_double_quotes_copy((val)));
  6407. }
  6408. });
  6409. }
  6410. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6411. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6412. #else
  6413. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6414. #endif
  6415. auto is_valid = [](const std::string &str) {
  6416. return std::all_of(str.cbegin(), str.cend(),
  6417. [](unsigned char c) { return std::isdigit(c); });
  6418. };
  6419. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6420. const auto pos = static_cast<size_t>(6);
  6421. const auto len = static_cast<size_t>(s.size() - 6);
  6422. auto all_valid_ranges = true;
  6423. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6424. if (!all_valid_ranges) { return; }
  6425. const auto it = std::find(b, e, '-');
  6426. if (it == e) {
  6427. all_valid_ranges = false;
  6428. return;
  6429. }
  6430. const auto lhs = std::string(b, it);
  6431. const auto rhs = std::string(it + 1, e);
  6432. if (!is_valid(lhs) || !is_valid(rhs)) {
  6433. all_valid_ranges = false;
  6434. return;
  6435. }
  6436. ssize_t first = -1;
  6437. if (!lhs.empty()) {
  6438. ssize_t v;
  6439. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6440. if (res.ec == std::errc{}) { first = v; }
  6441. }
  6442. ssize_t last = -1;
  6443. if (!rhs.empty()) {
  6444. ssize_t v;
  6445. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6446. if (res.ec == std::errc{}) { last = v; }
  6447. }
  6448. if ((first == -1 && last == -1) ||
  6449. (first != -1 && last != -1 && first > last)) {
  6450. all_valid_ranges = false;
  6451. return;
  6452. }
  6453. ranges.emplace_back(first, last);
  6454. });
  6455. return all_valid_ranges && !ranges.empty();
  6456. }
  6457. return false;
  6458. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6459. }
  6460. #else
  6461. } catch (...) { return false; }
  6462. #endif
  6463. inline bool parse_accept_header(const std::string &s,
  6464. std::vector<std::string> &content_types) {
  6465. content_types.clear();
  6466. // Empty string is considered valid (no preference)
  6467. if (s.empty()) { return true; }
  6468. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6469. if (s.front() == ',' || s.back() == ',' ||
  6470. s.find(",,") != std::string::npos) {
  6471. return false;
  6472. }
  6473. struct AcceptEntry {
  6474. std::string media_type;
  6475. double quality;
  6476. int order;
  6477. };
  6478. std::vector<AcceptEntry> entries;
  6479. int order = 0;
  6480. bool has_invalid_entry = false;
  6481. // Split by comma and parse each entry
  6482. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6483. std::string entry(b, e);
  6484. entry = trim_copy(entry);
  6485. if (entry.empty()) {
  6486. has_invalid_entry = true;
  6487. return;
  6488. }
  6489. AcceptEntry accept_entry;
  6490. accept_entry.order = order++;
  6491. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6492. accept_entry.media_type, accept_entry.quality)) {
  6493. has_invalid_entry = true;
  6494. return;
  6495. }
  6496. // Remove additional parameters from media type
  6497. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6498. // Basic validation of media type format
  6499. if (accept_entry.media_type.empty()) {
  6500. has_invalid_entry = true;
  6501. return;
  6502. }
  6503. // Check for basic media type format (should contain '/' or be '*')
  6504. if (accept_entry.media_type != "*" &&
  6505. accept_entry.media_type.find('/') == std::string::npos) {
  6506. has_invalid_entry = true;
  6507. return;
  6508. }
  6509. entries.push_back(std::move(accept_entry));
  6510. });
  6511. // Return false if any invalid entry was found
  6512. if (has_invalid_entry) { return false; }
  6513. // Sort by quality (descending), then by original order (ascending)
  6514. std::sort(entries.begin(), entries.end(),
  6515. [](const AcceptEntry &a, const AcceptEntry &b) {
  6516. if (a.quality != b.quality) {
  6517. return a.quality > b.quality; // Higher quality first
  6518. }
  6519. return a.order < b.order; // Earlier order first for same quality
  6520. });
  6521. // Extract sorted media types
  6522. content_types.reserve(entries.size());
  6523. for (auto &entry : entries) {
  6524. content_types.push_back(std::move(entry.media_type));
  6525. }
  6526. return true;
  6527. }
  6528. class FormDataParser {
  6529. public:
  6530. FormDataParser() = default;
  6531. void set_boundary(std::string &&boundary) {
  6532. boundary_ = std::move(boundary);
  6533. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6534. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6535. }
  6536. bool is_valid() const { return is_valid_; }
  6537. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6538. const ContentReceiver &content_callback) {
  6539. buf_append(buf, n);
  6540. while (buf_size() > 0) {
  6541. switch (state_) {
  6542. case 0: { // Initial boundary
  6543. auto pos = buf_find(dash_boundary_crlf_);
  6544. if (pos == buf_size()) { return true; }
  6545. buf_erase(pos + dash_boundary_crlf_.size());
  6546. state_ = 1;
  6547. break;
  6548. }
  6549. case 1: { // New entry
  6550. clear_file_info();
  6551. state_ = 2;
  6552. break;
  6553. }
  6554. case 2: { // Headers
  6555. auto pos = buf_find(crlf_);
  6556. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6557. while (pos < buf_size()) {
  6558. // Empty line
  6559. if (pos == 0) {
  6560. if (!header_callback(file_)) {
  6561. is_valid_ = false;
  6562. return false;
  6563. }
  6564. buf_erase(crlf_.size());
  6565. state_ = 3;
  6566. break;
  6567. }
  6568. const auto header = buf_head(pos);
  6569. if (!parse_header(header.data(), header.data() + header.size(),
  6570. [&](const std::string &, const std::string &) {})) {
  6571. is_valid_ = false;
  6572. return false;
  6573. }
  6574. // Parse and emplace space trimmed headers into a map
  6575. if (!parse_header(
  6576. header.data(), header.data() + header.size(),
  6577. [&](const std::string &key, const std::string &val) {
  6578. file_.headers.emplace(key, val);
  6579. })) {
  6580. is_valid_ = false;
  6581. return false;
  6582. }
  6583. constexpr const char header_content_type[] = "Content-Type:";
  6584. if (start_with_case_ignore(header, header_content_type)) {
  6585. file_.content_type =
  6586. trim_copy(header.substr(str_len(header_content_type)));
  6587. } else {
  6588. std::string disposition_params;
  6589. if (parse_content_disposition(header, disposition_params)) {
  6590. Params params;
  6591. parse_disposition_params(disposition_params, params);
  6592. auto it = params.find("name");
  6593. if (it != params.end()) {
  6594. file_.name = it->second;
  6595. } else {
  6596. is_valid_ = false;
  6597. return false;
  6598. }
  6599. it = params.find("filename");
  6600. if (it != params.end()) { file_.filename = it->second; }
  6601. it = params.find("filename*");
  6602. if (it != params.end()) {
  6603. // RFC 5987: only UTF-8 encoding is allowed
  6604. const auto &val = it->second;
  6605. constexpr const char utf8_prefix[] = "UTF-8''";
  6606. constexpr size_t prefix_len = str_len(utf8_prefix);
  6607. if (val.size() > prefix_len &&
  6608. start_with_case_ignore(val, utf8_prefix)) {
  6609. file_.filename = decode_path_component(
  6610. val.substr(prefix_len)); // override...
  6611. } else {
  6612. is_valid_ = false;
  6613. return false;
  6614. }
  6615. }
  6616. }
  6617. }
  6618. buf_erase(pos + crlf_.size());
  6619. pos = buf_find(crlf_);
  6620. }
  6621. if (state_ != 3) { return true; }
  6622. break;
  6623. }
  6624. case 3: { // Body
  6625. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6626. auto pos = buf_find(crlf_dash_boundary_);
  6627. if (pos < buf_size()) {
  6628. if (!content_callback(buf_data(), pos)) {
  6629. is_valid_ = false;
  6630. return false;
  6631. }
  6632. buf_erase(pos + crlf_dash_boundary_.size());
  6633. state_ = 4;
  6634. } else {
  6635. auto len = buf_size() - crlf_dash_boundary_.size();
  6636. if (len > 0) {
  6637. if (!content_callback(buf_data(), len)) {
  6638. is_valid_ = false;
  6639. return false;
  6640. }
  6641. buf_erase(len);
  6642. }
  6643. return true;
  6644. }
  6645. break;
  6646. }
  6647. case 4: { // Boundary
  6648. if (crlf_.size() > buf_size()) { return true; }
  6649. if (buf_start_with(crlf_)) {
  6650. buf_erase(crlf_.size());
  6651. state_ = 1;
  6652. } else {
  6653. if (dash_.size() > buf_size()) { return true; }
  6654. if (buf_start_with(dash_)) {
  6655. buf_erase(dash_.size());
  6656. is_valid_ = true;
  6657. buf_erase(buf_size()); // Remove epilogue
  6658. } else {
  6659. return true;
  6660. }
  6661. }
  6662. break;
  6663. }
  6664. }
  6665. }
  6666. return true;
  6667. }
  6668. private:
  6669. void clear_file_info() {
  6670. file_.name.clear();
  6671. file_.filename.clear();
  6672. file_.content_type.clear();
  6673. file_.headers.clear();
  6674. }
  6675. bool start_with_case_ignore(const std::string &a, const char *b,
  6676. size_t offset = 0) const {
  6677. const auto b_len = strlen(b);
  6678. if (a.size() < offset + b_len) { return false; }
  6679. for (size_t i = 0; i < b_len; i++) {
  6680. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6681. return false;
  6682. }
  6683. }
  6684. return true;
  6685. }
  6686. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6687. // Returns true if header matches, with the params portion in `params_out`.
  6688. bool parse_content_disposition(const std::string &header,
  6689. std::string &params_out) const {
  6690. constexpr const char prefix[] = "Content-Disposition:";
  6691. constexpr size_t prefix_len = str_len(prefix);
  6692. if (!start_with_case_ignore(header, prefix)) { return false; }
  6693. // Skip whitespace after "Content-Disposition:"
  6694. auto pos = prefix_len;
  6695. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6696. pos++;
  6697. }
  6698. // Match "form-data;" (case-insensitive)
  6699. constexpr const char form_data[] = "form-data;";
  6700. constexpr size_t form_data_len = str_len(form_data);
  6701. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6702. pos += form_data_len;
  6703. // Skip whitespace after "form-data;"
  6704. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6705. pos++;
  6706. }
  6707. params_out = header.substr(pos);
  6708. return true;
  6709. }
  6710. const std::string dash_ = "--";
  6711. const std::string crlf_ = "\r\n";
  6712. std::string boundary_;
  6713. std::string dash_boundary_crlf_;
  6714. std::string crlf_dash_boundary_;
  6715. size_t state_ = 0;
  6716. bool is_valid_ = false;
  6717. FormData file_;
  6718. // Buffer
  6719. bool start_with(const std::string &a, size_t spos, size_t epos,
  6720. const std::string &b) const {
  6721. if (epos - spos < b.size()) { return false; }
  6722. for (size_t i = 0; i < b.size(); i++) {
  6723. if (a[i + spos] != b[i]) { return false; }
  6724. }
  6725. return true;
  6726. }
  6727. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6728. const char *buf_data() const { return &buf_[buf_spos_]; }
  6729. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6730. bool buf_start_with(const std::string &s) const {
  6731. return start_with(buf_, buf_spos_, buf_epos_, s);
  6732. }
  6733. size_t buf_find(const std::string &s) const {
  6734. auto c = s.front();
  6735. size_t off = buf_spos_;
  6736. while (off < buf_epos_) {
  6737. auto pos = off;
  6738. while (true) {
  6739. if (pos == buf_epos_) { return buf_size(); }
  6740. if (buf_[pos] == c) { break; }
  6741. pos++;
  6742. }
  6743. auto remaining_size = buf_epos_ - pos;
  6744. if (s.size() > remaining_size) { return buf_size(); }
  6745. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6746. off = pos + 1;
  6747. }
  6748. return buf_size();
  6749. }
  6750. void buf_append(const char *data, size_t n) {
  6751. auto remaining_size = buf_size();
  6752. if (remaining_size > 0 && buf_spos_ > 0) {
  6753. for (size_t i = 0; i < remaining_size; i++) {
  6754. buf_[i] = buf_[buf_spos_ + i];
  6755. }
  6756. }
  6757. buf_spos_ = 0;
  6758. buf_epos_ = remaining_size;
  6759. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6760. for (size_t i = 0; i < n; i++) {
  6761. buf_[buf_epos_ + i] = data[i];
  6762. }
  6763. buf_epos_ += n;
  6764. }
  6765. void buf_erase(size_t size) { buf_spos_ += size; }
  6766. std::string buf_;
  6767. size_t buf_spos_ = 0;
  6768. size_t buf_epos_ = 0;
  6769. };
  6770. inline std::string random_string(size_t length) {
  6771. constexpr const char data[] =
  6772. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6773. thread_local auto engine([]() {
  6774. // std::random_device might actually be deterministic on some
  6775. // platforms, but due to lack of support in the c++ standard library,
  6776. // doing better requires either some ugly hacks or breaking portability.
  6777. std::random_device seed_gen;
  6778. // Request 128 bits of entropy for initialization
  6779. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6780. return std::mt19937(seed_sequence);
  6781. }());
  6782. std::string result;
  6783. for (size_t i = 0; i < length; i++) {
  6784. result += data[engine() % (sizeof(data) - 1)];
  6785. }
  6786. return result;
  6787. }
  6788. inline std::string make_multipart_data_boundary() {
  6789. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6790. }
  6791. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6792. auto valid = true;
  6793. for (size_t i = 0; i < boundary.size(); i++) {
  6794. auto c = boundary[i];
  6795. if (!std::isalnum(c) && c != '-' && c != '_') {
  6796. valid = false;
  6797. break;
  6798. }
  6799. }
  6800. return valid;
  6801. }
  6802. template <typename T>
  6803. inline std::string
  6804. serialize_multipart_formdata_item_begin(const T &item,
  6805. const std::string &boundary) {
  6806. std::string body = "--" + boundary + "\r\n";
  6807. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6808. if (!item.filename.empty()) {
  6809. body += "; filename=\"" + item.filename + "\"";
  6810. }
  6811. body += "\r\n";
  6812. if (!item.content_type.empty()) {
  6813. body += "Content-Type: " + item.content_type + "\r\n";
  6814. }
  6815. body += "\r\n";
  6816. return body;
  6817. }
  6818. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  6819. inline std::string
  6820. serialize_multipart_formdata_finish(const std::string &boundary) {
  6821. return "--" + boundary + "--\r\n";
  6822. }
  6823. inline std::string
  6824. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  6825. return "multipart/form-data; boundary=" + boundary;
  6826. }
  6827. inline std::string
  6828. serialize_multipart_formdata(const UploadFormDataItems &items,
  6829. const std::string &boundary, bool finish = true) {
  6830. std::string body;
  6831. for (const auto &item : items) {
  6832. body += serialize_multipart_formdata_item_begin(item, boundary);
  6833. body += item.content + serialize_multipart_formdata_item_end();
  6834. }
  6835. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  6836. return body;
  6837. }
  6838. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  6839. const std::string &boundary) {
  6840. size_t total = 0;
  6841. for (const auto &item : items) {
  6842. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  6843. total += item.content.size();
  6844. total += serialize_multipart_formdata_item_end().size();
  6845. }
  6846. total += serialize_multipart_formdata_finish(boundary).size();
  6847. return total;
  6848. }
  6849. struct MultipartSegment {
  6850. const char *data;
  6851. size_t size;
  6852. };
  6853. // NOTE: items must outlive the returned ContentProvider
  6854. // (safe for synchronous use inside Post/Put/Patch)
  6855. inline ContentProvider
  6856. make_multipart_content_provider(const UploadFormDataItems &items,
  6857. const std::string &boundary) {
  6858. // Own the per-item header strings and the finish string
  6859. std::vector<std::string> owned;
  6860. owned.reserve(items.size() + 1);
  6861. for (const auto &item : items)
  6862. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  6863. owned.push_back(serialize_multipart_formdata_finish(boundary));
  6864. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  6865. std::vector<MultipartSegment> segs;
  6866. segs.reserve(items.size() * 3 + 1);
  6867. static const char crlf[] = "\r\n";
  6868. for (size_t i = 0; i < items.size(); i++) {
  6869. segs.push_back({owned[i].data(), owned[i].size()});
  6870. segs.push_back({items[i].content.data(), items[i].content.size()});
  6871. segs.push_back({crlf, 2});
  6872. }
  6873. segs.push_back({owned.back().data(), owned.back().size()});
  6874. struct MultipartState {
  6875. std::vector<std::string> owned;
  6876. std::vector<MultipartSegment> segs;
  6877. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  6878. };
  6879. auto state = std::make_shared<MultipartState>();
  6880. state->owned = std::move(owned);
  6881. // `segs` holds raw pointers into owned strings; std::string move preserves
  6882. // the data pointer, so these pointers remain valid after the move above.
  6883. state->segs = std::move(segs);
  6884. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  6885. // Buffer multiple small segments into fewer, larger writes to avoid
  6886. // excessive TCP packets when there are many form data items (#2410)
  6887. auto &buf = state->buf;
  6888. auto buf_size = buf.size();
  6889. size_t buf_len = 0;
  6890. size_t remaining = length;
  6891. // Find the first segment containing 'offset'
  6892. size_t pos = 0;
  6893. size_t seg_idx = 0;
  6894. for (; seg_idx < state->segs.size(); seg_idx++) {
  6895. const auto &seg = state->segs[seg_idx];
  6896. if (seg.size > 0 && offset - pos < seg.size) { break; }
  6897. pos += seg.size;
  6898. }
  6899. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  6900. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  6901. const auto &seg = state->segs[seg_idx];
  6902. size_t available = seg.size - seg_offset;
  6903. size_t to_copy = (std::min)(available, remaining);
  6904. const char *src = seg.data + seg_offset;
  6905. seg_offset = 0; // only the first segment has a non-zero offset
  6906. while (to_copy > 0) {
  6907. size_t space = buf_size - buf_len;
  6908. size_t chunk = (std::min)(to_copy, space);
  6909. std::memcpy(buf.data() + buf_len, src, chunk);
  6910. buf_len += chunk;
  6911. src += chunk;
  6912. to_copy -= chunk;
  6913. remaining -= chunk;
  6914. if (buf_len == buf_size) {
  6915. if (!sink.write(buf.data(), buf_len)) { return false; }
  6916. buf_len = 0;
  6917. }
  6918. }
  6919. }
  6920. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  6921. return true;
  6922. };
  6923. }
  6924. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  6925. if (ranges.size() <= 1) return;
  6926. // Sort ranges by start position
  6927. std::sort(ranges.begin(), ranges.end(),
  6928. [](const Range &a, const Range &b) { return a.first < b.first; });
  6929. Ranges coalesced;
  6930. coalesced.reserve(ranges.size());
  6931. for (auto &r : ranges) {
  6932. auto first_pos = r.first;
  6933. auto last_pos = r.second;
  6934. // Handle special cases like in range_error
  6935. if (first_pos == -1 && last_pos == -1) {
  6936. first_pos = 0;
  6937. last_pos = static_cast<ssize_t>(content_length);
  6938. }
  6939. if (first_pos == -1) {
  6940. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  6941. last_pos = static_cast<ssize_t>(content_length) - 1;
  6942. }
  6943. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  6944. last_pos = static_cast<ssize_t>(content_length) - 1;
  6945. }
  6946. // Skip invalid ranges
  6947. if (!(0 <= first_pos && first_pos <= last_pos &&
  6948. last_pos < static_cast<ssize_t>(content_length))) {
  6949. continue;
  6950. }
  6951. // Coalesce with previous range if overlapping or adjacent (but not
  6952. // identical)
  6953. if (!coalesced.empty()) {
  6954. auto &prev = coalesced.back();
  6955. // Check if current range overlaps or is adjacent to previous range
  6956. // but don't coalesce identical ranges (allow duplicates)
  6957. if (first_pos <= prev.second + 1 &&
  6958. !(first_pos == prev.first && last_pos == prev.second)) {
  6959. // Extend the previous range
  6960. prev.second = (std::max)(prev.second, last_pos);
  6961. continue;
  6962. }
  6963. }
  6964. // Add new range
  6965. coalesced.emplace_back(first_pos, last_pos);
  6966. }
  6967. ranges = std::move(coalesced);
  6968. }
  6969. inline bool range_error(Request &req, Response &res) {
  6970. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  6971. ssize_t content_len = static_cast<ssize_t>(
  6972. res.content_length_ ? res.content_length_ : res.body.size());
  6973. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  6974. size_t overwrapping_count = 0;
  6975. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  6976. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  6977. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  6978. // Too many ranges
  6979. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  6980. for (auto &r : req.ranges) {
  6981. auto &first_pos = r.first;
  6982. auto &last_pos = r.second;
  6983. if (first_pos == -1 && last_pos == -1) {
  6984. first_pos = 0;
  6985. last_pos = content_len;
  6986. }
  6987. if (first_pos == -1) {
  6988. first_pos = content_len - last_pos;
  6989. last_pos = content_len - 1;
  6990. }
  6991. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  6992. // A client can limit the number of bytes requested without knowing the
  6993. // size of the selected representation. If the last-pos value is absent,
  6994. // or if the value is greater than or equal to the current length of the
  6995. // representation data, the byte range is interpreted as the remainder of
  6996. // the representation (i.e., the server replaces the value of last-pos
  6997. // with a value that is one less than the current length of the selected
  6998. // representation).
  6999. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7000. if (last_pos == -1 || last_pos >= content_len) {
  7001. last_pos = content_len - 1;
  7002. }
  7003. // Range must be within content length
  7004. if (!(0 <= first_pos && first_pos <= last_pos &&
  7005. last_pos <= content_len - 1)) {
  7006. return true;
  7007. }
  7008. // Request must not have more than two overlapping ranges
  7009. for (const auto &processed_range : processed_ranges) {
  7010. if (!(last_pos < processed_range.first ||
  7011. first_pos > processed_range.second)) {
  7012. overwrapping_count++;
  7013. if (overwrapping_count > 2) { return true; }
  7014. break; // Only count once per range
  7015. }
  7016. }
  7017. processed_ranges.emplace_back(first_pos, last_pos);
  7018. }
  7019. // After validation, coalesce overlapping ranges as per RFC 9110
  7020. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7021. }
  7022. return false;
  7023. }
  7024. inline std::pair<size_t, size_t>
  7025. get_range_offset_and_length(Range r, size_t content_length) {
  7026. assert(r.first != -1 && r.second != -1);
  7027. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7028. assert(r.first <= r.second &&
  7029. r.second < static_cast<ssize_t>(content_length));
  7030. (void)(content_length);
  7031. return std::make_pair(static_cast<size_t>(r.first),
  7032. static_cast<size_t>(r.second - r.first) + 1);
  7033. }
  7034. inline std::string make_content_range_header_field(
  7035. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7036. auto st = offset_and_length.first;
  7037. auto ed = st + offset_and_length.second - 1;
  7038. std::string field = "bytes ";
  7039. field += std::to_string(st);
  7040. field += '-';
  7041. field += std::to_string(ed);
  7042. field += '/';
  7043. field += std::to_string(content_length);
  7044. return field;
  7045. }
  7046. template <typename SToken, typename CToken, typename Content>
  7047. bool process_multipart_ranges_data(const Request &req,
  7048. const std::string &boundary,
  7049. const std::string &content_type,
  7050. size_t content_length, SToken stoken,
  7051. CToken ctoken, Content content) {
  7052. for (size_t i = 0; i < req.ranges.size(); i++) {
  7053. ctoken("--");
  7054. stoken(boundary);
  7055. ctoken("\r\n");
  7056. if (!content_type.empty()) {
  7057. ctoken("Content-Type: ");
  7058. stoken(content_type);
  7059. ctoken("\r\n");
  7060. }
  7061. auto offset_and_length =
  7062. get_range_offset_and_length(req.ranges[i], content_length);
  7063. ctoken("Content-Range: ");
  7064. stoken(make_content_range_header_field(offset_and_length, content_length));
  7065. ctoken("\r\n");
  7066. ctoken("\r\n");
  7067. if (!content(offset_and_length.first, offset_and_length.second)) {
  7068. return false;
  7069. }
  7070. ctoken("\r\n");
  7071. }
  7072. ctoken("--");
  7073. stoken(boundary);
  7074. ctoken("--");
  7075. return true;
  7076. }
  7077. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7078. const std::string &boundary,
  7079. const std::string &content_type,
  7080. size_t content_length,
  7081. std::string &data) {
  7082. process_multipart_ranges_data(
  7083. req, boundary, content_type, content_length,
  7084. [&](const std::string &token) { data += token; },
  7085. [&](const std::string &token) { data += token; },
  7086. [&](size_t offset, size_t length) {
  7087. assert(offset + length <= content_length);
  7088. data += res.body.substr(offset, length);
  7089. return true;
  7090. });
  7091. }
  7092. inline size_t get_multipart_ranges_data_length(const Request &req,
  7093. const std::string &boundary,
  7094. const std::string &content_type,
  7095. size_t content_length) {
  7096. size_t data_length = 0;
  7097. process_multipart_ranges_data(
  7098. req, boundary, content_type, content_length,
  7099. [&](const std::string &token) { data_length += token.size(); },
  7100. [&](const std::string &token) { data_length += token.size(); },
  7101. [&](size_t /*offset*/, size_t length) {
  7102. data_length += length;
  7103. return true;
  7104. });
  7105. return data_length;
  7106. }
  7107. template <typename T>
  7108. inline bool
  7109. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7110. const std::string &boundary,
  7111. const std::string &content_type,
  7112. size_t content_length, const T &is_shutting_down) {
  7113. return process_multipart_ranges_data(
  7114. req, boundary, content_type, content_length,
  7115. [&](const std::string &token) { strm.write(token); },
  7116. [&](const std::string &token) { strm.write(token); },
  7117. [&](size_t offset, size_t length) {
  7118. return write_content(strm, res.content_provider_, offset, length,
  7119. is_shutting_down);
  7120. });
  7121. }
  7122. inline bool expect_content(const Request &req) {
  7123. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7124. req.method == "DELETE") {
  7125. return true;
  7126. }
  7127. if (req.has_header("Content-Length") &&
  7128. req.get_header_value_u64("Content-Length") > 0) {
  7129. return true;
  7130. }
  7131. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  7132. return false;
  7133. }
  7134. #ifdef _WIN32
  7135. class WSInit {
  7136. public:
  7137. WSInit() {
  7138. WSADATA wsaData;
  7139. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7140. }
  7141. ~WSInit() {
  7142. if (is_valid_) WSACleanup();
  7143. }
  7144. bool is_valid_ = false;
  7145. };
  7146. static WSInit wsinit_;
  7147. #endif
  7148. inline bool parse_www_authenticate(const Response &res,
  7149. std::map<std::string, std::string> &auth,
  7150. bool is_proxy) {
  7151. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7152. if (res.has_header(auth_key)) {
  7153. thread_local auto re =
  7154. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7155. auto s = res.get_header_value(auth_key);
  7156. auto pos = s.find(' ');
  7157. if (pos != std::string::npos) {
  7158. auto type = s.substr(0, pos);
  7159. if (type == "Basic") {
  7160. return false;
  7161. } else if (type == "Digest") {
  7162. s = s.substr(pos + 1);
  7163. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7164. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7165. const auto &m = *i;
  7166. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7167. static_cast<size_t>(m.length(1)));
  7168. auto val = m.length(2) > 0
  7169. ? s.substr(static_cast<size_t>(m.position(2)),
  7170. static_cast<size_t>(m.length(2)))
  7171. : s.substr(static_cast<size_t>(m.position(3)),
  7172. static_cast<size_t>(m.length(3)));
  7173. auth[std::move(key)] = std::move(val);
  7174. }
  7175. return true;
  7176. }
  7177. }
  7178. }
  7179. return false;
  7180. }
  7181. class ContentProviderAdapter {
  7182. public:
  7183. explicit ContentProviderAdapter(
  7184. ContentProviderWithoutLength &&content_provider)
  7185. : content_provider_(std::move(content_provider)) {}
  7186. bool operator()(size_t offset, size_t, DataSink &sink) {
  7187. return content_provider_(offset, sink);
  7188. }
  7189. private:
  7190. ContentProviderWithoutLength content_provider_;
  7191. };
  7192. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7193. namespace fields {
  7194. inline bool is_token_char(char c) {
  7195. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7196. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7197. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7198. }
  7199. inline bool is_token(const std::string &s) {
  7200. if (s.empty()) { return false; }
  7201. for (auto c : s) {
  7202. if (!is_token_char(c)) { return false; }
  7203. }
  7204. return true;
  7205. }
  7206. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7207. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7208. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7209. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7210. inline bool is_field_content(const std::string &s) {
  7211. if (s.empty()) { return true; }
  7212. if (s.size() == 1) {
  7213. return is_field_vchar(s[0]);
  7214. } else if (s.size() == 2) {
  7215. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7216. } else {
  7217. size_t i = 0;
  7218. if (!is_field_vchar(s[i])) { return false; }
  7219. i++;
  7220. while (i < s.size() - 1) {
  7221. auto c = s[i++];
  7222. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7223. } else {
  7224. return false;
  7225. }
  7226. }
  7227. return is_field_vchar(s[i]);
  7228. }
  7229. }
  7230. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7231. } // namespace fields
  7232. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7233. int port, const std::string &path,
  7234. const Headers &headers,
  7235. std::string &selected_subprotocol) {
  7236. // Validate path and host
  7237. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7238. return false;
  7239. }
  7240. // Validate user-provided headers
  7241. for (const auto &h : headers) {
  7242. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7243. return false;
  7244. }
  7245. }
  7246. // Generate random Sec-WebSocket-Key
  7247. thread_local std::mt19937 rng(std::random_device{}());
  7248. std::string key_bytes(16, '\0');
  7249. for (size_t i = 0; i < 16; i += 4) {
  7250. auto r = rng();
  7251. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7252. }
  7253. auto client_key = base64_encode(key_bytes);
  7254. // Build upgrade request
  7255. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7256. req_str += "Host: " + host + ":" + std::to_string(port) + "\r\n";
  7257. req_str += "Upgrade: websocket\r\n";
  7258. req_str += "Connection: Upgrade\r\n";
  7259. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7260. req_str += "Sec-WebSocket-Version: 13\r\n";
  7261. for (const auto &h : headers) {
  7262. req_str += h.first + ": " + h.second + "\r\n";
  7263. }
  7264. req_str += "\r\n";
  7265. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7266. // Verify 101 response and Sec-WebSocket-Accept header
  7267. auto expected_accept = websocket_accept_key(client_key);
  7268. return read_websocket_upgrade_response(strm, expected_accept,
  7269. selected_subprotocol);
  7270. }
  7271. } // namespace detail
  7272. /*
  7273. * Group 2: detail namespace - SSL common utilities
  7274. */
  7275. #ifdef CPPHTTPLIB_SSL_ENABLED
  7276. namespace detail {
  7277. class SSLSocketStream final : public Stream {
  7278. public:
  7279. SSLSocketStream(
  7280. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7281. time_t read_timeout_usec, time_t write_timeout_sec,
  7282. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7283. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7284. (std::chrono::steady_clock::time_point::min)());
  7285. ~SSLSocketStream() override;
  7286. bool is_readable() const override;
  7287. bool wait_readable() const override;
  7288. bool wait_writable() const override;
  7289. bool is_peer_alive() const override;
  7290. ssize_t read(char *ptr, size_t size) override;
  7291. ssize_t write(const char *ptr, size_t size) override;
  7292. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7293. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7294. socket_t socket() const override;
  7295. time_t duration() const override;
  7296. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7297. private:
  7298. socket_t sock_;
  7299. tls::session_t session_;
  7300. time_t read_timeout_sec_;
  7301. time_t read_timeout_usec_;
  7302. time_t write_timeout_sec_;
  7303. time_t write_timeout_usec_;
  7304. time_t max_timeout_msec_;
  7305. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7306. };
  7307. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7308. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7309. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7310. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7311. unsigned int hash_length = 0;
  7312. unsigned char hash[EVP_MAX_MD_SIZE];
  7313. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7314. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7315. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7316. std::stringstream ss;
  7317. for (auto i = 0u; i < hash_length; ++i) {
  7318. ss << std::hex << std::setw(2) << std::setfill('0')
  7319. << static_cast<unsigned int>(hash[i]);
  7320. }
  7321. return ss.str();
  7322. }
  7323. inline std::string MD5(const std::string &s) {
  7324. return message_digest(s, EVP_md5());
  7325. }
  7326. inline std::string SHA_256(const std::string &s) {
  7327. return message_digest(s, EVP_sha256());
  7328. }
  7329. inline std::string SHA_512(const std::string &s) {
  7330. return message_digest(s, EVP_sha512());
  7331. }
  7332. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7333. namespace {
  7334. template <size_t N>
  7335. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7336. std::stringstream ss;
  7337. for (size_t i = 0; i < N; ++i) {
  7338. ss << std::hex << std::setw(2) << std::setfill('0')
  7339. << static_cast<unsigned int>(hash[i]);
  7340. }
  7341. return ss.str();
  7342. }
  7343. } // namespace
  7344. inline std::string MD5(const std::string &s) {
  7345. unsigned char hash[16];
  7346. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7347. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7348. hash);
  7349. #else
  7350. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7351. hash);
  7352. #endif
  7353. return hash_to_hex(hash);
  7354. }
  7355. inline std::string SHA_256(const std::string &s) {
  7356. unsigned char hash[32];
  7357. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7358. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7359. hash, 0);
  7360. #else
  7361. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7362. s.size(), hash, 0);
  7363. #endif
  7364. return hash_to_hex(hash);
  7365. }
  7366. inline std::string SHA_512(const std::string &s) {
  7367. unsigned char hash[64];
  7368. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7369. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7370. hash, 0);
  7371. #else
  7372. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7373. s.size(), hash, 0);
  7374. #endif
  7375. return hash_to_hex(hash);
  7376. }
  7377. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7378. namespace {
  7379. template <size_t N>
  7380. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7381. std::stringstream ss;
  7382. for (size_t i = 0; i < N; ++i) {
  7383. ss << std::hex << std::setw(2) << std::setfill('0')
  7384. << static_cast<unsigned int>(hash[i]);
  7385. }
  7386. return ss.str();
  7387. }
  7388. } // namespace
  7389. inline std::string MD5(const std::string &s) {
  7390. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7391. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7392. static_cast<word32>(s.size()), hash);
  7393. return hash_to_hex(hash);
  7394. }
  7395. inline std::string SHA_256(const std::string &s) {
  7396. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7397. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7398. static_cast<word32>(s.size()), hash);
  7399. return hash_to_hex(hash);
  7400. }
  7401. inline std::string SHA_512(const std::string &s) {
  7402. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7403. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7404. static_cast<word32>(s.size()), hash);
  7405. return hash_to_hex(hash);
  7406. }
  7407. #endif
  7408. inline bool is_ip_address(const std::string &host) {
  7409. struct in_addr addr4;
  7410. struct in6_addr addr6;
  7411. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7412. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7413. }
  7414. template <typename T>
  7415. inline bool process_server_socket_ssl(
  7416. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7417. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7418. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7419. time_t write_timeout_usec, T callback) {
  7420. return process_server_socket_core(
  7421. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7422. [&](bool close_connection, bool &connection_closed) {
  7423. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7424. write_timeout_sec, write_timeout_usec);
  7425. return callback(strm, close_connection, connection_closed);
  7426. });
  7427. }
  7428. template <typename T>
  7429. inline bool process_client_socket_ssl(
  7430. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7431. time_t read_timeout_usec, time_t write_timeout_sec,
  7432. time_t write_timeout_usec, time_t max_timeout_msec,
  7433. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7434. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7435. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7436. start_time);
  7437. return callback(strm);
  7438. }
  7439. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7440. const Request &req, const std::map<std::string, std::string> &auth,
  7441. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7442. const std::string &password, bool is_proxy = false) {
  7443. std::string nc;
  7444. {
  7445. std::stringstream ss;
  7446. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7447. nc = ss.str();
  7448. }
  7449. std::string qop;
  7450. if (auth.find("qop") != auth.end()) {
  7451. qop = auth.at("qop");
  7452. if (qop.find("auth-int") != std::string::npos) {
  7453. qop = "auth-int";
  7454. } else if (qop.find("auth") != std::string::npos) {
  7455. qop = "auth";
  7456. } else {
  7457. qop.clear();
  7458. }
  7459. }
  7460. std::string algo = "MD5";
  7461. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7462. std::string response;
  7463. {
  7464. auto H = algo == "SHA-256" ? detail::SHA_256
  7465. : algo == "SHA-512" ? detail::SHA_512
  7466. : detail::MD5;
  7467. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7468. auto A2 = req.method + ":" + req.path;
  7469. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7470. if (qop.empty()) {
  7471. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7472. } else {
  7473. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7474. ":" + qop + ":" + H(A2));
  7475. }
  7476. }
  7477. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7478. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7479. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7480. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7481. (qop.empty() ? ", response=\""
  7482. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7483. cnonce + "\", response=\"") +
  7484. response + "\"" +
  7485. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7486. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7487. return std::make_pair(key, field);
  7488. }
  7489. inline bool match_hostname(const std::string &pattern,
  7490. const std::string &hostname) {
  7491. // Exact match (case-insensitive)
  7492. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7493. // Split both pattern and hostname into components by '.'
  7494. std::vector<std::string> pattern_components;
  7495. if (!pattern.empty()) {
  7496. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7497. [&](const char *b, const char *e) {
  7498. pattern_components.emplace_back(b, e);
  7499. });
  7500. }
  7501. std::vector<std::string> host_components;
  7502. if (!hostname.empty()) {
  7503. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7504. [&](const char *b, const char *e) {
  7505. host_components.emplace_back(b, e);
  7506. });
  7507. }
  7508. // Component count must match
  7509. if (host_components.size() != pattern_components.size()) { return false; }
  7510. // Compare each component with wildcard support
  7511. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7512. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7513. auto itr = pattern_components.begin();
  7514. for (const auto &h : host_components) {
  7515. auto &p = *itr;
  7516. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7517. bool partial_match = false;
  7518. if (!p.empty() && p[p.size() - 1] == '*') {
  7519. const auto prefix_length = p.size() - 1;
  7520. if (prefix_length == 0) {
  7521. partial_match = true;
  7522. } else if (h.size() >= prefix_length) {
  7523. partial_match =
  7524. std::equal(p.begin(),
  7525. p.begin() + static_cast<std::string::difference_type>(
  7526. prefix_length),
  7527. h.begin(), [](const char ca, const char cb) {
  7528. return detail::case_ignore::to_lower(ca) ==
  7529. detail::case_ignore::to_lower(cb);
  7530. });
  7531. }
  7532. }
  7533. if (!partial_match) { return false; }
  7534. }
  7535. ++itr;
  7536. }
  7537. return true;
  7538. }
  7539. #ifdef _WIN32
  7540. // Verify certificate using Windows CertGetCertificateChain API.
  7541. // This provides real-time certificate validation with Windows Update
  7542. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7543. inline bool
  7544. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7545. const std::string &hostname,
  7546. bool verify_hostname, uint64_t &out_error) {
  7547. if (der_cert.empty()) { return false; }
  7548. out_error = 0;
  7549. // Create Windows certificate context from DER data
  7550. auto cert_context = CertCreateCertificateContext(
  7551. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7552. static_cast<DWORD>(der_cert.size()));
  7553. if (!cert_context) {
  7554. out_error = GetLastError();
  7555. return false;
  7556. }
  7557. auto cert_guard =
  7558. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7559. // Setup chain parameters
  7560. CERT_CHAIN_PARA chain_para = {};
  7561. chain_para.cbSize = sizeof(chain_para);
  7562. // Build certificate chain with revocation checking
  7563. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7564. auto chain_result = CertGetCertificateChain(
  7565. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7566. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7567. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7568. nullptr, &chain_context);
  7569. if (!chain_result || !chain_context) {
  7570. out_error = GetLastError();
  7571. return false;
  7572. }
  7573. auto chain_guard =
  7574. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7575. // Check if chain has errors
  7576. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7577. out_error = chain_context->TrustStatus.dwErrorStatus;
  7578. return false;
  7579. }
  7580. // Verify SSL policy
  7581. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7582. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7583. #ifdef AUTHTYPE_SERVER
  7584. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7585. #endif
  7586. std::wstring whost;
  7587. if (verify_hostname) {
  7588. whost = u8string_to_wstring(hostname.c_str());
  7589. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7590. }
  7591. CERT_CHAIN_POLICY_PARA policy_para = {};
  7592. policy_para.cbSize = sizeof(policy_para);
  7593. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7594. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7595. #else
  7596. policy_para.dwFlags = 0;
  7597. #endif
  7598. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7599. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7600. policy_status.cbSize = sizeof(policy_status);
  7601. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7602. &policy_para, &policy_status)) {
  7603. out_error = GetLastError();
  7604. return false;
  7605. }
  7606. if (policy_status.dwError != 0) {
  7607. out_error = policy_status.dwError;
  7608. return false;
  7609. }
  7610. return true;
  7611. }
  7612. #endif // _WIN32
  7613. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t &ctx,
  7614. tls::session_t &session, socket_t sock,
  7615. bool server_certificate_verification,
  7616. const std::string &ca_cert_file_path,
  7617. tls::ca_store_t ca_cert_store,
  7618. time_t timeout_sec, time_t timeout_usec) {
  7619. using namespace tls;
  7620. ctx = create_client_context();
  7621. if (!ctx) { return false; }
  7622. if (server_certificate_verification) {
  7623. if (!ca_cert_file_path.empty()) {
  7624. load_ca_file(ctx, ca_cert_file_path.c_str());
  7625. }
  7626. if (ca_cert_store) { set_ca_store(ctx, ca_cert_store); }
  7627. load_system_certs(ctx);
  7628. }
  7629. bool is_ip = is_ip_address(host);
  7630. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  7631. if (is_ip && server_certificate_verification) {
  7632. set_verify_client(ctx, false);
  7633. } else {
  7634. set_verify_client(ctx, server_certificate_verification);
  7635. }
  7636. #endif
  7637. session = create_session(ctx, sock);
  7638. if (!session) { return false; }
  7639. // RFC 6066: SNI must not be set for IP addresses
  7640. if (!is_ip) { set_sni(session, host.c_str()); }
  7641. if (server_certificate_verification) { set_hostname(session, host.c_str()); }
  7642. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7643. return false;
  7644. }
  7645. if (server_certificate_verification) {
  7646. if (get_verify_result(session) != 0) { return false; }
  7647. }
  7648. return true;
  7649. }
  7650. } // namespace detail
  7651. #endif // CPPHTTPLIB_SSL_ENABLED
  7652. /*
  7653. * Group 3: httplib namespace - Non-SSL public API implementations
  7654. */
  7655. inline void default_socket_options(socket_t sock) {
  7656. set_socket_opt(sock, SOL_SOCKET,
  7657. #ifdef SO_REUSEPORT
  7658. SO_REUSEPORT,
  7659. #else
  7660. SO_REUSEADDR,
  7661. #endif
  7662. 1);
  7663. }
  7664. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7665. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7666. sizeof(optval));
  7667. }
  7668. inline std::string get_bearer_token_auth(const Request &req) {
  7669. if (req.has_header("Authorization")) {
  7670. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7671. return req.get_header_value("Authorization")
  7672. .substr(bearer_header_prefix_len);
  7673. }
  7674. return "";
  7675. }
  7676. inline const char *status_message(int status) {
  7677. switch (status) {
  7678. case StatusCode::Continue_100: return "Continue";
  7679. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7680. case StatusCode::Processing_102: return "Processing";
  7681. case StatusCode::EarlyHints_103: return "Early Hints";
  7682. case StatusCode::OK_200: return "OK";
  7683. case StatusCode::Created_201: return "Created";
  7684. case StatusCode::Accepted_202: return "Accepted";
  7685. case StatusCode::NonAuthoritativeInformation_203:
  7686. return "Non-Authoritative Information";
  7687. case StatusCode::NoContent_204: return "No Content";
  7688. case StatusCode::ResetContent_205: return "Reset Content";
  7689. case StatusCode::PartialContent_206: return "Partial Content";
  7690. case StatusCode::MultiStatus_207: return "Multi-Status";
  7691. case StatusCode::AlreadyReported_208: return "Already Reported";
  7692. case StatusCode::IMUsed_226: return "IM Used";
  7693. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7694. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7695. case StatusCode::Found_302: return "Found";
  7696. case StatusCode::SeeOther_303: return "See Other";
  7697. case StatusCode::NotModified_304: return "Not Modified";
  7698. case StatusCode::UseProxy_305: return "Use Proxy";
  7699. case StatusCode::unused_306: return "unused";
  7700. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7701. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7702. case StatusCode::BadRequest_400: return "Bad Request";
  7703. case StatusCode::Unauthorized_401: return "Unauthorized";
  7704. case StatusCode::PaymentRequired_402: return "Payment Required";
  7705. case StatusCode::Forbidden_403: return "Forbidden";
  7706. case StatusCode::NotFound_404: return "Not Found";
  7707. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7708. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7709. case StatusCode::ProxyAuthenticationRequired_407:
  7710. return "Proxy Authentication Required";
  7711. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7712. case StatusCode::Conflict_409: return "Conflict";
  7713. case StatusCode::Gone_410: return "Gone";
  7714. case StatusCode::LengthRequired_411: return "Length Required";
  7715. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7716. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7717. case StatusCode::UriTooLong_414: return "URI Too Long";
  7718. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7719. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7720. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7721. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7722. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7723. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7724. case StatusCode::Locked_423: return "Locked";
  7725. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7726. case StatusCode::TooEarly_425: return "Too Early";
  7727. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7728. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7729. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7730. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7731. return "Request Header Fields Too Large";
  7732. case StatusCode::UnavailableForLegalReasons_451:
  7733. return "Unavailable For Legal Reasons";
  7734. case StatusCode::NotImplemented_501: return "Not Implemented";
  7735. case StatusCode::BadGateway_502: return "Bad Gateway";
  7736. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  7737. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  7738. case StatusCode::HttpVersionNotSupported_505:
  7739. return "HTTP Version Not Supported";
  7740. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  7741. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  7742. case StatusCode::LoopDetected_508: return "Loop Detected";
  7743. case StatusCode::NotExtended_510: return "Not Extended";
  7744. case StatusCode::NetworkAuthenticationRequired_511:
  7745. return "Network Authentication Required";
  7746. default:
  7747. case StatusCode::InternalServerError_500: return "Internal Server Error";
  7748. }
  7749. }
  7750. inline std::string to_string(const Error error) {
  7751. switch (error) {
  7752. case Error::Success: return "Success (no error)";
  7753. case Error::Unknown: return "Unknown";
  7754. case Error::Connection: return "Could not establish connection";
  7755. case Error::BindIPAddress: return "Failed to bind IP address";
  7756. case Error::Read: return "Failed to read connection";
  7757. case Error::Write: return "Failed to write connection";
  7758. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  7759. case Error::Canceled: return "Connection handling canceled";
  7760. case Error::SSLConnection: return "SSL connection failed";
  7761. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  7762. case Error::SSLServerVerification: return "SSL server verification failed";
  7763. case Error::SSLServerHostnameVerification:
  7764. return "SSL server hostname verification failed";
  7765. case Error::UnsupportedMultipartBoundaryChars:
  7766. return "Unsupported HTTP multipart boundary characters";
  7767. case Error::Compression: return "Compression failed";
  7768. case Error::ConnectionTimeout: return "Connection timed out";
  7769. case Error::ProxyConnection: return "Proxy connection failed";
  7770. case Error::ConnectionClosed: return "Connection closed by server";
  7771. case Error::Timeout: return "Read timeout";
  7772. case Error::ResourceExhaustion: return "Resource exhaustion";
  7773. case Error::TooManyFormDataFiles: return "Too many form data files";
  7774. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  7775. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  7776. case Error::ExceedMaxSocketDescriptorCount:
  7777. return "Exceeded maximum socket descriptor count";
  7778. case Error::InvalidRequestLine: return "Invalid request line";
  7779. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  7780. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  7781. case Error::InvalidHeaders: return "Invalid headers";
  7782. case Error::MultipartParsing: return "Multipart parsing failed";
  7783. case Error::OpenFile: return "Failed to open file";
  7784. case Error::Listen: return "Failed to listen on socket";
  7785. case Error::GetSockName: return "Failed to get socket name";
  7786. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  7787. case Error::HTTPParsing: return "HTTP parsing failed";
  7788. case Error::InvalidRangeHeader: return "Invalid Range header";
  7789. default: break;
  7790. }
  7791. return "Invalid";
  7792. }
  7793. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  7794. os << to_string(obj);
  7795. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  7796. return os;
  7797. }
  7798. inline std::string hosted_at(const std::string &hostname) {
  7799. std::vector<std::string> addrs;
  7800. hosted_at(hostname, addrs);
  7801. if (addrs.empty()) { return std::string(); }
  7802. return addrs[0];
  7803. }
  7804. inline void hosted_at(const std::string &hostname,
  7805. std::vector<std::string> &addrs) {
  7806. struct addrinfo hints;
  7807. struct addrinfo *result;
  7808. memset(&hints, 0, sizeof(struct addrinfo));
  7809. hints.ai_family = AF_UNSPEC;
  7810. hints.ai_socktype = SOCK_STREAM;
  7811. hints.ai_protocol = 0;
  7812. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  7813. &result, 0)) {
  7814. #if defined __linux__ && !defined __ANDROID__
  7815. res_init();
  7816. #endif
  7817. return;
  7818. }
  7819. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  7820. for (auto rp = result; rp; rp = rp->ai_next) {
  7821. const auto &addr =
  7822. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  7823. std::string ip;
  7824. auto dummy = -1;
  7825. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  7826. dummy)) {
  7827. addrs.emplace_back(std::move(ip));
  7828. }
  7829. }
  7830. }
  7831. inline std::string encode_uri_component(const std::string &value) {
  7832. std::ostringstream escaped;
  7833. escaped.fill('0');
  7834. escaped << std::hex;
  7835. for (auto c : value) {
  7836. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  7837. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  7838. c == ')') {
  7839. escaped << c;
  7840. } else {
  7841. escaped << std::uppercase;
  7842. escaped << '%' << std::setw(2)
  7843. << static_cast<int>(static_cast<unsigned char>(c));
  7844. escaped << std::nouppercase;
  7845. }
  7846. }
  7847. return escaped.str();
  7848. }
  7849. inline std::string encode_uri(const std::string &value) {
  7850. std::ostringstream escaped;
  7851. escaped.fill('0');
  7852. escaped << std::hex;
  7853. for (auto c : value) {
  7854. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  7855. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  7856. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  7857. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  7858. escaped << c;
  7859. } else {
  7860. escaped << std::uppercase;
  7861. escaped << '%' << std::setw(2)
  7862. << static_cast<int>(static_cast<unsigned char>(c));
  7863. escaped << std::nouppercase;
  7864. }
  7865. }
  7866. return escaped.str();
  7867. }
  7868. inline std::string decode_uri_component(const std::string &value) {
  7869. std::string result;
  7870. for (size_t i = 0; i < value.size(); i++) {
  7871. if (value[i] == '%' && i + 2 < value.size()) {
  7872. auto val = 0;
  7873. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  7874. result += static_cast<char>(val);
  7875. i += 2;
  7876. } else {
  7877. result += value[i];
  7878. }
  7879. } else {
  7880. result += value[i];
  7881. }
  7882. }
  7883. return result;
  7884. }
  7885. inline std::string decode_uri(const std::string &value) {
  7886. std::string result;
  7887. for (size_t i = 0; i < value.size(); i++) {
  7888. if (value[i] == '%' && i + 2 < value.size()) {
  7889. auto val = 0;
  7890. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  7891. result += static_cast<char>(val);
  7892. i += 2;
  7893. } else {
  7894. result += value[i];
  7895. }
  7896. } else {
  7897. result += value[i];
  7898. }
  7899. }
  7900. return result;
  7901. }
  7902. inline std::string encode_path_component(const std::string &component) {
  7903. std::string result;
  7904. result.reserve(component.size() * 3);
  7905. for (size_t i = 0; i < component.size(); i++) {
  7906. auto c = static_cast<unsigned char>(component[i]);
  7907. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  7908. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  7909. result += static_cast<char>(c);
  7910. }
  7911. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  7912. // "," / ";" / "="
  7913. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  7914. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  7915. c == '=') {
  7916. result += static_cast<char>(c);
  7917. }
  7918. // Colon is allowed in path segments except first segment
  7919. else if (c == ':') {
  7920. result += static_cast<char>(c);
  7921. }
  7922. // @ is allowed in path
  7923. else if (c == '@') {
  7924. result += static_cast<char>(c);
  7925. } else {
  7926. result += '%';
  7927. char hex[3];
  7928. snprintf(hex, sizeof(hex), "%02X", c);
  7929. result.append(hex, 2);
  7930. }
  7931. }
  7932. return result;
  7933. }
  7934. inline std::string decode_path_component(const std::string &component) {
  7935. std::string result;
  7936. result.reserve(component.size());
  7937. for (size_t i = 0; i < component.size(); i++) {
  7938. if (component[i] == '%' && i + 1 < component.size()) {
  7939. if (component[i + 1] == 'u') {
  7940. // Unicode %uXXXX encoding
  7941. auto val = 0;
  7942. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  7943. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  7944. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  7945. char buff[4];
  7946. size_t len = detail::to_utf8(val, buff);
  7947. if (len > 0) { result.append(buff, len); }
  7948. i += 5; // 'u0000'
  7949. } else {
  7950. result += component[i];
  7951. }
  7952. } else {
  7953. // Standard %XX encoding
  7954. auto val = 0;
  7955. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  7956. // 2 digits hex codes
  7957. result += static_cast<char>(val);
  7958. i += 2; // 'XX'
  7959. } else {
  7960. result += component[i];
  7961. }
  7962. }
  7963. } else {
  7964. result += component[i];
  7965. }
  7966. }
  7967. return result;
  7968. }
  7969. inline std::string encode_query_component(const std::string &component,
  7970. bool space_as_plus) {
  7971. std::string result;
  7972. result.reserve(component.size() * 3);
  7973. for (size_t i = 0; i < component.size(); i++) {
  7974. auto c = static_cast<unsigned char>(component[i]);
  7975. // Unreserved characters per RFC 3986
  7976. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  7977. result += static_cast<char>(c);
  7978. }
  7979. // Space handling
  7980. else if (c == ' ') {
  7981. if (space_as_plus) {
  7982. result += '+';
  7983. } else {
  7984. result += "%20";
  7985. }
  7986. }
  7987. // Plus sign handling
  7988. else if (c == '+') {
  7989. if (space_as_plus) {
  7990. result += "%2B";
  7991. } else {
  7992. result += static_cast<char>(c);
  7993. }
  7994. }
  7995. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  7996. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  7997. c == '*' || c == ',' || c == ';') {
  7998. result += static_cast<char>(c);
  7999. }
  8000. // Colon and @ are allowed in query
  8001. else if (c == ':' || c == '@') {
  8002. result += static_cast<char>(c);
  8003. }
  8004. // Forward slash is allowed in query values
  8005. else if (c == '/') {
  8006. result += static_cast<char>(c);
  8007. }
  8008. // Question mark is allowed in query values (after first ?)
  8009. else if (c == '?') {
  8010. result += static_cast<char>(c);
  8011. } else {
  8012. result += '%';
  8013. char hex[3];
  8014. snprintf(hex, sizeof(hex), "%02X", c);
  8015. result.append(hex, 2);
  8016. }
  8017. }
  8018. return result;
  8019. }
  8020. inline std::string decode_query_component(const std::string &component,
  8021. bool plus_as_space) {
  8022. std::string result;
  8023. result.reserve(component.size());
  8024. for (size_t i = 0; i < component.size(); i++) {
  8025. if (component[i] == '%' && i + 2 < component.size()) {
  8026. std::string hex = component.substr(i + 1, 2);
  8027. char *end;
  8028. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  8029. if (end == hex.c_str() + 2) {
  8030. result += static_cast<char>(value);
  8031. i += 2;
  8032. } else {
  8033. result += component[i];
  8034. }
  8035. } else if (component[i] == '+' && plus_as_space) {
  8036. result += ' '; // + becomes space in form-urlencoded
  8037. } else {
  8038. result += component[i];
  8039. }
  8040. }
  8041. return result;
  8042. }
  8043. inline std::string sanitize_filename(const std::string &filename) {
  8044. // Extract basename: find the last path separator (/ or \)
  8045. auto pos = filename.find_last_of("/\\");
  8046. auto result =
  8047. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8048. // Strip null bytes
  8049. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8050. // Trim whitespace
  8051. {
  8052. auto start = result.find_first_not_of(" \t");
  8053. auto end = result.find_last_not_of(" \t");
  8054. result = (start == std::string::npos)
  8055. ? ""
  8056. : result.substr(start, end - start + 1);
  8057. }
  8058. // Reject . and ..
  8059. if (result == "." || result == "..") { return ""; }
  8060. return result;
  8061. }
  8062. inline std::string append_query_params(const std::string &path,
  8063. const Params &params) {
  8064. std::string path_with_query = path;
  8065. thread_local const std::regex re("[^?]+\\?.*");
  8066. auto delm = std::regex_match(path, re) ? '&' : '?';
  8067. path_with_query += delm + detail::params_to_query_str(params);
  8068. return path_with_query;
  8069. }
  8070. // Header utilities
  8071. inline std::pair<std::string, std::string>
  8072. make_range_header(const Ranges &ranges) {
  8073. std::string field = "bytes=";
  8074. auto i = 0;
  8075. for (const auto &r : ranges) {
  8076. if (i != 0) { field += ", "; }
  8077. if (r.first != -1) { field += std::to_string(r.first); }
  8078. field += '-';
  8079. if (r.second != -1) { field += std::to_string(r.second); }
  8080. i++;
  8081. }
  8082. return std::make_pair("Range", std::move(field));
  8083. }
  8084. inline std::pair<std::string, std::string>
  8085. make_basic_authentication_header(const std::string &username,
  8086. const std::string &password, bool is_proxy) {
  8087. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8088. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8089. return std::make_pair(key, std::move(field));
  8090. }
  8091. inline std::pair<std::string, std::string>
  8092. make_bearer_token_authentication_header(const std::string &token,
  8093. bool is_proxy = false) {
  8094. auto field = "Bearer " + token;
  8095. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8096. return std::make_pair(key, std::move(field));
  8097. }
  8098. // Request implementation
  8099. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8100. size_t id) const {
  8101. return detail::get_header_value_u64(headers, key, def, id);
  8102. }
  8103. inline bool Request::has_header(const std::string &key) const {
  8104. return detail::has_header(headers, key);
  8105. }
  8106. inline std::string Request::get_header_value(const std::string &key,
  8107. const char *def, size_t id) const {
  8108. return detail::get_header_value(headers, key, def, id);
  8109. }
  8110. inline size_t Request::get_header_value_count(const std::string &key) const {
  8111. return detail::get_header_value_count(headers, key);
  8112. }
  8113. inline void Request::set_header(const std::string &key,
  8114. const std::string &val) {
  8115. detail::set_header(headers, key, val);
  8116. }
  8117. inline bool Request::has_trailer(const std::string &key) const {
  8118. return trailers.find(key) != trailers.end();
  8119. }
  8120. inline std::string Request::get_trailer_value(const std::string &key,
  8121. size_t id) const {
  8122. return detail::get_multimap_value(trailers, key, id);
  8123. }
  8124. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8125. auto r = trailers.equal_range(key);
  8126. return static_cast<size_t>(std::distance(r.first, r.second));
  8127. }
  8128. inline bool Request::has_param(const std::string &key) const {
  8129. return params.find(key) != params.end();
  8130. }
  8131. inline std::string Request::get_param_value(const std::string &key,
  8132. size_t id) const {
  8133. return detail::get_multimap_value(params, key, id);
  8134. }
  8135. inline std::vector<std::string>
  8136. Request::get_param_values(const std::string &key) const {
  8137. auto rng = params.equal_range(key);
  8138. std::vector<std::string> values;
  8139. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8140. for (auto it = rng.first; it != rng.second; ++it) {
  8141. values.push_back(it->second);
  8142. }
  8143. return values;
  8144. }
  8145. inline size_t Request::get_param_value_count(const std::string &key) const {
  8146. auto r = params.equal_range(key);
  8147. return static_cast<size_t>(std::distance(r.first, r.second));
  8148. }
  8149. inline bool Request::is_multipart_form_data() const {
  8150. const auto &content_type = get_header_value("Content-Type");
  8151. return detail::extract_media_type(content_type) == "multipart/form-data";
  8152. }
  8153. // Multipart FormData implementation
  8154. inline std::string MultipartFormData::get_field(const std::string &key,
  8155. size_t id) const {
  8156. auto rng = fields.equal_range(key);
  8157. auto it = rng.first;
  8158. std::advance(it, static_cast<ssize_t>(id));
  8159. if (it != rng.second) { return it->second.content; }
  8160. return std::string();
  8161. }
  8162. inline std::vector<std::string>
  8163. MultipartFormData::get_fields(const std::string &key) const {
  8164. std::vector<std::string> values;
  8165. auto rng = fields.equal_range(key);
  8166. for (auto it = rng.first; it != rng.second; it++) {
  8167. values.push_back(it->second.content);
  8168. }
  8169. return values;
  8170. }
  8171. inline bool MultipartFormData::has_field(const std::string &key) const {
  8172. return fields.find(key) != fields.end();
  8173. }
  8174. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8175. auto r = fields.equal_range(key);
  8176. return static_cast<size_t>(std::distance(r.first, r.second));
  8177. }
  8178. inline FormData MultipartFormData::get_file(const std::string &key,
  8179. size_t id) const {
  8180. return detail::get_multimap_value(files, key, id);
  8181. }
  8182. inline std::vector<FormData>
  8183. MultipartFormData::get_files(const std::string &key) const {
  8184. std::vector<FormData> values;
  8185. auto rng = files.equal_range(key);
  8186. for (auto it = rng.first; it != rng.second; it++) {
  8187. values.push_back(it->second);
  8188. }
  8189. return values;
  8190. }
  8191. inline bool MultipartFormData::has_file(const std::string &key) const {
  8192. return files.find(key) != files.end();
  8193. }
  8194. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8195. auto r = files.equal_range(key);
  8196. return static_cast<size_t>(std::distance(r.first, r.second));
  8197. }
  8198. // Response implementation
  8199. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8200. size_t id) const {
  8201. return detail::get_header_value_u64(headers, key, def, id);
  8202. }
  8203. inline bool Response::has_header(const std::string &key) const {
  8204. return headers.find(key) != headers.end();
  8205. }
  8206. inline std::string Response::get_header_value(const std::string &key,
  8207. const char *def,
  8208. size_t id) const {
  8209. return detail::get_header_value(headers, key, def, id);
  8210. }
  8211. inline size_t Response::get_header_value_count(const std::string &key) const {
  8212. return detail::get_header_value_count(headers, key);
  8213. }
  8214. inline void Response::set_header(const std::string &key,
  8215. const std::string &val) {
  8216. detail::set_header(headers, key, val);
  8217. }
  8218. inline bool Response::has_trailer(const std::string &key) const {
  8219. return trailers.find(key) != trailers.end();
  8220. }
  8221. inline std::string Response::get_trailer_value(const std::string &key,
  8222. size_t id) const {
  8223. return detail::get_multimap_value(trailers, key, id);
  8224. }
  8225. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8226. auto r = trailers.equal_range(key);
  8227. return static_cast<size_t>(std::distance(r.first, r.second));
  8228. }
  8229. inline void Response::set_redirect(const std::string &url, int stat) {
  8230. if (detail::fields::is_field_value(url)) {
  8231. set_header("Location", url);
  8232. if (300 <= stat && stat < 400) {
  8233. this->status = stat;
  8234. } else {
  8235. this->status = StatusCode::Found_302;
  8236. }
  8237. }
  8238. }
  8239. inline void Response::set_content(const char *s, size_t n,
  8240. const std::string &content_type) {
  8241. body.assign(s, n);
  8242. auto rng = headers.equal_range("Content-Type");
  8243. headers.erase(rng.first, rng.second);
  8244. set_header("Content-Type", content_type);
  8245. }
  8246. inline void Response::set_content(const std::string &s,
  8247. const std::string &content_type) {
  8248. set_content(s.data(), s.size(), content_type);
  8249. }
  8250. inline void Response::set_content(std::string &&s,
  8251. const std::string &content_type) {
  8252. body = std::move(s);
  8253. auto rng = headers.equal_range("Content-Type");
  8254. headers.erase(rng.first, rng.second);
  8255. set_header("Content-Type", content_type);
  8256. }
  8257. inline void Response::set_content_provider(
  8258. size_t in_length, const std::string &content_type, ContentProvider provider,
  8259. ContentProviderResourceReleaser resource_releaser) {
  8260. set_header("Content-Type", content_type);
  8261. content_length_ = in_length;
  8262. if (in_length > 0) { content_provider_ = std::move(provider); }
  8263. content_provider_resource_releaser_ = std::move(resource_releaser);
  8264. is_chunked_content_provider_ = false;
  8265. }
  8266. inline void Response::set_content_provider(
  8267. const std::string &content_type, ContentProviderWithoutLength provider,
  8268. ContentProviderResourceReleaser resource_releaser) {
  8269. set_header("Content-Type", content_type);
  8270. content_length_ = 0;
  8271. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8272. content_provider_resource_releaser_ = std::move(resource_releaser);
  8273. is_chunked_content_provider_ = false;
  8274. }
  8275. inline void Response::set_chunked_content_provider(
  8276. const std::string &content_type, ContentProviderWithoutLength provider,
  8277. ContentProviderResourceReleaser resource_releaser) {
  8278. set_header("Content-Type", content_type);
  8279. content_length_ = 0;
  8280. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8281. content_provider_resource_releaser_ = std::move(resource_releaser);
  8282. is_chunked_content_provider_ = true;
  8283. }
  8284. inline void Response::set_file_content(const std::string &path,
  8285. const std::string &content_type) {
  8286. file_content_path_ = path;
  8287. file_content_content_type_ = content_type;
  8288. }
  8289. inline void Response::set_file_content(const std::string &path) {
  8290. file_content_path_ = path;
  8291. }
  8292. // Result implementation
  8293. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8294. size_t def,
  8295. size_t id) const {
  8296. return detail::get_header_value_u64(request_headers_, key, def, id);
  8297. }
  8298. inline bool Result::has_request_header(const std::string &key) const {
  8299. return request_headers_.find(key) != request_headers_.end();
  8300. }
  8301. inline std::string Result::get_request_header_value(const std::string &key,
  8302. const char *def,
  8303. size_t id) const {
  8304. return detail::get_header_value(request_headers_, key, def, id);
  8305. }
  8306. inline size_t
  8307. Result::get_request_header_value_count(const std::string &key) const {
  8308. auto r = request_headers_.equal_range(key);
  8309. return static_cast<size_t>(std::distance(r.first, r.second));
  8310. }
  8311. // Stream implementation
  8312. inline ssize_t Stream::write(const char *ptr) {
  8313. return write(ptr, strlen(ptr));
  8314. }
  8315. inline ssize_t Stream::write(const std::string &s) {
  8316. return write(s.data(), s.size());
  8317. }
  8318. // BodyReader implementation
  8319. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8320. if (!stream) {
  8321. last_error = Error::Connection;
  8322. return -1;
  8323. }
  8324. if (eof) { return 0; }
  8325. if (!chunked) {
  8326. // Content-Length based reading
  8327. if (has_content_length && bytes_read >= content_length) {
  8328. eof = true;
  8329. return 0;
  8330. }
  8331. auto to_read = len;
  8332. if (has_content_length) {
  8333. auto remaining = content_length - bytes_read;
  8334. to_read = (std::min)(len, remaining);
  8335. }
  8336. auto n = stream->read(buf, to_read);
  8337. if (n < 0) {
  8338. last_error = stream->get_error();
  8339. if (last_error == Error::Success) { last_error = Error::Read; }
  8340. eof = true;
  8341. return n;
  8342. }
  8343. if (n == 0) {
  8344. // Unexpected EOF before content_length
  8345. last_error = stream->get_error();
  8346. if (last_error == Error::Success) { last_error = Error::Read; }
  8347. eof = true;
  8348. return 0;
  8349. }
  8350. bytes_read += static_cast<size_t>(n);
  8351. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8352. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8353. last_error = Error::ExceedMaxPayloadSize;
  8354. eof = true;
  8355. return -1;
  8356. }
  8357. return n;
  8358. }
  8359. // Chunked transfer encoding: delegate to shared decoder instance.
  8360. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8361. size_t chunk_offset = 0;
  8362. size_t chunk_total = 0;
  8363. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8364. if (n < 0) {
  8365. last_error = stream->get_error();
  8366. if (last_error == Error::Success) { last_error = Error::Read; }
  8367. eof = true;
  8368. return n;
  8369. }
  8370. if (n == 0) {
  8371. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8372. eof = true;
  8373. return 0;
  8374. }
  8375. bytes_read += static_cast<size_t>(n);
  8376. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8377. last_error = Error::ExceedMaxPayloadSize;
  8378. eof = true;
  8379. return -1;
  8380. }
  8381. return n;
  8382. }
  8383. // ThreadPool implementation
  8384. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr)
  8385. : base_thread_count_(n), max_queued_requests_(mqr), idle_thread_count_(0),
  8386. shutdown_(false) {
  8387. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8388. if (max_n != 0 && max_n < n) {
  8389. std::string msg = "max_threads must be >= base_threads";
  8390. throw std::invalid_argument(msg);
  8391. }
  8392. #endif
  8393. max_thread_count_ = max_n == 0 ? n : max_n;
  8394. threads_.reserve(base_thread_count_);
  8395. for (size_t i = 0; i < base_thread_count_; i++) {
  8396. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8397. }
  8398. }
  8399. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8400. {
  8401. std::unique_lock<std::mutex> lock(mutex_);
  8402. if (shutdown_) { return false; }
  8403. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8404. return false;
  8405. }
  8406. jobs_.push_back(std::move(fn));
  8407. // Spawn a dynamic thread if no idle threads and under max
  8408. if (idle_thread_count_ == 0 &&
  8409. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8410. cleanup_finished_threads();
  8411. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8412. }
  8413. }
  8414. cond_.notify_one();
  8415. return true;
  8416. }
  8417. inline void ThreadPool::shutdown() {
  8418. {
  8419. std::unique_lock<std::mutex> lock(mutex_);
  8420. shutdown_ = true;
  8421. }
  8422. cond_.notify_all();
  8423. for (auto &t : threads_) {
  8424. if (t.joinable()) { t.join(); }
  8425. }
  8426. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8427. // with worker threads that call move_to_finished() concurrently.
  8428. std::list<std::thread> remaining_dynamic;
  8429. {
  8430. std::unique_lock<std::mutex> lock(mutex_);
  8431. remaining_dynamic = std::move(dynamic_threads_);
  8432. }
  8433. for (auto &t : remaining_dynamic) {
  8434. if (t.joinable()) { t.join(); }
  8435. }
  8436. std::unique_lock<std::mutex> lock(mutex_);
  8437. cleanup_finished_threads();
  8438. }
  8439. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8440. // Must be called with mutex_ held
  8441. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8442. if (it->get_id() == id) {
  8443. finished_threads_.push_back(std::move(*it));
  8444. dynamic_threads_.erase(it);
  8445. return;
  8446. }
  8447. }
  8448. }
  8449. inline void ThreadPool::cleanup_finished_threads() {
  8450. // Must be called with mutex_ held
  8451. for (auto &t : finished_threads_) {
  8452. if (t.joinable()) { t.join(); }
  8453. }
  8454. finished_threads_.clear();
  8455. }
  8456. inline void ThreadPool::worker(bool is_dynamic) {
  8457. for (;;) {
  8458. std::function<void()> fn;
  8459. {
  8460. std::unique_lock<std::mutex> lock(mutex_);
  8461. idle_thread_count_++;
  8462. if (is_dynamic) {
  8463. auto has_work = cond_.wait_for(
  8464. lock, std::chrono::seconds(CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT),
  8465. [&] { return !jobs_.empty() || shutdown_; });
  8466. if (!has_work) {
  8467. // Timed out with no work - exit this dynamic thread
  8468. idle_thread_count_--;
  8469. move_to_finished(std::this_thread::get_id());
  8470. break;
  8471. }
  8472. } else {
  8473. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8474. }
  8475. idle_thread_count_--;
  8476. if (shutdown_ && jobs_.empty()) { break; }
  8477. fn = std::move(jobs_.front());
  8478. jobs_.pop_front();
  8479. }
  8480. assert(true == static_cast<bool>(fn));
  8481. fn();
  8482. }
  8483. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8484. !defined(LIBRESSL_VERSION_NUMBER)
  8485. OPENSSL_thread_stop();
  8486. #endif
  8487. }
  8488. /*
  8489. * Group 1 (continued): detail namespace - Stream implementations
  8490. */
  8491. namespace detail {
  8492. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8493. time_t timeout_sec, time_t timeout_usec,
  8494. time_t &actual_timeout_sec,
  8495. time_t &actual_timeout_usec) {
  8496. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8497. auto actual_timeout_msec =
  8498. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8499. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8500. actual_timeout_sec = actual_timeout_msec / 1000;
  8501. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8502. }
  8503. // Socket stream implementation
  8504. inline SocketStream::SocketStream(
  8505. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8506. time_t write_timeout_sec, time_t write_timeout_usec,
  8507. time_t max_timeout_msec,
  8508. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8509. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8510. read_timeout_usec_(read_timeout_usec),
  8511. write_timeout_sec_(write_timeout_sec),
  8512. write_timeout_usec_(write_timeout_usec),
  8513. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8514. read_buff_(read_buff_size_, 0) {}
  8515. inline SocketStream::~SocketStream() = default;
  8516. inline bool SocketStream::is_readable() const {
  8517. return read_buff_off_ < read_buff_content_size_;
  8518. }
  8519. inline bool SocketStream::wait_readable() const {
  8520. if (max_timeout_msec_ <= 0) {
  8521. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8522. }
  8523. time_t read_timeout_sec;
  8524. time_t read_timeout_usec;
  8525. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8526. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8527. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8528. }
  8529. inline bool SocketStream::wait_writable() const {
  8530. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8531. }
  8532. inline bool SocketStream::is_peer_alive() const {
  8533. return detail::is_socket_alive(sock_);
  8534. }
  8535. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8536. #ifdef _WIN32
  8537. size =
  8538. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8539. #else
  8540. size = (std::min)(size,
  8541. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8542. #endif
  8543. if (read_buff_off_ < read_buff_content_size_) {
  8544. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8545. if (size <= remaining_size) {
  8546. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8547. read_buff_off_ += size;
  8548. return static_cast<ssize_t>(size);
  8549. } else {
  8550. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8551. read_buff_off_ += remaining_size;
  8552. return static_cast<ssize_t>(remaining_size);
  8553. }
  8554. }
  8555. if (!wait_readable()) {
  8556. error_ = Error::Timeout;
  8557. return -1;
  8558. }
  8559. read_buff_off_ = 0;
  8560. read_buff_content_size_ = 0;
  8561. if (size < read_buff_size_) {
  8562. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8563. CPPHTTPLIB_RECV_FLAGS);
  8564. if (n <= 0) {
  8565. if (n == 0) {
  8566. error_ = Error::ConnectionClosed;
  8567. } else {
  8568. error_ = Error::Read;
  8569. }
  8570. return n;
  8571. } else if (n <= static_cast<ssize_t>(size)) {
  8572. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8573. return n;
  8574. } else {
  8575. memcpy(ptr, read_buff_.data(), size);
  8576. read_buff_off_ = size;
  8577. read_buff_content_size_ = static_cast<size_t>(n);
  8578. return static_cast<ssize_t>(size);
  8579. }
  8580. } else {
  8581. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8582. if (n <= 0) {
  8583. if (n == 0) {
  8584. error_ = Error::ConnectionClosed;
  8585. } else {
  8586. error_ = Error::Read;
  8587. }
  8588. }
  8589. return n;
  8590. }
  8591. }
  8592. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8593. if (!wait_writable()) { return -1; }
  8594. #if defined(_WIN32) && !defined(_WIN64)
  8595. size =
  8596. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8597. #endif
  8598. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8599. }
  8600. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8601. int &port) const {
  8602. return detail::get_remote_ip_and_port(sock_, ip, port);
  8603. }
  8604. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8605. int &port) const {
  8606. return detail::get_local_ip_and_port(sock_, ip, port);
  8607. }
  8608. inline socket_t SocketStream::socket() const { return sock_; }
  8609. inline time_t SocketStream::duration() const {
  8610. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8611. std::chrono::steady_clock::now() - start_time_)
  8612. .count();
  8613. }
  8614. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8615. read_timeout_sec_ = sec;
  8616. read_timeout_usec_ = usec;
  8617. }
  8618. // Buffer stream implementation
  8619. inline bool BufferStream::is_readable() const { return true; }
  8620. inline bool BufferStream::wait_readable() const { return true; }
  8621. inline bool BufferStream::wait_writable() const { return true; }
  8622. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8623. #if defined(_MSC_VER) && _MSC_VER < 1910
  8624. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8625. #else
  8626. auto len_read = buffer.copy(ptr, size, position);
  8627. #endif
  8628. position += static_cast<size_t>(len_read);
  8629. return static_cast<ssize_t>(len_read);
  8630. }
  8631. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8632. buffer.append(ptr, size);
  8633. return static_cast<ssize_t>(size);
  8634. }
  8635. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8636. int & /*port*/) const {}
  8637. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8638. int & /*port*/) const {}
  8639. inline socket_t BufferStream::socket() const { return 0; }
  8640. inline time_t BufferStream::duration() const { return 0; }
  8641. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8642. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8643. : MatcherBase(pattern) {
  8644. constexpr const char marker[] = "/:";
  8645. // One past the last ending position of a path param substring
  8646. std::size_t last_param_end = 0;
  8647. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8648. // Needed to ensure that parameter names are unique during matcher
  8649. // construction
  8650. // If exceptions are disabled, only last duplicate path
  8651. // parameter will be set
  8652. std::unordered_set<std::string> param_name_set;
  8653. #endif
  8654. while (true) {
  8655. const auto marker_pos = pattern.find(
  8656. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8657. if (marker_pos == std::string::npos) { break; }
  8658. static_fragments_.push_back(
  8659. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8660. const auto param_name_start = marker_pos + str_len(marker);
  8661. auto sep_pos = pattern.find(separator, param_name_start);
  8662. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8663. auto param_name =
  8664. pattern.substr(param_name_start, sep_pos - param_name_start);
  8665. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8666. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8667. std::string msg = "Encountered path parameter '" + param_name +
  8668. "' multiple times in route pattern '" + pattern + "'.";
  8669. throw std::invalid_argument(msg);
  8670. }
  8671. #endif
  8672. param_names_.push_back(std::move(param_name));
  8673. last_param_end = sep_pos + 1;
  8674. }
  8675. if (last_param_end < pattern.length()) {
  8676. static_fragments_.push_back(pattern.substr(last_param_end));
  8677. }
  8678. }
  8679. inline bool PathParamsMatcher::match(Request &request) const {
  8680. request.matches = std::smatch();
  8681. request.path_params.clear();
  8682. request.path_params.reserve(param_names_.size());
  8683. // One past the position at which the path matched the pattern last time
  8684. std::size_t starting_pos = 0;
  8685. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  8686. const auto &fragment = static_fragments_[i];
  8687. if (starting_pos + fragment.length() > request.path.length()) {
  8688. return false;
  8689. }
  8690. // Avoid unnecessary allocation by using strncmp instead of substr +
  8691. // comparison
  8692. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  8693. fragment.length()) != 0) {
  8694. return false;
  8695. }
  8696. starting_pos += fragment.length();
  8697. // Should only happen when we have a static fragment after a param
  8698. // Example: '/users/:id/subscriptions'
  8699. // The 'subscriptions' fragment here does not have a corresponding param
  8700. if (i >= param_names_.size()) { continue; }
  8701. auto sep_pos = request.path.find(separator, starting_pos);
  8702. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  8703. const auto &param_name = param_names_[i];
  8704. request.path_params.emplace(
  8705. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  8706. // Mark everything up to '/' as matched
  8707. starting_pos = sep_pos + 1;
  8708. }
  8709. // Returns false if the path is longer than the pattern
  8710. return starting_pos >= request.path.length();
  8711. }
  8712. inline bool RegexMatcher::match(Request &request) const {
  8713. request.path_params.clear();
  8714. return std::regex_match(request.path, request.matches, regex_);
  8715. }
  8716. // Enclose IPv6 address in brackets if needed
  8717. inline std::string prepare_host_string(const std::string &host) {
  8718. // Enclose IPv6 address in brackets (but not if already enclosed)
  8719. if (host.find(':') == std::string::npos ||
  8720. (!host.empty() && host[0] == '[')) {
  8721. // IPv4, hostname, or already bracketed IPv6
  8722. return host;
  8723. } else {
  8724. // IPv6 address without brackets
  8725. return "[" + host + "]";
  8726. }
  8727. }
  8728. inline std::string make_host_and_port_string(const std::string &host, int port,
  8729. bool is_ssl) {
  8730. auto result = prepare_host_string(host);
  8731. // Append port if not default
  8732. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  8733. ; // do nothing
  8734. } else {
  8735. result += ":" + std::to_string(port);
  8736. }
  8737. return result;
  8738. }
  8739. // Create "host:port" string always including port number (for CONNECT method)
  8740. inline std::string
  8741. make_host_and_port_string_always_port(const std::string &host, int port) {
  8742. return prepare_host_string(host) + ":" + std::to_string(port);
  8743. }
  8744. template <typename T>
  8745. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  8746. T header_writer, Error &error) {
  8747. for (const auto &h : headers) {
  8748. if (!detail::fields::is_field_name(h.first) ||
  8749. !detail::fields::is_field_value(h.second)) {
  8750. error = Error::InvalidHeaders;
  8751. return false;
  8752. }
  8753. }
  8754. if (header_writer(strm, headers) <= 0) {
  8755. error = Error::Write;
  8756. return false;
  8757. }
  8758. return true;
  8759. }
  8760. } // namespace detail
  8761. /*
  8762. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  8763. */
  8764. #ifdef CPPHTTPLIB_SSL_ENABLED
  8765. namespace detail {
  8766. // SSL socket stream implementation
  8767. inline SSLSocketStream::SSLSocketStream(
  8768. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  8769. time_t read_timeout_usec, time_t write_timeout_sec,
  8770. time_t write_timeout_usec, time_t max_timeout_msec,
  8771. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8772. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  8773. read_timeout_usec_(read_timeout_usec),
  8774. write_timeout_sec_(write_timeout_sec),
  8775. write_timeout_usec_(write_timeout_usec),
  8776. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  8777. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8778. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  8779. // Note: create_session() also clears this, but SSLClient currently
  8780. // uses ssl_new() which does not. Until full TLS API migration is complete,
  8781. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  8782. // SSL session was created.
  8783. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  8784. #endif
  8785. }
  8786. inline SSLSocketStream::~SSLSocketStream() = default;
  8787. inline bool SSLSocketStream::is_readable() const {
  8788. return tls::pending(session_) > 0;
  8789. }
  8790. inline bool SSLSocketStream::wait_readable() const {
  8791. if (max_timeout_msec_ <= 0) {
  8792. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8793. }
  8794. time_t read_timeout_sec;
  8795. time_t read_timeout_usec;
  8796. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8797. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8798. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8799. }
  8800. inline bool SSLSocketStream::wait_writable() const {
  8801. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  8802. !tls::is_peer_closed(session_, sock_);
  8803. }
  8804. inline bool SSLSocketStream::is_peer_alive() const {
  8805. return !tls::is_peer_closed(session_, sock_);
  8806. }
  8807. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  8808. if (tls::pending(session_) > 0) {
  8809. tls::TlsError err;
  8810. auto ret = tls::read(session_, ptr, size, err);
  8811. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  8812. error_ = Error::ConnectionClosed;
  8813. }
  8814. return ret;
  8815. } else if (wait_readable()) {
  8816. tls::TlsError err;
  8817. auto ret = tls::read(session_, ptr, size, err);
  8818. if (ret < 0) {
  8819. auto n = 1000;
  8820. #ifdef _WIN32
  8821. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  8822. (err.code == tls::ErrorCode::SyscallError &&
  8823. WSAGetLastError() == WSAETIMEDOUT))) {
  8824. #else
  8825. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  8826. #endif
  8827. if (tls::pending(session_) > 0) {
  8828. return tls::read(session_, ptr, size, err);
  8829. } else if (wait_readable()) {
  8830. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8831. ret = tls::read(session_, ptr, size, err);
  8832. if (ret >= 0) { return ret; }
  8833. } else {
  8834. break;
  8835. }
  8836. }
  8837. assert(ret < 0);
  8838. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  8839. error_ = Error::ConnectionClosed;
  8840. }
  8841. return ret;
  8842. } else {
  8843. error_ = Error::Timeout;
  8844. return -1;
  8845. }
  8846. }
  8847. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  8848. if (wait_writable()) {
  8849. auto handle_size =
  8850. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  8851. tls::TlsError err;
  8852. auto ret = tls::write(session_, ptr, handle_size, err);
  8853. if (ret < 0) {
  8854. auto n = 1000;
  8855. #ifdef _WIN32
  8856. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  8857. (err.code == tls::ErrorCode::SyscallError &&
  8858. WSAGetLastError() == WSAETIMEDOUT))) {
  8859. #else
  8860. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  8861. #endif
  8862. if (wait_writable()) {
  8863. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8864. ret = tls::write(session_, ptr, handle_size, err);
  8865. if (ret >= 0) { return ret; }
  8866. } else {
  8867. break;
  8868. }
  8869. }
  8870. assert(ret < 0);
  8871. }
  8872. return ret;
  8873. }
  8874. return -1;
  8875. }
  8876. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  8877. int &port) const {
  8878. detail::get_remote_ip_and_port(sock_, ip, port);
  8879. }
  8880. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  8881. int &port) const {
  8882. detail::get_local_ip_and_port(sock_, ip, port);
  8883. }
  8884. inline socket_t SSLSocketStream::socket() const { return sock_; }
  8885. inline time_t SSLSocketStream::duration() const {
  8886. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8887. std::chrono::steady_clock::now() - start_time_)
  8888. .count();
  8889. }
  8890. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  8891. read_timeout_sec_ = sec;
  8892. read_timeout_usec_ = usec;
  8893. }
  8894. } // namespace detail
  8895. #endif // CPPHTTPLIB_SSL_ENABLED
  8896. /*
  8897. * Group 4: Server implementation
  8898. */
  8899. // HTTP server implementation
  8900. inline Server::Server()
  8901. : new_task_queue([] {
  8902. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  8903. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  8904. }) {
  8905. #ifndef _WIN32
  8906. signal(SIGPIPE, SIG_IGN);
  8907. #endif
  8908. }
  8909. inline Server::~Server() = default;
  8910. inline std::unique_ptr<detail::MatcherBase>
  8911. Server::make_matcher(const std::string &pattern) {
  8912. if (pattern.find("/:") != std::string::npos) {
  8913. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  8914. } else {
  8915. return detail::make_unique<detail::RegexMatcher>(pattern);
  8916. }
  8917. }
  8918. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  8919. return add_handler(get_handlers_, pattern, std::move(handler));
  8920. }
  8921. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  8922. return add_handler(post_handlers_, pattern, std::move(handler));
  8923. }
  8924. inline Server &Server::Post(const std::string &pattern,
  8925. HandlerWithContentReader handler) {
  8926. return add_handler(post_handlers_for_content_reader_, pattern,
  8927. std::move(handler));
  8928. }
  8929. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  8930. return add_handler(put_handlers_, pattern, std::move(handler));
  8931. }
  8932. inline Server &Server::Put(const std::string &pattern,
  8933. HandlerWithContentReader handler) {
  8934. return add_handler(put_handlers_for_content_reader_, pattern,
  8935. std::move(handler));
  8936. }
  8937. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  8938. return add_handler(patch_handlers_, pattern, std::move(handler));
  8939. }
  8940. inline Server &Server::Patch(const std::string &pattern,
  8941. HandlerWithContentReader handler) {
  8942. return add_handler(patch_handlers_for_content_reader_, pattern,
  8943. std::move(handler));
  8944. }
  8945. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  8946. return add_handler(delete_handlers_, pattern, std::move(handler));
  8947. }
  8948. inline Server &Server::Delete(const std::string &pattern,
  8949. HandlerWithContentReader handler) {
  8950. return add_handler(delete_handlers_for_content_reader_, pattern,
  8951. std::move(handler));
  8952. }
  8953. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  8954. return add_handler(options_handlers_, pattern, std::move(handler));
  8955. }
  8956. inline Server &Server::WebSocket(const std::string &pattern,
  8957. WebSocketHandler handler) {
  8958. websocket_handlers_.push_back(
  8959. {make_matcher(pattern), std::move(handler), nullptr});
  8960. return *this;
  8961. }
  8962. inline Server &Server::WebSocket(const std::string &pattern,
  8963. WebSocketHandler handler,
  8964. SubProtocolSelector sub_protocol_selector) {
  8965. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  8966. std::move(sub_protocol_selector)});
  8967. return *this;
  8968. }
  8969. inline bool Server::set_base_dir(const std::string &dir,
  8970. const std::string &mount_point) {
  8971. return set_mount_point(mount_point, dir);
  8972. }
  8973. inline bool Server::set_mount_point(const std::string &mount_point,
  8974. const std::string &dir, Headers headers) {
  8975. detail::FileStat stat(dir);
  8976. if (stat.is_dir()) {
  8977. std::string mnt = !mount_point.empty() ? mount_point : "/";
  8978. if (!mnt.empty() && mnt[0] == '/') {
  8979. std::string resolved_base;
  8980. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  8981. #if defined(_WIN32)
  8982. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  8983. resolved_base += '\\';
  8984. }
  8985. #else
  8986. if (resolved_base.back() != '/') { resolved_base += '/'; }
  8987. #endif
  8988. }
  8989. base_dirs_.push_back(
  8990. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  8991. return true;
  8992. }
  8993. }
  8994. return false;
  8995. }
  8996. inline bool Server::remove_mount_point(const std::string &mount_point) {
  8997. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  8998. if (it->mount_point == mount_point) {
  8999. base_dirs_.erase(it);
  9000. return true;
  9001. }
  9002. }
  9003. return false;
  9004. }
  9005. inline Server &
  9006. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9007. const std::string &mime) {
  9008. file_extension_and_mimetype_map_[ext] = mime;
  9009. return *this;
  9010. }
  9011. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9012. default_file_mimetype_ = mime;
  9013. return *this;
  9014. }
  9015. inline Server &Server::set_file_request_handler(Handler handler) {
  9016. file_request_handler_ = std::move(handler);
  9017. return *this;
  9018. }
  9019. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9020. std::true_type) {
  9021. error_handler_ = std::move(handler);
  9022. return *this;
  9023. }
  9024. inline Server &Server::set_error_handler_core(Handler handler,
  9025. std::false_type) {
  9026. error_handler_ = [handler](const Request &req, Response &res) {
  9027. handler(req, res);
  9028. return HandlerResponse::Handled;
  9029. };
  9030. return *this;
  9031. }
  9032. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9033. exception_handler_ = std::move(handler);
  9034. return *this;
  9035. }
  9036. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9037. pre_routing_handler_ = std::move(handler);
  9038. return *this;
  9039. }
  9040. inline Server &Server::set_post_routing_handler(Handler handler) {
  9041. post_routing_handler_ = std::move(handler);
  9042. return *this;
  9043. }
  9044. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9045. pre_request_handler_ = std::move(handler);
  9046. return *this;
  9047. }
  9048. inline Server &Server::set_logger(Logger logger) {
  9049. logger_ = std::move(logger);
  9050. return *this;
  9051. }
  9052. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9053. error_logger_ = std::move(error_logger);
  9054. return *this;
  9055. }
  9056. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9057. pre_compression_logger_ = std::move(logger);
  9058. return *this;
  9059. }
  9060. inline Server &
  9061. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9062. expect_100_continue_handler_ = std::move(handler);
  9063. return *this;
  9064. }
  9065. inline Server &Server::set_address_family(int family) {
  9066. address_family_ = family;
  9067. return *this;
  9068. }
  9069. inline Server &Server::set_tcp_nodelay(bool on) {
  9070. tcp_nodelay_ = on;
  9071. return *this;
  9072. }
  9073. inline Server &Server::set_ipv6_v6only(bool on) {
  9074. ipv6_v6only_ = on;
  9075. return *this;
  9076. }
  9077. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9078. socket_options_ = std::move(socket_options);
  9079. return *this;
  9080. }
  9081. inline Server &Server::set_default_headers(Headers headers) {
  9082. default_headers_ = std::move(headers);
  9083. return *this;
  9084. }
  9085. inline Server &Server::set_header_writer(
  9086. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9087. header_writer_ = writer;
  9088. return *this;
  9089. }
  9090. inline Server &
  9091. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9092. trusted_proxies_ = proxies;
  9093. return *this;
  9094. }
  9095. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9096. keep_alive_max_count_ = count;
  9097. return *this;
  9098. }
  9099. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9100. keep_alive_timeout_sec_ = sec;
  9101. return *this;
  9102. }
  9103. template <class Rep, class Period>
  9104. inline Server &Server::set_keep_alive_timeout(
  9105. const std::chrono::duration<Rep, Period> &duration) {
  9106. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9107. set_keep_alive_timeout(sec);
  9108. });
  9109. return *this;
  9110. }
  9111. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9112. read_timeout_sec_ = sec;
  9113. read_timeout_usec_ = usec;
  9114. return *this;
  9115. }
  9116. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9117. write_timeout_sec_ = sec;
  9118. write_timeout_usec_ = usec;
  9119. return *this;
  9120. }
  9121. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9122. idle_interval_sec_ = sec;
  9123. idle_interval_usec_ = usec;
  9124. return *this;
  9125. }
  9126. inline Server &Server::set_payload_max_length(size_t length) {
  9127. payload_max_length_ = length;
  9128. return *this;
  9129. }
  9130. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9131. websocket_max_missed_pongs_ = count;
  9132. return *this;
  9133. }
  9134. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9135. websocket_ping_interval_sec_ = sec;
  9136. return *this;
  9137. }
  9138. template <class Rep, class Period>
  9139. inline Server &Server::set_websocket_ping_interval(
  9140. const std::chrono::duration<Rep, Period> &duration) {
  9141. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9142. set_websocket_ping_interval(sec);
  9143. });
  9144. return *this;
  9145. }
  9146. inline bool Server::bind_to_port(const std::string &host, int port,
  9147. int socket_flags) {
  9148. auto ret = bind_internal(host, port, socket_flags);
  9149. if (ret == -1) { is_decommissioned = true; }
  9150. return ret >= 0;
  9151. }
  9152. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9153. auto ret = bind_internal(host, 0, socket_flags);
  9154. if (ret == -1) { is_decommissioned = true; }
  9155. return ret;
  9156. }
  9157. inline bool Server::listen_after_bind() { return listen_internal(); }
  9158. inline bool Server::listen(const std::string &host, int port,
  9159. int socket_flags) {
  9160. return bind_to_port(host, port, socket_flags) && listen_internal();
  9161. }
  9162. inline bool Server::is_running() const { return is_running_; }
  9163. inline void Server::wait_until_ready() const {
  9164. while (!is_running_ && !is_decommissioned) {
  9165. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9166. }
  9167. }
  9168. inline void Server::stop() {
  9169. if (is_running_) {
  9170. assert(svr_sock_ != INVALID_SOCKET);
  9171. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9172. detail::shutdown_socket(sock);
  9173. detail::close_socket(sock);
  9174. }
  9175. is_decommissioned = false;
  9176. }
  9177. inline void Server::decommission() { is_decommissioned = true; }
  9178. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9179. auto len = strlen(s);
  9180. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9181. len -= 2;
  9182. {
  9183. size_t count = 0;
  9184. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9185. switch (count) {
  9186. case 0: req.method = std::string(b, e); break;
  9187. case 1: req.target = std::string(b, e); break;
  9188. case 2: req.version = std::string(b, e); break;
  9189. default: break;
  9190. }
  9191. count++;
  9192. });
  9193. if (count != 3) { return false; }
  9194. }
  9195. thread_local const std::set<std::string> methods{
  9196. "GET", "HEAD", "POST", "PUT", "DELETE",
  9197. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9198. if (methods.find(req.method) == methods.end()) {
  9199. output_error_log(Error::InvalidHTTPMethod, &req);
  9200. return false;
  9201. }
  9202. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9203. output_error_log(Error::InvalidHTTPVersion, &req);
  9204. return false;
  9205. }
  9206. {
  9207. // Skip URL fragment
  9208. for (size_t i = 0; i < req.target.size(); i++) {
  9209. if (req.target[i] == '#') {
  9210. req.target.erase(i);
  9211. break;
  9212. }
  9213. }
  9214. detail::divide(req.target, '?',
  9215. [&](const char *lhs_data, std::size_t lhs_size,
  9216. const char *rhs_data, std::size_t rhs_size) {
  9217. req.path =
  9218. decode_path_component(std::string(lhs_data, lhs_size));
  9219. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9220. });
  9221. }
  9222. return true;
  9223. }
  9224. inline bool Server::write_response(Stream &strm, bool close_connection,
  9225. Request &req, Response &res) {
  9226. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9227. // incorrectly to the error content.
  9228. req.ranges.clear();
  9229. return write_response_core(strm, close_connection, req, res, false);
  9230. }
  9231. inline bool Server::write_response_with_content(Stream &strm,
  9232. bool close_connection,
  9233. const Request &req,
  9234. Response &res) {
  9235. return write_response_core(strm, close_connection, req, res, true);
  9236. }
  9237. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9238. const Request &req, Response &res,
  9239. bool need_apply_ranges) {
  9240. assert(res.status != -1);
  9241. if (400 <= res.status && error_handler_ &&
  9242. error_handler_(req, res) == HandlerResponse::Handled) {
  9243. need_apply_ranges = true;
  9244. }
  9245. std::string content_type;
  9246. std::string boundary;
  9247. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9248. // Prepare additional headers
  9249. if (close_connection || req.get_header_value("Connection") == "close" ||
  9250. 400 <= res.status) { // Don't leave connections open after errors
  9251. res.set_header("Connection", "close");
  9252. } else {
  9253. std::string s = "timeout=";
  9254. s += std::to_string(keep_alive_timeout_sec_);
  9255. s += ", max=";
  9256. s += std::to_string(keep_alive_max_count_);
  9257. res.set_header("Keep-Alive", s);
  9258. }
  9259. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9260. !res.has_header("Content-Type")) {
  9261. res.set_header("Content-Type", "text/plain");
  9262. }
  9263. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9264. !res.has_header("Content-Length")) {
  9265. res.set_header("Content-Length", "0");
  9266. }
  9267. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9268. res.set_header("Accept-Ranges", "bytes");
  9269. }
  9270. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9271. // Response line and headers
  9272. detail::BufferStream bstrm;
  9273. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9274. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9275. // Combine small body with headers to reduce write syscalls
  9276. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9277. bstrm.write(res.body.data(), res.body.size());
  9278. }
  9279. // Log before writing to avoid race condition with client-side code that
  9280. // accesses logger-captured data immediately after receiving the response.
  9281. output_log(req, res);
  9282. // Flush buffer
  9283. auto &data = bstrm.get_buffer();
  9284. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9285. // Streaming body
  9286. auto ret = true;
  9287. if (req.method != "HEAD" && res.content_provider_) {
  9288. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9289. res.content_provider_success_ = true;
  9290. } else {
  9291. ret = false;
  9292. }
  9293. }
  9294. return ret;
  9295. }
  9296. inline bool
  9297. Server::write_content_with_provider(Stream &strm, const Request &req,
  9298. Response &res, const std::string &boundary,
  9299. const std::string &content_type) {
  9300. auto is_shutting_down = [this]() {
  9301. return this->svr_sock_ == INVALID_SOCKET;
  9302. };
  9303. if (res.content_length_ > 0) {
  9304. if (req.ranges.empty()) {
  9305. return detail::write_content(strm, res.content_provider_, 0,
  9306. res.content_length_, is_shutting_down);
  9307. } else if (req.ranges.size() == 1) {
  9308. auto offset_and_length = detail::get_range_offset_and_length(
  9309. req.ranges[0], res.content_length_);
  9310. return detail::write_content(strm, res.content_provider_,
  9311. offset_and_length.first,
  9312. offset_and_length.second, is_shutting_down);
  9313. } else {
  9314. return detail::write_multipart_ranges_data(
  9315. strm, req, res, boundary, content_type, res.content_length_,
  9316. is_shutting_down);
  9317. }
  9318. } else {
  9319. if (res.is_chunked_content_provider_) {
  9320. auto type = detail::encoding_type(req, res);
  9321. auto compressor = detail::make_compressor(type);
  9322. if (!compressor) {
  9323. compressor = detail::make_unique<detail::nocompressor>();
  9324. }
  9325. return detail::write_content_chunked(strm, res.content_provider_,
  9326. is_shutting_down, *compressor);
  9327. } else {
  9328. return detail::write_content_without_length(strm, res.content_provider_,
  9329. is_shutting_down);
  9330. }
  9331. }
  9332. }
  9333. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9334. FormFields::iterator cur_field;
  9335. FormFiles::iterator cur_file;
  9336. auto is_text_field = false;
  9337. size_t count = 0;
  9338. if (read_content_core(
  9339. strm, req, res,
  9340. // Regular
  9341. [&](const char *buf, size_t n) {
  9342. // Prevent arithmetic overflow when checking sizes.
  9343. // Avoid computing (req.body.size() + n) directly because
  9344. // adding two unsigned `size_t` values can wrap around and
  9345. // produce a small result instead of indicating overflow.
  9346. // Instead, check using subtraction: ensure `n` does not
  9347. // exceed the remaining capacity `max_size() - size()`.
  9348. if (req.body.size() >= req.body.max_size() ||
  9349. n > req.body.max_size() - req.body.size()) {
  9350. return false;
  9351. }
  9352. // Limit decompressed body size to payload_max_length_ to protect
  9353. // against "zip bomb" attacks where a small compressed payload
  9354. // decompresses to a massive size.
  9355. if (payload_max_length_ > 0 &&
  9356. (req.body.size() >= payload_max_length_ ||
  9357. n > payload_max_length_ - req.body.size())) {
  9358. return false;
  9359. }
  9360. req.body.append(buf, n);
  9361. return true;
  9362. },
  9363. // Multipart FormData
  9364. [&](const FormData &file) {
  9365. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9366. output_error_log(Error::TooManyFormDataFiles, &req);
  9367. return false;
  9368. }
  9369. if (file.filename.empty()) {
  9370. cur_field = req.form.fields.emplace(
  9371. file.name, FormField{file.name, file.content, file.headers});
  9372. is_text_field = true;
  9373. } else {
  9374. cur_file = req.form.files.emplace(file.name, file);
  9375. is_text_field = false;
  9376. }
  9377. return true;
  9378. },
  9379. [&](const char *buf, size_t n) {
  9380. if (is_text_field) {
  9381. auto &content = cur_field->second.content;
  9382. if (content.size() + n > content.max_size()) { return false; }
  9383. content.append(buf, n);
  9384. } else {
  9385. auto &content = cur_file->second.content;
  9386. if (content.size() + n > content.max_size()) { return false; }
  9387. content.append(buf, n);
  9388. }
  9389. return true;
  9390. })) {
  9391. const auto &content_type = req.get_header_value("Content-Type");
  9392. if (detail::extract_media_type(content_type) ==
  9393. "application/x-www-form-urlencoded") {
  9394. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9395. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9396. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9397. return false;
  9398. }
  9399. detail::parse_query_text(req.body, req.params);
  9400. }
  9401. return true;
  9402. }
  9403. return false;
  9404. }
  9405. inline bool Server::read_content_with_content_receiver(
  9406. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9407. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9408. return read_content_core(strm, req, res, std::move(receiver),
  9409. std::move(multipart_header),
  9410. std::move(multipart_receiver));
  9411. }
  9412. inline bool Server::read_content_core(
  9413. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9414. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9415. detail::FormDataParser multipart_form_data_parser;
  9416. ContentReceiverWithProgress out;
  9417. if (req.is_multipart_form_data()) {
  9418. const auto &content_type = req.get_header_value("Content-Type");
  9419. std::string boundary;
  9420. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9421. res.status = StatusCode::BadRequest_400;
  9422. output_error_log(Error::MultipartParsing, &req);
  9423. return false;
  9424. }
  9425. multipart_form_data_parser.set_boundary(std::move(boundary));
  9426. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9427. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9428. multipart_receiver);
  9429. };
  9430. } else {
  9431. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9432. size_t /*len*/) { return receiver(buf, n); };
  9433. }
  9434. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  9435. // are true (no Transfer-Encoding and no Content-Length), then the message
  9436. // body length is zero (no message body is present).
  9437. //
  9438. // For non-SSL builds, detect clients that send a body without a
  9439. // Content-Length header (raw HTTP over TCP). Check both the stream's
  9440. // internal read buffer (data already read from the socket during header
  9441. // parsing) and the socket itself for pending data. If data is found and
  9442. // exceeds the configured payload limit, reject with 413.
  9443. // For SSL builds we cannot reliably peek the decrypted application bytes,
  9444. // so keep the original behaviour.
  9445. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9446. if (!req.has_header("Content-Length") &&
  9447. !detail::is_chunked_transfer_encoding(req.headers)) {
  9448. // Only check if payload_max_length is set to a finite value
  9449. if (payload_max_length_ > 0 &&
  9450. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9451. // Check if there is data already buffered in the stream (read during
  9452. // header parsing) or pending on the socket. Use a non-blocking socket
  9453. // check to avoid deadlock when the client sends no body.
  9454. bool has_data = strm.is_readable();
  9455. if (!has_data) {
  9456. socket_t s = strm.socket();
  9457. if (s != INVALID_SOCKET) {
  9458. has_data = detail::select_read(s, 0, 0) > 0;
  9459. }
  9460. }
  9461. if (has_data) {
  9462. auto result =
  9463. detail::read_content_without_length(strm, payload_max_length_, out);
  9464. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9465. res.status = StatusCode::PayloadTooLarge_413;
  9466. return false;
  9467. } else if (result != detail::ReadContentResult::Success) {
  9468. return false;
  9469. }
  9470. return true;
  9471. }
  9472. }
  9473. return true;
  9474. }
  9475. #else
  9476. if (!req.has_header("Content-Length") &&
  9477. !detail::is_chunked_transfer_encoding(req.headers)) {
  9478. return true;
  9479. }
  9480. #endif
  9481. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9482. out, true)) {
  9483. return false;
  9484. }
  9485. req.body_consumed_ = true;
  9486. if (req.is_multipart_form_data()) {
  9487. if (!multipart_form_data_parser.is_valid()) {
  9488. res.status = StatusCode::BadRequest_400;
  9489. output_error_log(Error::MultipartParsing, &req);
  9490. return false;
  9491. }
  9492. }
  9493. return true;
  9494. }
  9495. inline bool Server::handle_file_request(Request &req, Response &res) {
  9496. for (const auto &entry : base_dirs_) {
  9497. // Prefix match
  9498. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9499. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9500. if (detail::is_valid_path(sub_path)) {
  9501. auto path = entry.base_dir + sub_path;
  9502. if (path.back() == '/') { path += "index.html"; }
  9503. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9504. // but symlinks/junctions can still escape the base directory.
  9505. if (!entry.resolved_base_dir.empty()) {
  9506. std::string resolved_path;
  9507. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9508. !detail::is_path_within_base(resolved_path,
  9509. entry.resolved_base_dir)) {
  9510. res.status = StatusCode::Forbidden_403;
  9511. return true;
  9512. }
  9513. }
  9514. detail::FileStat stat(path);
  9515. if (stat.is_dir()) {
  9516. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9517. return true;
  9518. }
  9519. if (stat.is_file()) {
  9520. for (const auto &kv : entry.headers) {
  9521. res.set_header(kv.first, kv.second);
  9522. }
  9523. auto etag = detail::compute_etag(stat);
  9524. if (!etag.empty()) { res.set_header("ETag", etag); }
  9525. auto mtime = stat.mtime();
  9526. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9527. if (!last_modified.empty()) {
  9528. res.set_header("Last-Modified", last_modified);
  9529. }
  9530. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9531. check_if_range(req, etag, mtime);
  9532. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9533. if (!mm->is_open()) {
  9534. output_error_log(Error::OpenFile, &req);
  9535. return false;
  9536. }
  9537. res.set_content_provider(
  9538. mm->size(),
  9539. detail::find_content_type(path, file_extension_and_mimetype_map_,
  9540. default_file_mimetype_),
  9541. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9542. sink.write(mm->data() + offset, length);
  9543. return true;
  9544. });
  9545. if (req.method != "HEAD" && file_request_handler_) {
  9546. file_request_handler_(req, res);
  9547. }
  9548. return true;
  9549. } else {
  9550. output_error_log(Error::OpenFile, &req);
  9551. }
  9552. }
  9553. }
  9554. }
  9555. return false;
  9556. }
  9557. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  9558. const std::string &etag,
  9559. time_t mtime) const {
  9560. // Handle conditional GET:
  9561. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  9562. // 2. If-Modified-Since is checked only when If-None-Match is absent
  9563. if (req.has_header("If-None-Match")) {
  9564. if (!etag.empty()) {
  9565. auto val = req.get_header_value("If-None-Match");
  9566. // NOTE: We use exact string matching here. This works correctly
  9567. // because our server always generates weak ETags (W/"..."), and
  9568. // clients typically send back the same ETag they received.
  9569. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  9570. // If-None-Match, where W/"x" and "x" would match, but this
  9571. // simplified implementation requires exact matches.
  9572. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  9573. [&](const char *b, const char *e) {
  9574. auto seg_len = static_cast<size_t>(e - b);
  9575. return (seg_len == 1 && *b == '*') ||
  9576. (seg_len == etag.size() &&
  9577. std::equal(b, e, etag.begin()));
  9578. });
  9579. if (ret) {
  9580. res.status = StatusCode::NotModified_304;
  9581. return true;
  9582. }
  9583. }
  9584. } else if (req.has_header("If-Modified-Since")) {
  9585. auto val = req.get_header_value("If-Modified-Since");
  9586. auto t = detail::parse_http_date(val);
  9587. if (t != static_cast<time_t>(-1) && mtime <= t) {
  9588. res.status = StatusCode::NotModified_304;
  9589. return true;
  9590. }
  9591. }
  9592. return false;
  9593. }
  9594. inline bool Server::check_if_range(Request &req, const std::string &etag,
  9595. time_t mtime) const {
  9596. // Handle If-Range for partial content requests (RFC 9110
  9597. // Section 13.1.5). If-Range is only evaluated when Range header is
  9598. // present. If the validator matches, serve partial content; otherwise
  9599. // serve full content.
  9600. if (!req.ranges.empty() && req.has_header("If-Range")) {
  9601. auto val = req.get_header_value("If-Range");
  9602. auto is_valid_range = [&]() {
  9603. if (detail::is_strong_etag(val)) {
  9604. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  9605. // comparison.
  9606. return (!etag.empty() && val == etag);
  9607. } else if (detail::is_weak_etag(val)) {
  9608. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  9609. return false;
  9610. } else {
  9611. // HTTP-date comparison
  9612. auto t = detail::parse_http_date(val);
  9613. return (t != static_cast<time_t>(-1) && mtime <= t);
  9614. }
  9615. };
  9616. if (!is_valid_range()) {
  9617. // Validator doesn't match: ignore Range and serve full content
  9618. req.ranges.clear();
  9619. return false;
  9620. }
  9621. }
  9622. return true;
  9623. }
  9624. inline socket_t
  9625. Server::create_server_socket(const std::string &host, int port,
  9626. int socket_flags,
  9627. SocketOptions socket_options) const {
  9628. return detail::create_socket(
  9629. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  9630. ipv6_v6only_, std::move(socket_options),
  9631. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  9632. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  9633. output_error_log(Error::BindIPAddress, nullptr);
  9634. return false;
  9635. }
  9636. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  9637. output_error_log(Error::Listen, nullptr);
  9638. return false;
  9639. }
  9640. return true;
  9641. });
  9642. }
  9643. inline int Server::bind_internal(const std::string &host, int port,
  9644. int socket_flags) {
  9645. if (is_decommissioned) { return -1; }
  9646. if (!is_valid()) { return -1; }
  9647. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  9648. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  9649. if (port == 0) {
  9650. struct sockaddr_storage addr;
  9651. socklen_t addr_len = sizeof(addr);
  9652. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  9653. &addr_len) == -1) {
  9654. output_error_log(Error::GetSockName, nullptr);
  9655. return -1;
  9656. }
  9657. if (addr.ss_family == AF_INET) {
  9658. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  9659. } else if (addr.ss_family == AF_INET6) {
  9660. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  9661. } else {
  9662. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  9663. return -1;
  9664. }
  9665. } else {
  9666. return port;
  9667. }
  9668. }
  9669. inline bool Server::listen_internal() {
  9670. if (is_decommissioned) { return false; }
  9671. auto ret = true;
  9672. is_running_ = true;
  9673. auto se = detail::scope_exit([&]() { is_running_ = false; });
  9674. {
  9675. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  9676. while (svr_sock_ != INVALID_SOCKET) {
  9677. #ifndef _WIN32
  9678. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  9679. #endif
  9680. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  9681. idle_interval_usec_);
  9682. if (val == 0) { // Timeout
  9683. task_queue->on_idle();
  9684. continue;
  9685. }
  9686. #ifndef _WIN32
  9687. }
  9688. #endif
  9689. #if defined _WIN32
  9690. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  9691. // OVERLAPPED
  9692. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  9693. #elif defined SOCK_CLOEXEC
  9694. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  9695. #else
  9696. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  9697. #endif
  9698. if (sock == INVALID_SOCKET) {
  9699. if (errno == EMFILE) {
  9700. // The per-process limit of open file descriptors has been reached.
  9701. // Try to accept new connections after a short sleep.
  9702. std::this_thread::sleep_for(std::chrono::microseconds{1});
  9703. continue;
  9704. } else if (errno == EINTR || errno == EAGAIN) {
  9705. continue;
  9706. }
  9707. if (svr_sock_ != INVALID_SOCKET) {
  9708. detail::close_socket(svr_sock_);
  9709. ret = false;
  9710. output_error_log(Error::Connection, nullptr);
  9711. } else {
  9712. ; // The server socket was closed by user.
  9713. }
  9714. break;
  9715. }
  9716. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  9717. read_timeout_sec_, read_timeout_usec_);
  9718. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  9719. write_timeout_sec_, write_timeout_usec_);
  9720. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  9721. if (!task_queue->enqueue(
  9722. [this, sock]() { process_and_close_socket(sock); })) {
  9723. output_error_log(Error::ResourceExhaustion, nullptr);
  9724. detail::shutdown_socket(sock);
  9725. detail::close_socket(sock);
  9726. }
  9727. }
  9728. task_queue->shutdown();
  9729. }
  9730. is_decommissioned = !ret;
  9731. return ret;
  9732. }
  9733. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  9734. if (pre_routing_handler_ &&
  9735. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  9736. return true;
  9737. }
  9738. // File handler
  9739. if ((req.method == "GET" || req.method == "HEAD") &&
  9740. handle_file_request(req, res)) {
  9741. return true;
  9742. }
  9743. if (detail::expect_content(req)) {
  9744. // Content reader handler
  9745. {
  9746. // Track whether the ContentReader was aborted due to the decompressed
  9747. // payload exceeding `payload_max_length_`.
  9748. // The user handler runs after the lambda returns, so we must restore the
  9749. // 413 status if the handler overwrites it.
  9750. bool content_reader_payload_too_large = false;
  9751. ContentReader reader(
  9752. [&](ContentReceiver receiver) {
  9753. auto result = read_content_with_content_receiver(
  9754. strm, req, res, std::move(receiver), nullptr, nullptr);
  9755. if (!result) {
  9756. output_error_log(Error::Read, &req);
  9757. if (res.status == StatusCode::PayloadTooLarge_413) {
  9758. content_reader_payload_too_large = true;
  9759. }
  9760. }
  9761. return result;
  9762. },
  9763. [&](FormDataHeader header, ContentReceiver receiver) {
  9764. auto result = read_content_with_content_receiver(
  9765. strm, req, res, nullptr, std::move(header),
  9766. std::move(receiver));
  9767. if (!result) {
  9768. output_error_log(Error::Read, &req);
  9769. if (res.status == StatusCode::PayloadTooLarge_413) {
  9770. content_reader_payload_too_large = true;
  9771. }
  9772. }
  9773. return result;
  9774. });
  9775. bool dispatched = false;
  9776. if (req.method == "POST") {
  9777. dispatched = dispatch_request_for_content_reader(
  9778. req, res, std::move(reader), post_handlers_for_content_reader_);
  9779. } else if (req.method == "PUT") {
  9780. dispatched = dispatch_request_for_content_reader(
  9781. req, res, std::move(reader), put_handlers_for_content_reader_);
  9782. } else if (req.method == "PATCH") {
  9783. dispatched = dispatch_request_for_content_reader(
  9784. req, res, std::move(reader), patch_handlers_for_content_reader_);
  9785. } else if (req.method == "DELETE") {
  9786. dispatched = dispatch_request_for_content_reader(
  9787. req, res, std::move(reader), delete_handlers_for_content_reader_);
  9788. }
  9789. if (dispatched) {
  9790. if (content_reader_payload_too_large) {
  9791. // Enforce the limit: override any status the handler may have set
  9792. // and return false so the error path sends a plain 413 response.
  9793. res.status = StatusCode::PayloadTooLarge_413;
  9794. res.body.clear();
  9795. res.content_length_ = 0;
  9796. res.content_provider_ = nullptr;
  9797. return false;
  9798. }
  9799. return true;
  9800. }
  9801. }
  9802. // Read content into `req.body`
  9803. if (!read_content(strm, req, res)) {
  9804. output_error_log(Error::Read, &req);
  9805. return false;
  9806. }
  9807. }
  9808. // Regular handler
  9809. if (req.method == "GET" || req.method == "HEAD") {
  9810. return dispatch_request(req, res, get_handlers_);
  9811. } else if (req.method == "POST") {
  9812. return dispatch_request(req, res, post_handlers_);
  9813. } else if (req.method == "PUT") {
  9814. return dispatch_request(req, res, put_handlers_);
  9815. } else if (req.method == "DELETE") {
  9816. return dispatch_request(req, res, delete_handlers_);
  9817. } else if (req.method == "OPTIONS") {
  9818. return dispatch_request(req, res, options_handlers_);
  9819. } else if (req.method == "PATCH") {
  9820. return dispatch_request(req, res, patch_handlers_);
  9821. }
  9822. res.status = StatusCode::BadRequest_400;
  9823. return false;
  9824. }
  9825. inline bool Server::dispatch_request(Request &req, Response &res,
  9826. const Handlers &handlers) const {
  9827. for (const auto &x : handlers) {
  9828. const auto &matcher = x.first;
  9829. const auto &handler = x.second;
  9830. if (matcher->match(req)) {
  9831. req.matched_route = matcher->pattern();
  9832. if (!pre_request_handler_ ||
  9833. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  9834. handler(req, res);
  9835. }
  9836. return true;
  9837. }
  9838. }
  9839. return false;
  9840. }
  9841. inline void Server::apply_ranges(const Request &req, Response &res,
  9842. std::string &content_type,
  9843. std::string &boundary) const {
  9844. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  9845. auto it = res.headers.find("Content-Type");
  9846. if (it != res.headers.end()) {
  9847. content_type = it->second;
  9848. res.headers.erase(it);
  9849. }
  9850. boundary = detail::make_multipart_data_boundary();
  9851. res.set_header("Content-Type",
  9852. "multipart/byteranges; boundary=" + boundary);
  9853. }
  9854. auto type = detail::encoding_type(req, res);
  9855. if (res.body.empty()) {
  9856. if (res.content_length_ > 0) {
  9857. size_t length = 0;
  9858. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  9859. length = res.content_length_;
  9860. } else if (req.ranges.size() == 1) {
  9861. auto offset_and_length = detail::get_range_offset_and_length(
  9862. req.ranges[0], res.content_length_);
  9863. length = offset_and_length.second;
  9864. auto content_range = detail::make_content_range_header_field(
  9865. offset_and_length, res.content_length_);
  9866. res.set_header("Content-Range", content_range);
  9867. } else {
  9868. length = detail::get_multipart_ranges_data_length(
  9869. req, boundary, content_type, res.content_length_);
  9870. }
  9871. res.set_header("Content-Length", std::to_string(length));
  9872. } else {
  9873. if (res.content_provider_) {
  9874. if (res.is_chunked_content_provider_) {
  9875. res.set_header("Transfer-Encoding", "chunked");
  9876. if (type != detail::EncodingType::None) {
  9877. res.set_header("Content-Encoding", detail::encoding_name(type));
  9878. res.set_header("Vary", "Accept-Encoding");
  9879. }
  9880. }
  9881. }
  9882. }
  9883. } else {
  9884. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  9885. ;
  9886. } else if (req.ranges.size() == 1) {
  9887. auto offset_and_length =
  9888. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  9889. auto offset = offset_and_length.first;
  9890. auto length = offset_and_length.second;
  9891. auto content_range = detail::make_content_range_header_field(
  9892. offset_and_length, res.body.size());
  9893. res.set_header("Content-Range", content_range);
  9894. assert(offset + length <= res.body.size());
  9895. res.body = res.body.substr(offset, length);
  9896. } else {
  9897. std::string data;
  9898. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  9899. res.body.size(), data);
  9900. res.body.swap(data);
  9901. }
  9902. if (type != detail::EncodingType::None) {
  9903. output_pre_compression_log(req, res);
  9904. if (auto compressor = detail::make_compressor(type)) {
  9905. std::string compressed;
  9906. if (compressor->compress(res.body.data(), res.body.size(), true,
  9907. [&](const char *data, size_t data_len) {
  9908. compressed.append(data, data_len);
  9909. return true;
  9910. })) {
  9911. res.body.swap(compressed);
  9912. res.set_header("Content-Encoding", detail::encoding_name(type));
  9913. res.set_header("Vary", "Accept-Encoding");
  9914. }
  9915. }
  9916. }
  9917. auto length = std::to_string(res.body.size());
  9918. res.set_header("Content-Length", length);
  9919. }
  9920. }
  9921. inline bool Server::dispatch_request_for_content_reader(
  9922. Request &req, Response &res, ContentReader content_reader,
  9923. const HandlersForContentReader &handlers) const {
  9924. for (const auto &x : handlers) {
  9925. const auto &matcher = x.first;
  9926. const auto &handler = x.second;
  9927. if (matcher->match(req)) {
  9928. req.matched_route = matcher->pattern();
  9929. if (!pre_request_handler_ ||
  9930. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  9931. handler(req, res, content_reader);
  9932. }
  9933. return true;
  9934. }
  9935. }
  9936. return false;
  9937. }
  9938. inline std::string
  9939. get_client_ip(const std::string &x_forwarded_for,
  9940. const std::vector<std::string> &trusted_proxies) {
  9941. // X-Forwarded-For is a comma-separated list per RFC 7239
  9942. std::vector<std::string> ip_list;
  9943. detail::split(x_forwarded_for.data(),
  9944. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  9945. [&](const char *b, const char *e) {
  9946. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  9947. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  9948. });
  9949. for (size_t i = 0; i < ip_list.size(); ++i) {
  9950. auto ip = ip_list[i];
  9951. auto is_trusted_proxy =
  9952. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  9953. [&](const std::string &proxy) { return ip == proxy; });
  9954. if (is_trusted_proxy) {
  9955. if (i == 0) {
  9956. // If the trusted proxy is the first IP, there's no preceding client IP
  9957. return ip;
  9958. } else {
  9959. // Return the IP immediately before the trusted proxy
  9960. return ip_list[i - 1];
  9961. }
  9962. }
  9963. }
  9964. // If no trusted proxy is found, return the first IP in the list
  9965. return ip_list.front();
  9966. }
  9967. inline bool
  9968. Server::process_request(Stream &strm, const std::string &remote_addr,
  9969. int remote_port, const std::string &local_addr,
  9970. int local_port, bool close_connection,
  9971. bool &connection_closed,
  9972. const std::function<void(Request &)> &setup_request,
  9973. bool *websocket_upgraded) {
  9974. std::array<char, 2048> buf{};
  9975. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  9976. // Connection has been closed on client
  9977. if (!line_reader.getline()) { return false; }
  9978. Request req;
  9979. req.start_time_ = std::chrono::steady_clock::now();
  9980. req.remote_addr = remote_addr;
  9981. req.remote_port = remote_port;
  9982. req.local_addr = local_addr;
  9983. req.local_port = local_port;
  9984. Response res;
  9985. res.version = "HTTP/1.1";
  9986. res.headers = default_headers_;
  9987. // Request line and headers
  9988. if (!parse_request_line(line_reader.ptr(), req)) {
  9989. res.status = StatusCode::BadRequest_400;
  9990. output_error_log(Error::InvalidRequestLine, &req);
  9991. return write_response(strm, close_connection, req, res);
  9992. }
  9993. // Request headers
  9994. if (!detail::read_headers(strm, req.headers)) {
  9995. res.status = StatusCode::BadRequest_400;
  9996. output_error_log(Error::InvalidHeaders, &req);
  9997. return write_response(strm, close_connection, req, res);
  9998. }
  9999. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10000. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10001. // tolerated for compatibility with existing clients.
  10002. if (req.get_header_value_u64("Content-Length") > 0 &&
  10003. req.has_header("Transfer-Encoding")) {
  10004. connection_closed = true;
  10005. res.status = StatusCode::BadRequest_400;
  10006. return write_response(strm, close_connection, req, res);
  10007. }
  10008. // Check if the request URI doesn't exceed the limit
  10009. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10010. connection_closed = true;
  10011. res.status = StatusCode::UriTooLong_414;
  10012. output_error_log(Error::ExceedUriMaxLength, &req);
  10013. return write_response(strm, close_connection, req, res);
  10014. }
  10015. if (req.get_header_value("Connection") == "close") {
  10016. connection_closed = true;
  10017. }
  10018. if (req.version == "HTTP/1.0" &&
  10019. req.get_header_value("Connection") != "Keep-Alive") {
  10020. connection_closed = true;
  10021. }
  10022. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10023. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10024. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  10025. } else {
  10026. req.remote_addr = remote_addr;
  10027. }
  10028. req.remote_port = remote_port;
  10029. req.local_addr = local_addr;
  10030. req.local_port = local_port;
  10031. if (req.has_header("Accept")) {
  10032. const auto &accept_header = req.get_header_value("Accept");
  10033. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10034. connection_closed = true;
  10035. res.status = StatusCode::BadRequest_400;
  10036. output_error_log(Error::HTTPParsing, &req);
  10037. return write_response(strm, close_connection, req, res);
  10038. }
  10039. }
  10040. if (req.has_header("Range")) {
  10041. const auto &range_header_value = req.get_header_value("Range");
  10042. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10043. connection_closed = true;
  10044. res.status = StatusCode::RangeNotSatisfiable_416;
  10045. output_error_log(Error::InvalidRangeHeader, &req);
  10046. return write_response(strm, close_connection, req, res);
  10047. }
  10048. }
  10049. if (setup_request) { setup_request(req); }
  10050. if (req.get_header_value("Expect") == "100-continue") {
  10051. int status = StatusCode::Continue_100;
  10052. if (expect_100_continue_handler_) {
  10053. status = expect_100_continue_handler_(req, res);
  10054. }
  10055. switch (status) {
  10056. case StatusCode::Continue_100:
  10057. case StatusCode::ExpectationFailed_417:
  10058. detail::write_response_line(strm, status);
  10059. strm.write("\r\n");
  10060. break;
  10061. default:
  10062. connection_closed = true;
  10063. return write_response(strm, true, req, res);
  10064. }
  10065. }
  10066. // Setup `is_connection_closed` method
  10067. auto sock = strm.socket();
  10068. req.is_connection_closed = [sock]() {
  10069. return !detail::is_socket_alive(sock);
  10070. };
  10071. // WebSocket upgrade
  10072. // Check pre_routing_handler_ before upgrading so that authentication
  10073. // and other middleware can reject the request with an HTTP response
  10074. // (e.g., 401) before the protocol switches.
  10075. if (detail::is_websocket_upgrade(req)) {
  10076. if (pre_routing_handler_ &&
  10077. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10078. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10079. return write_response(strm, close_connection, req, res);
  10080. }
  10081. // Find matching WebSocket handler
  10082. for (const auto &entry : websocket_handlers_) {
  10083. if (entry.matcher->match(req)) {
  10084. // Compute accept key
  10085. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10086. auto accept_key = detail::websocket_accept_key(client_key);
  10087. // Negotiate subprotocol
  10088. std::string selected_subprotocol;
  10089. if (entry.sub_protocol_selector) {
  10090. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10091. if (!protocol_header.empty()) {
  10092. std::vector<std::string> protocols;
  10093. std::istringstream iss(protocol_header);
  10094. std::string token;
  10095. while (std::getline(iss, token, ',')) {
  10096. // Trim whitespace
  10097. auto start = token.find_first_not_of(' ');
  10098. auto end = token.find_last_not_of(' ');
  10099. if (start != std::string::npos) {
  10100. protocols.push_back(token.substr(start, end - start + 1));
  10101. }
  10102. }
  10103. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10104. }
  10105. }
  10106. // Send 101 Switching Protocols
  10107. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10108. "Upgrade: websocket\r\n"
  10109. "Connection: Upgrade\r\n"
  10110. "Sec-WebSocket-Accept: " +
  10111. accept_key + "\r\n";
  10112. if (!selected_subprotocol.empty()) {
  10113. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10114. return false;
  10115. }
  10116. handshake_response +=
  10117. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10118. }
  10119. handshake_response += "\r\n";
  10120. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10121. 0) {
  10122. return false;
  10123. }
  10124. connection_closed = true;
  10125. if (websocket_upgraded) { *websocket_upgraded = true; }
  10126. {
  10127. // Use WebSocket-specific read timeout instead of HTTP timeout
  10128. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10129. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10130. websocket_max_missed_pongs_);
  10131. entry.handler(req, ws);
  10132. }
  10133. return true;
  10134. }
  10135. }
  10136. // No matching handler - fall through to 404
  10137. }
  10138. // Routing
  10139. auto routed = false;
  10140. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10141. routed = routing(req, res, strm);
  10142. #else
  10143. try {
  10144. routed = routing(req, res, strm);
  10145. } catch (std::exception &) {
  10146. if (exception_handler_) {
  10147. auto ep = std::current_exception();
  10148. exception_handler_(req, res, ep);
  10149. routed = true;
  10150. } else {
  10151. res.status = StatusCode::InternalServerError_500;
  10152. }
  10153. } catch (...) {
  10154. if (exception_handler_) {
  10155. auto ep = std::current_exception();
  10156. exception_handler_(req, res, ep);
  10157. routed = true;
  10158. } else {
  10159. res.status = StatusCode::InternalServerError_500;
  10160. }
  10161. }
  10162. #endif
  10163. auto ret = false;
  10164. if (routed) {
  10165. if (res.status == -1) {
  10166. res.status = req.ranges.empty() ? StatusCode::OK_200
  10167. : StatusCode::PartialContent_206;
  10168. }
  10169. // Serve file content by using a content provider
  10170. auto file_open_error = false;
  10171. if (!res.file_content_path_.empty()) {
  10172. const auto &path = res.file_content_path_;
  10173. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10174. if (!mm->is_open()) {
  10175. res.body.clear();
  10176. res.content_length_ = 0;
  10177. res.content_provider_ = nullptr;
  10178. res.status = StatusCode::NotFound_404;
  10179. output_error_log(Error::OpenFile, &req);
  10180. file_open_error = true;
  10181. } else {
  10182. auto content_type = res.file_content_content_type_;
  10183. if (content_type.empty()) {
  10184. content_type = detail::find_content_type(
  10185. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10186. }
  10187. res.set_content_provider(
  10188. mm->size(), content_type,
  10189. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10190. sink.write(mm->data() + offset, length);
  10191. return true;
  10192. });
  10193. }
  10194. }
  10195. if (file_open_error) {
  10196. ret = write_response(strm, close_connection, req, res);
  10197. } else if (detail::range_error(req, res)) {
  10198. res.body.clear();
  10199. res.content_length_ = 0;
  10200. res.content_provider_ = nullptr;
  10201. res.status = StatusCode::RangeNotSatisfiable_416;
  10202. ret = write_response(strm, close_connection, req, res);
  10203. } else {
  10204. ret = write_response_with_content(strm, close_connection, req, res);
  10205. }
  10206. } else {
  10207. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10208. ret = write_response(strm, close_connection, req, res);
  10209. }
  10210. // Drain any unconsumed request body to prevent request smuggling on
  10211. // keep-alive connections.
  10212. if (!req.body_consumed_ && detail::expect_content(req)) {
  10213. int drain_status = 200; // required by read_content signature
  10214. if (!detail::read_content(
  10215. strm, req, payload_max_length_, drain_status, nullptr,
  10216. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10217. // Body exceeds payload limit or read error — close the connection
  10218. // to prevent leftover bytes from being misinterpreted.
  10219. connection_closed = true;
  10220. }
  10221. }
  10222. return ret;
  10223. }
  10224. inline bool Server::is_valid() const { return true; }
  10225. inline bool Server::process_and_close_socket(socket_t sock) {
  10226. std::string remote_addr;
  10227. int remote_port = 0;
  10228. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10229. std::string local_addr;
  10230. int local_port = 0;
  10231. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10232. bool websocket_upgraded = false;
  10233. auto ret = detail::process_server_socket(
  10234. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10235. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10236. write_timeout_usec_,
  10237. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10238. return process_request(strm, remote_addr, remote_port, local_addr,
  10239. local_port, close_connection, connection_closed,
  10240. nullptr, &websocket_upgraded);
  10241. });
  10242. detail::shutdown_socket(sock);
  10243. detail::close_socket(sock);
  10244. return ret;
  10245. }
  10246. inline void Server::output_log(const Request &req, const Response &res) const {
  10247. if (logger_) {
  10248. std::lock_guard<std::mutex> guard(logger_mutex_);
  10249. logger_(req, res);
  10250. }
  10251. }
  10252. inline void Server::output_pre_compression_log(const Request &req,
  10253. const Response &res) const {
  10254. if (pre_compression_logger_) {
  10255. std::lock_guard<std::mutex> guard(logger_mutex_);
  10256. pre_compression_logger_(req, res);
  10257. }
  10258. }
  10259. inline void Server::output_error_log(const Error &err,
  10260. const Request *req) const {
  10261. if (error_logger_) {
  10262. std::lock_guard<std::mutex> guard(logger_mutex_);
  10263. error_logger_(err, req);
  10264. }
  10265. }
  10266. /*
  10267. * Group 5: ClientImpl and Client (Universal) implementation
  10268. */
  10269. // HTTP client implementation
  10270. inline ClientImpl::ClientImpl(const std::string &host)
  10271. : ClientImpl(host, 80, std::string(), std::string()) {}
  10272. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10273. : ClientImpl(host, port, std::string(), std::string()) {}
  10274. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10275. const std::string &client_cert_path,
  10276. const std::string &client_key_path)
  10277. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10278. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10279. inline ClientImpl::~ClientImpl() {
  10280. // Wait until all the requests in flight are handled.
  10281. size_t retry_count = 10;
  10282. while (retry_count-- > 0) {
  10283. {
  10284. std::lock_guard<std::mutex> guard(socket_mutex_);
  10285. if (socket_requests_in_flight_ == 0) { break; }
  10286. }
  10287. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10288. }
  10289. std::lock_guard<std::mutex> guard(socket_mutex_);
  10290. shutdown_socket(socket_);
  10291. close_socket(socket_);
  10292. }
  10293. inline bool ClientImpl::is_valid() const { return true; }
  10294. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10295. client_cert_path_ = rhs.client_cert_path_;
  10296. client_key_path_ = rhs.client_key_path_;
  10297. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10298. read_timeout_sec_ = rhs.read_timeout_sec_;
  10299. read_timeout_usec_ = rhs.read_timeout_usec_;
  10300. write_timeout_sec_ = rhs.write_timeout_sec_;
  10301. write_timeout_usec_ = rhs.write_timeout_usec_;
  10302. max_timeout_msec_ = rhs.max_timeout_msec_;
  10303. basic_auth_username_ = rhs.basic_auth_username_;
  10304. basic_auth_password_ = rhs.basic_auth_password_;
  10305. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10306. keep_alive_ = rhs.keep_alive_;
  10307. follow_location_ = rhs.follow_location_;
  10308. path_encode_ = rhs.path_encode_;
  10309. address_family_ = rhs.address_family_;
  10310. tcp_nodelay_ = rhs.tcp_nodelay_;
  10311. ipv6_v6only_ = rhs.ipv6_v6only_;
  10312. socket_options_ = rhs.socket_options_;
  10313. compress_ = rhs.compress_;
  10314. decompress_ = rhs.decompress_;
  10315. payload_max_length_ = rhs.payload_max_length_;
  10316. has_payload_max_length_ = rhs.has_payload_max_length_;
  10317. interface_ = rhs.interface_;
  10318. proxy_host_ = rhs.proxy_host_;
  10319. proxy_port_ = rhs.proxy_port_;
  10320. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10321. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10322. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10323. logger_ = rhs.logger_;
  10324. error_logger_ = rhs.error_logger_;
  10325. #ifdef CPPHTTPLIB_SSL_ENABLED
  10326. digest_auth_username_ = rhs.digest_auth_username_;
  10327. digest_auth_password_ = rhs.digest_auth_password_;
  10328. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10329. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10330. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10331. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10332. server_certificate_verification_ = rhs.server_certificate_verification_;
  10333. server_hostname_verification_ = rhs.server_hostname_verification_;
  10334. #endif
  10335. }
  10336. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10337. if (!proxy_host_.empty() && proxy_port_ != -1) {
  10338. return detail::create_client_socket(
  10339. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10340. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10341. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10342. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10343. }
  10344. // Check is custom IP specified for host_
  10345. std::string ip;
  10346. auto it = addr_map_.find(host_);
  10347. if (it != addr_map_.end()) { ip = it->second; }
  10348. return detail::create_client_socket(
  10349. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10350. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10351. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10352. write_timeout_usec_, interface_, error);
  10353. }
  10354. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10355. Error &error) {
  10356. auto sock = create_client_socket(error);
  10357. if (sock == INVALID_SOCKET) { return false; }
  10358. socket.sock = sock;
  10359. return true;
  10360. }
  10361. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10362. return create_and_connect_socket(socket, error);
  10363. }
  10364. inline bool ClientImpl::setup_proxy_connection(
  10365. Socket & /*socket*/,
  10366. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10367. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10368. return true;
  10369. }
  10370. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10371. bool /*shutdown_gracefully*/) {
  10372. // If there are any requests in flight from threads other than us, then it's
  10373. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10374. assert(socket_requests_in_flight_ == 0 ||
  10375. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10376. }
  10377. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10378. if (socket.sock == INVALID_SOCKET) { return; }
  10379. detail::shutdown_socket(socket.sock);
  10380. }
  10381. inline void ClientImpl::close_socket(Socket &socket) {
  10382. // If there are requests in flight in another thread, usually closing
  10383. // the socket will be fine and they will simply receive an error when
  10384. // using the closed socket, but it is still a bug since rarely the OS
  10385. // may reassign the socket id to be used for a new socket, and then
  10386. // suddenly they will be operating on a live socket that is different
  10387. // than the one they intended!
  10388. assert(socket_requests_in_flight_ == 0 ||
  10389. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10390. // It is also a bug if this happens while SSL is still active
  10391. #ifdef CPPHTTPLIB_SSL_ENABLED
  10392. assert(socket.ssl == nullptr);
  10393. #endif
  10394. if (socket.sock == INVALID_SOCKET) { return; }
  10395. detail::close_socket(socket.sock);
  10396. socket.sock = INVALID_SOCKET;
  10397. }
  10398. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10399. Response &res,
  10400. bool skip_100_continue) const {
  10401. std::array<char, 2048> buf{};
  10402. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10403. if (!line_reader.getline()) { return false; }
  10404. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10405. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10406. #else
  10407. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10408. #endif
  10409. std::cmatch m;
  10410. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10411. return req.method == "CONNECT";
  10412. }
  10413. res.version = std::string(m[1]);
  10414. res.status = std::stoi(std::string(m[2]));
  10415. res.reason = std::string(m[3]);
  10416. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10417. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10418. if (!line_reader.getline()) { return false; } // CRLF
  10419. if (!line_reader.getline()) { return false; } // next response line
  10420. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10421. res.version = std::string(m[1]);
  10422. res.status = std::stoi(std::string(m[2]));
  10423. res.reason = std::string(m[3]);
  10424. }
  10425. return true;
  10426. }
  10427. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10428. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10429. auto ret = send_(req, res, error);
  10430. if (error == Error::SSLPeerCouldBeClosed_) {
  10431. assert(!ret);
  10432. ret = send_(req, res, error);
  10433. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10434. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10435. }
  10436. return ret;
  10437. }
  10438. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10439. {
  10440. std::lock_guard<std::mutex> guard(socket_mutex_);
  10441. // Set this to false immediately - if it ever gets set to true by the end
  10442. // of the request, we know another thread instructed us to close the
  10443. // socket.
  10444. socket_should_be_closed_when_request_is_done_ = false;
  10445. auto is_alive = false;
  10446. if (socket_.is_open()) {
  10447. is_alive = detail::is_socket_alive(socket_.sock);
  10448. #ifdef CPPHTTPLIB_SSL_ENABLED
  10449. if (is_alive && is_ssl()) {
  10450. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10451. is_alive = false;
  10452. }
  10453. }
  10454. #endif
  10455. if (!is_alive) {
  10456. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  10457. // seems like the other side has already closed the connection Also,
  10458. // there cannot be any requests in flight from other threads since we
  10459. // locked request_mutex_, so safe to close everything immediately
  10460. const bool shutdown_gracefully = false;
  10461. shutdown_ssl(socket_, shutdown_gracefully);
  10462. shutdown_socket(socket_);
  10463. close_socket(socket_);
  10464. }
  10465. }
  10466. if (!is_alive) {
  10467. if (!ensure_socket_connection(socket_, error)) {
  10468. output_error_log(error, &req);
  10469. return false;
  10470. }
  10471. {
  10472. auto success = true;
  10473. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10474. error)) {
  10475. if (!success) { output_error_log(error, &req); }
  10476. return success;
  10477. }
  10478. }
  10479. }
  10480. // Mark the current socket as being in use so that it cannot be closed by
  10481. // anyone else while this request is ongoing, even though we will be
  10482. // releasing the mutex.
  10483. if (socket_requests_in_flight_ > 1) {
  10484. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10485. }
  10486. socket_requests_in_flight_ += 1;
  10487. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10488. }
  10489. for (const auto &header : default_headers_) {
  10490. if (req.headers.find(header.first) == req.headers.end()) {
  10491. req.headers.insert(header);
  10492. }
  10493. }
  10494. auto ret = false;
  10495. auto close_connection = !keep_alive_;
  10496. auto se = detail::scope_exit([&]() {
  10497. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10498. std::lock_guard<std::mutex> guard(socket_mutex_);
  10499. socket_requests_in_flight_ -= 1;
  10500. if (socket_requests_in_flight_ <= 0) {
  10501. assert(socket_requests_in_flight_ == 0);
  10502. socket_requests_are_from_thread_ = std::thread::id();
  10503. }
  10504. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10505. !ret) {
  10506. shutdown_ssl(socket_, true);
  10507. shutdown_socket(socket_);
  10508. close_socket(socket_);
  10509. }
  10510. });
  10511. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  10512. return handle_request(strm, req, res, close_connection, error);
  10513. });
  10514. if (!ret) {
  10515. if (error == Error::Success) {
  10516. error = Error::Unknown;
  10517. output_error_log(error, &req);
  10518. }
  10519. }
  10520. return ret;
  10521. }
  10522. inline Result ClientImpl::send(const Request &req) {
  10523. auto req2 = req;
  10524. return send_(std::move(req2));
  10525. }
  10526. inline Result ClientImpl::send_(Request &&req) {
  10527. auto res = detail::make_unique<Response>();
  10528. auto error = Error::Success;
  10529. auto ret = send(req, *res, error);
  10530. #ifdef CPPHTTPLIB_SSL_ENABLED
  10531. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  10532. last_ssl_error_, last_backend_error_};
  10533. #else
  10534. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  10535. #endif
  10536. }
  10537. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  10538. const std::string &ct) {
  10539. (void)for_stream;
  10540. for (const auto &header : default_headers_) {
  10541. if (!r.has_header(header.first)) { r.headers.insert(header); }
  10542. }
  10543. if (!r.has_header("Host")) {
  10544. if (address_family_ == AF_UNIX) {
  10545. r.headers.emplace("Host", "localhost");
  10546. } else {
  10547. r.headers.emplace(
  10548. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  10549. }
  10550. }
  10551. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  10552. if (!r.content_receiver) {
  10553. if (!r.has_header("Accept-Encoding")) {
  10554. std::string accept_encoding;
  10555. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10556. accept_encoding = "br";
  10557. #endif
  10558. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10559. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10560. accept_encoding += "gzip, deflate";
  10561. #endif
  10562. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10563. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10564. accept_encoding += "zstd";
  10565. #endif
  10566. r.set_header("Accept-Encoding", accept_encoding);
  10567. }
  10568. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  10569. if (!r.has_header("User-Agent")) {
  10570. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  10571. r.set_header("User-Agent", agent);
  10572. }
  10573. #endif
  10574. }
  10575. if (!r.body.empty()) {
  10576. if (!ct.empty() && !r.has_header("Content-Type")) {
  10577. r.headers.emplace("Content-Type", ct);
  10578. }
  10579. if (!r.has_header("Content-Length")) {
  10580. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  10581. }
  10582. }
  10583. }
  10584. inline ClientImpl::StreamHandle
  10585. ClientImpl::open_stream(const std::string &method, const std::string &path,
  10586. const Params &params, const Headers &headers,
  10587. const std::string &body,
  10588. const std::string &content_type) {
  10589. StreamHandle handle;
  10590. handle.response = detail::make_unique<Response>();
  10591. handle.error = Error::Success;
  10592. auto query_path = params.empty() ? path : append_query_params(path, params);
  10593. handle.connection_ = detail::make_unique<ClientConnection>();
  10594. {
  10595. std::lock_guard<std::mutex> guard(socket_mutex_);
  10596. auto is_alive = false;
  10597. if (socket_.is_open()) {
  10598. is_alive = detail::is_socket_alive(socket_.sock);
  10599. #ifdef CPPHTTPLIB_SSL_ENABLED
  10600. if (is_alive && is_ssl()) {
  10601. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10602. is_alive = false;
  10603. }
  10604. }
  10605. #endif
  10606. if (!is_alive) {
  10607. shutdown_ssl(socket_, false);
  10608. shutdown_socket(socket_);
  10609. close_socket(socket_);
  10610. }
  10611. }
  10612. if (!is_alive) {
  10613. if (!ensure_socket_connection(socket_, handle.error)) {
  10614. handle.response.reset();
  10615. return handle;
  10616. }
  10617. {
  10618. auto success = true;
  10619. auto start_time = std::chrono::steady_clock::now();
  10620. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  10621. success, handle.error)) {
  10622. if (!success) { handle.response.reset(); }
  10623. return handle;
  10624. }
  10625. }
  10626. }
  10627. transfer_socket_ownership_to_handle(handle);
  10628. }
  10629. #ifdef CPPHTTPLIB_SSL_ENABLED
  10630. if (is_ssl() && handle.connection_->session) {
  10631. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  10632. handle.connection_->sock, handle.connection_->session,
  10633. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10634. write_timeout_usec_);
  10635. } else {
  10636. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  10637. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  10638. write_timeout_sec_, write_timeout_usec_);
  10639. }
  10640. #else
  10641. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  10642. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  10643. write_timeout_sec_, write_timeout_usec_);
  10644. #endif
  10645. handle.stream_ = handle.socket_stream_.get();
  10646. Request req;
  10647. req.method = method;
  10648. req.path = query_path;
  10649. req.headers = headers;
  10650. req.body = body;
  10651. prepare_default_headers(req, true, content_type);
  10652. auto &strm = *handle.stream_;
  10653. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  10654. handle.error = Error::Write;
  10655. handle.response.reset();
  10656. return handle;
  10657. }
  10658. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  10659. handle.error)) {
  10660. handle.response.reset();
  10661. return handle;
  10662. }
  10663. if (!body.empty()) {
  10664. if (strm.write(body.data(), body.size()) < 0) {
  10665. handle.error = Error::Write;
  10666. handle.response.reset();
  10667. return handle;
  10668. }
  10669. }
  10670. if (!read_response_line(strm, req, *handle.response) ||
  10671. !detail::read_headers(strm, handle.response->headers)) {
  10672. handle.error = Error::Read;
  10673. handle.response.reset();
  10674. return handle;
  10675. }
  10676. handle.body_reader_.stream = handle.stream_;
  10677. handle.body_reader_.payload_max_length = payload_max_length_;
  10678. if (handle.response->has_header("Content-Length")) {
  10679. bool is_invalid = false;
  10680. auto content_length = detail::get_header_value_u64(
  10681. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  10682. if (is_invalid) {
  10683. handle.error = Error::Read;
  10684. handle.response.reset();
  10685. return handle;
  10686. }
  10687. handle.body_reader_.has_content_length = true;
  10688. handle.body_reader_.content_length = content_length;
  10689. }
  10690. auto transfer_encoding =
  10691. handle.response->get_header_value("Transfer-Encoding");
  10692. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  10693. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  10694. if (!content_encoding.empty()) {
  10695. handle.decompressor_ = detail::create_decompressor(content_encoding);
  10696. }
  10697. return handle;
  10698. }
  10699. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  10700. if (!is_valid() || !response) { return -1; }
  10701. if (decompressor_) { return read_with_decompression(buf, len); }
  10702. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  10703. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  10704. trailers_parsed_ = true;
  10705. if (body_reader_.chunked_decoder) {
  10706. if (!body_reader_.chunked_decoder->parse_trailers_into(
  10707. response->trailers, response->headers)) {
  10708. return n;
  10709. }
  10710. } else {
  10711. detail::ChunkedDecoder dec(*stream_);
  10712. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  10713. return n;
  10714. }
  10715. }
  10716. }
  10717. return n;
  10718. }
  10719. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  10720. size_t len) {
  10721. if (decompress_offset_ < decompress_buffer_.size()) {
  10722. auto available = decompress_buffer_.size() - decompress_offset_;
  10723. auto to_copy = (std::min)(len, available);
  10724. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  10725. decompress_offset_ += to_copy;
  10726. decompressed_bytes_read_ += to_copy;
  10727. return static_cast<ssize_t>(to_copy);
  10728. }
  10729. decompress_buffer_.clear();
  10730. decompress_offset_ = 0;
  10731. constexpr size_t kDecompressionBufferSize = 8192;
  10732. char compressed_buf[kDecompressionBufferSize];
  10733. while (true) {
  10734. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  10735. sizeof(compressed_buf));
  10736. if (n <= 0) { return n; }
  10737. bool decompress_ok = decompressor_->decompress(
  10738. compressed_buf, static_cast<size_t>(n),
  10739. [this](const char *data, size_t data_len) {
  10740. decompress_buffer_.append(data, data_len);
  10741. auto limit = body_reader_.payload_max_length;
  10742. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  10743. return false;
  10744. }
  10745. return true;
  10746. });
  10747. if (!decompress_ok) {
  10748. body_reader_.last_error = Error::Read;
  10749. return -1;
  10750. }
  10751. if (!decompress_buffer_.empty()) { break; }
  10752. }
  10753. auto to_copy = (std::min)(len, decompress_buffer_.size());
  10754. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  10755. decompress_offset_ = to_copy;
  10756. decompressed_bytes_read_ += to_copy;
  10757. return static_cast<ssize_t>(to_copy);
  10758. }
  10759. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  10760. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  10761. return;
  10762. }
  10763. trailers_parsed_ = true;
  10764. const auto bufsiz = 128;
  10765. char line_buf[bufsiz];
  10766. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  10767. if (!line_reader.getline()) { return; }
  10768. if (!detail::parse_trailers(line_reader, response->trailers,
  10769. response->headers)) {
  10770. return;
  10771. }
  10772. }
  10773. namespace detail {
  10774. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  10775. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  10776. size_t &out_chunk_offset,
  10777. size_t &out_chunk_total) {
  10778. if (finished) { return 0; }
  10779. if (chunk_remaining == 0) {
  10780. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10781. if (!lr.getline()) { return -1; }
  10782. char *endptr = nullptr;
  10783. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  10784. if (endptr == lr.ptr()) { return -1; }
  10785. if (chunk_len == ULONG_MAX) { return -1; }
  10786. if (chunk_len == 0) {
  10787. chunk_remaining = 0;
  10788. finished = true;
  10789. out_chunk_offset = 0;
  10790. out_chunk_total = 0;
  10791. return 0;
  10792. }
  10793. chunk_remaining = static_cast<size_t>(chunk_len);
  10794. last_chunk_total = chunk_remaining;
  10795. last_chunk_offset = 0;
  10796. }
  10797. auto to_read = (std::min)(chunk_remaining, len);
  10798. auto n = strm.read(buf, to_read);
  10799. if (n <= 0) { return -1; }
  10800. auto offset_before = last_chunk_offset;
  10801. last_chunk_offset += static_cast<size_t>(n);
  10802. chunk_remaining -= static_cast<size_t>(n);
  10803. out_chunk_offset = offset_before;
  10804. out_chunk_total = last_chunk_total;
  10805. if (chunk_remaining == 0) {
  10806. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10807. if (!lr.getline()) { return -1; }
  10808. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  10809. }
  10810. return n;
  10811. }
  10812. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  10813. const Headers &src_headers) {
  10814. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  10815. if (!lr.getline()) { return false; }
  10816. return parse_trailers(lr, dest, src_headers);
  10817. }
  10818. } // namespace detail
  10819. inline void
  10820. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  10821. handle.connection_->sock = socket_.sock;
  10822. #ifdef CPPHTTPLIB_SSL_ENABLED
  10823. handle.connection_->session = socket_.ssl;
  10824. socket_.ssl = nullptr;
  10825. #endif
  10826. socket_.sock = INVALID_SOCKET;
  10827. }
  10828. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  10829. Response &res, bool close_connection,
  10830. Error &error) {
  10831. if (req.path.empty()) {
  10832. error = Error::Connection;
  10833. output_error_log(error, &req);
  10834. return false;
  10835. }
  10836. auto req_save = req;
  10837. bool ret;
  10838. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  10839. auto req2 = req;
  10840. req2.path = "http://" +
  10841. detail::make_host_and_port_string(host_, port_, false) +
  10842. req.path;
  10843. ret = process_request(strm, req2, res, close_connection, error);
  10844. req = std::move(req2);
  10845. req.path = req_save.path;
  10846. } else {
  10847. ret = process_request(strm, req, res, close_connection, error);
  10848. }
  10849. if (!ret) { return false; }
  10850. if (res.get_header_value("Connection") == "close" ||
  10851. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  10852. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  10853. // for this to be safe.
  10854. // This is safe to call because handle_request is only called by send_
  10855. // which locks the request mutex during the process. It would be a bug
  10856. // to call it from a different thread since it's a thread-safety issue
  10857. // to do these things to the socket if another thread is using the socket.
  10858. std::lock_guard<std::mutex> guard(socket_mutex_);
  10859. shutdown_ssl(socket_, true);
  10860. shutdown_socket(socket_);
  10861. close_socket(socket_);
  10862. }
  10863. if (300 < res.status && res.status < 400 && follow_location_) {
  10864. req = std::move(req_save);
  10865. ret = redirect(req, res, error);
  10866. }
  10867. #ifdef CPPHTTPLIB_SSL_ENABLED
  10868. if ((res.status == StatusCode::Unauthorized_401 ||
  10869. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  10870. req.authorization_count_ < 5) {
  10871. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  10872. const auto &username =
  10873. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  10874. const auto &password =
  10875. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  10876. if (!username.empty() && !password.empty()) {
  10877. std::map<std::string, std::string> auth;
  10878. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  10879. Request new_req = req;
  10880. new_req.authorization_count_ += 1;
  10881. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  10882. : "Authorization");
  10883. new_req.headers.insert(detail::make_digest_authentication_header(
  10884. req, auth, new_req.authorization_count_, detail::random_string(10),
  10885. username, password, is_proxy));
  10886. Response new_res;
  10887. ret = send(new_req, new_res, error);
  10888. if (ret) { res = std::move(new_res); }
  10889. }
  10890. }
  10891. }
  10892. #endif
  10893. return ret;
  10894. }
  10895. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  10896. if (req.redirect_count_ == 0) {
  10897. error = Error::ExceedRedirectCount;
  10898. output_error_log(error, &req);
  10899. return false;
  10900. }
  10901. auto location = res.get_header_value("location");
  10902. if (location.empty()) { return false; }
  10903. detail::UrlComponents uc;
  10904. if (!detail::parse_url(location, uc)) { return false; }
  10905. // Only follow http/https redirects
  10906. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  10907. return false;
  10908. }
  10909. auto scheme = is_ssl() ? "https" : "http";
  10910. auto next_scheme = std::move(uc.scheme);
  10911. auto next_host = std::move(uc.host);
  10912. auto port_str = std::move(uc.port);
  10913. auto next_path = std::move(uc.path);
  10914. auto next_query = std::move(uc.query);
  10915. auto next_port = port_;
  10916. if (!port_str.empty()) {
  10917. if (!detail::parse_port(port_str, next_port)) { return false; }
  10918. } else if (!next_scheme.empty()) {
  10919. next_port = next_scheme == "https" ? 443 : 80;
  10920. }
  10921. if (next_scheme.empty()) { next_scheme = scheme; }
  10922. if (next_host.empty()) { next_host = host_; }
  10923. if (next_path.empty()) { next_path = "/"; }
  10924. auto path = decode_path_component(next_path) + next_query;
  10925. // Same host redirect - use current client
  10926. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  10927. return detail::redirect(*this, req, res, path, location, error);
  10928. }
  10929. // Cross-host/scheme redirect - create new client with robust setup
  10930. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  10931. path, location, error);
  10932. }
  10933. // New method for robust redirect client creation
  10934. inline bool ClientImpl::create_redirect_client(
  10935. const std::string &scheme, const std::string &host, int port, Request &req,
  10936. Response &res, const std::string &path, const std::string &location,
  10937. Error &error) {
  10938. // Determine if we need SSL
  10939. auto need_ssl = (scheme == "https");
  10940. // Clean up request headers that are host/client specific
  10941. // Remove headers that should not be carried over to new host
  10942. auto headers_to_remove =
  10943. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  10944. for (const auto &header_name : headers_to_remove) {
  10945. auto it = req.headers.find(header_name);
  10946. while (it != req.headers.end()) {
  10947. it = req.headers.erase(it);
  10948. it = req.headers.find(header_name);
  10949. }
  10950. }
  10951. // Create appropriate client type and handle redirect
  10952. if (need_ssl) {
  10953. #ifdef CPPHTTPLIB_SSL_ENABLED
  10954. // Create SSL client for HTTPS redirect
  10955. SSLClient redirect_client(host, port);
  10956. // Setup basic client configuration first
  10957. setup_redirect_client(redirect_client);
  10958. redirect_client.enable_server_certificate_verification(
  10959. server_certificate_verification_);
  10960. redirect_client.enable_server_hostname_verification(
  10961. server_hostname_verification_);
  10962. // Transfer CA certificate to redirect client
  10963. if (!ca_cert_pem_.empty()) {
  10964. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  10965. ca_cert_pem_.size());
  10966. }
  10967. if (!ca_cert_file_path_.empty()) {
  10968. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  10969. }
  10970. // Client certificates are set through constructor for SSLClient
  10971. // NOTE: SSLClient constructor already takes client_cert_path and
  10972. // client_key_path so we need to create it properly if client certs are
  10973. // needed
  10974. // Execute the redirect
  10975. return detail::redirect(redirect_client, req, res, path, location, error);
  10976. #else
  10977. // SSL not supported - set appropriate error
  10978. error = Error::SSLConnection;
  10979. output_error_log(error, &req);
  10980. return false;
  10981. #endif
  10982. } else {
  10983. // HTTP redirect
  10984. ClientImpl redirect_client(host, port);
  10985. // Setup client with robust configuration
  10986. setup_redirect_client(redirect_client);
  10987. // Execute the redirect
  10988. return detail::redirect(redirect_client, req, res, path, location, error);
  10989. }
  10990. }
  10991. // New method for robust client setup (based on basic_manual_redirect.cpp
  10992. // logic)
  10993. template <typename ClientType>
  10994. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  10995. // Copy basic settings first
  10996. client.set_connection_timeout(connection_timeout_sec_);
  10997. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  10998. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  10999. client.set_keep_alive(keep_alive_);
  11000. client.set_follow_location(
  11001. true); // Enable redirects to handle multi-step redirects
  11002. client.set_path_encode(path_encode_);
  11003. client.set_compress(compress_);
  11004. client.set_decompress(decompress_);
  11005. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11006. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11007. // 15.4, credentials must not be forwarded when redirecting to a different
  11008. // host. This function is only called for cross-host redirects; same-host
  11009. // redirects are handled directly in ClientImpl::redirect().
  11010. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  11011. // before proxy auth)
  11012. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11013. // First set proxy host and port
  11014. client.set_proxy(proxy_host_, proxy_port_);
  11015. // Then set proxy authentication (order matters!)
  11016. if (!proxy_basic_auth_username_.empty()) {
  11017. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11018. proxy_basic_auth_password_);
  11019. }
  11020. if (!proxy_bearer_token_auth_token_.empty()) {
  11021. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11022. }
  11023. #ifdef CPPHTTPLIB_SSL_ENABLED
  11024. if (!proxy_digest_auth_username_.empty()) {
  11025. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11026. proxy_digest_auth_password_);
  11027. }
  11028. #endif
  11029. }
  11030. // Copy network and socket settings
  11031. client.set_address_family(address_family_);
  11032. client.set_tcp_nodelay(tcp_nodelay_);
  11033. client.set_ipv6_v6only(ipv6_v6only_);
  11034. if (socket_options_) { client.set_socket_options(socket_options_); }
  11035. if (!interface_.empty()) { client.set_interface(interface_); }
  11036. // Copy logging and headers
  11037. if (logger_) { client.set_logger(logger_); }
  11038. if (error_logger_) { client.set_error_logger(error_logger_); }
  11039. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11040. // Each new client should generate its own headers based on its target host
  11041. }
  11042. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11043. const Request &req,
  11044. Error &error) const {
  11045. auto is_shutting_down = []() { return false; };
  11046. if (req.is_chunked_content_provider_) {
  11047. auto compressor = compress_ ? detail::create_compressor().first
  11048. : std::unique_ptr<detail::compressor>();
  11049. if (!compressor) {
  11050. compressor = detail::make_unique<detail::nocompressor>();
  11051. }
  11052. return detail::write_content_chunked(strm, req.content_provider_,
  11053. is_shutting_down, *compressor, error);
  11054. } else {
  11055. return detail::write_content_with_progress(
  11056. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11057. req.upload_progress, error);
  11058. }
  11059. }
  11060. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11061. bool close_connection, Error &error,
  11062. bool skip_body) {
  11063. // Prepare additional headers
  11064. if (close_connection) {
  11065. if (!req.has_header("Connection")) {
  11066. req.set_header("Connection", "close");
  11067. }
  11068. }
  11069. std::string ct_for_defaults;
  11070. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11071. ct_for_defaults = "text/plain";
  11072. }
  11073. prepare_default_headers(req, false, ct_for_defaults);
  11074. if (req.body.empty()) {
  11075. if (req.content_provider_) {
  11076. if (!req.is_chunked_content_provider_) {
  11077. if (!req.has_header("Content-Length")) {
  11078. auto length = std::to_string(req.content_length_);
  11079. req.set_header("Content-Length", length);
  11080. }
  11081. }
  11082. } else {
  11083. if (req.method == "POST" || req.method == "PUT" ||
  11084. req.method == "PATCH") {
  11085. req.set_header("Content-Length", "0");
  11086. }
  11087. }
  11088. }
  11089. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11090. if (!req.has_header("Authorization")) {
  11091. req.headers.insert(make_basic_authentication_header(
  11092. basic_auth_username_, basic_auth_password_, false));
  11093. }
  11094. }
  11095. if (!proxy_basic_auth_username_.empty() &&
  11096. !proxy_basic_auth_password_.empty()) {
  11097. if (!req.has_header("Proxy-Authorization")) {
  11098. req.headers.insert(make_basic_authentication_header(
  11099. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11100. }
  11101. }
  11102. if (!bearer_token_auth_token_.empty()) {
  11103. if (!req.has_header("Authorization")) {
  11104. req.headers.insert(make_bearer_token_authentication_header(
  11105. bearer_token_auth_token_, false));
  11106. }
  11107. }
  11108. if (!proxy_bearer_token_auth_token_.empty()) {
  11109. if (!req.has_header("Proxy-Authorization")) {
  11110. req.headers.insert(make_bearer_token_authentication_header(
  11111. proxy_bearer_token_auth_token_, true));
  11112. }
  11113. }
  11114. // Request line and headers
  11115. {
  11116. detail::BufferStream bstrm;
  11117. // Extract path and query from req.path
  11118. std::string path_part, query_part;
  11119. auto query_pos = req.path.find('?');
  11120. if (query_pos != std::string::npos) {
  11121. path_part = req.path.substr(0, query_pos);
  11122. query_part = req.path.substr(query_pos + 1);
  11123. } else {
  11124. path_part = req.path;
  11125. query_part = "";
  11126. }
  11127. // Encode path part. If the original `req.path` already contained a
  11128. // query component, preserve its raw query string (including parameter
  11129. // order) instead of reparsing and reassembling it which may reorder
  11130. // parameters due to container ordering (e.g. `Params` uses
  11131. // `std::multimap`). When there is no query in `req.path`, fall back to
  11132. // building a query from `req.params` so existing callers that pass
  11133. // `Params` continue to work.
  11134. auto path_with_query =
  11135. path_encode_ ? detail::encode_path(path_part) : path_part;
  11136. if (!query_part.empty()) {
  11137. // Normalize the query string (decode then re-encode) while preserving
  11138. // the original parameter order.
  11139. auto normalized = detail::normalize_query_string(query_part);
  11140. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11141. // Still populate req.params for handlers/users who read them.
  11142. detail::parse_query_text(query_part, req.params);
  11143. } else {
  11144. // No query in path; parse any query_part (empty) and append params
  11145. // from `req.params` when present (preserves prior behavior for
  11146. // callers who provide Params separately).
  11147. detail::parse_query_text(query_part, req.params);
  11148. if (!req.params.empty()) {
  11149. path_with_query = append_query_params(path_with_query, req.params);
  11150. }
  11151. }
  11152. // Write request line and headers
  11153. detail::write_request_line(bstrm, req.method, path_with_query);
  11154. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11155. error)) {
  11156. output_error_log(error, &req);
  11157. return false;
  11158. }
  11159. // Flush buffer
  11160. auto &data = bstrm.get_buffer();
  11161. if (!detail::write_data(strm, data.data(), data.size())) {
  11162. error = Error::Write;
  11163. output_error_log(error, &req);
  11164. return false;
  11165. }
  11166. }
  11167. // After sending request line and headers, wait briefly for an early server
  11168. // response (e.g. 4xx) and avoid sending a potentially large request body
  11169. // unnecessarily. This workaround is only enabled on Windows because Unix
  11170. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11171. // buffering can accept large writes even when the peer already responded.
  11172. // Check the stream first (which covers SSL via `is_readable()`), then
  11173. // fall back to select on the socket. Only perform the wait for very large
  11174. // request bodies to avoid interfering with normal small requests and
  11175. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11176. // response. Skip this check when using Expect: 100-continue, as the protocol
  11177. // handles early responses properly.
  11178. #if defined(_WIN32)
  11179. if (!skip_body &&
  11180. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11181. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11182. auto start = std::chrono::high_resolution_clock::now();
  11183. for (;;) {
  11184. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11185. // from SSL internals. If the underlying socket is readable, assume an
  11186. // early response may be present.
  11187. auto sock = strm.socket();
  11188. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11189. return false;
  11190. }
  11191. // Fallback to stream-level check for non-socket streams or when the
  11192. // socket isn't reporting readable. Avoid using `is_readable()` for
  11193. // SSL, since `SSL_pending()` may report buffered records that do not
  11194. // indicate a complete application-level response yet.
  11195. if (!is_ssl() && strm.is_readable()) { return false; }
  11196. auto now = std::chrono::high_resolution_clock::now();
  11197. auto elapsed =
  11198. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11199. .count();
  11200. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11201. break;
  11202. }
  11203. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11204. }
  11205. }
  11206. #endif
  11207. // Body
  11208. if (skip_body) { return true; }
  11209. return write_request_body(strm, req, error);
  11210. }
  11211. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11212. Error &error) {
  11213. if (req.body.empty()) {
  11214. return write_content_with_provider(strm, req, error);
  11215. }
  11216. if (req.upload_progress) {
  11217. auto body_size = req.body.size();
  11218. size_t written = 0;
  11219. auto data = req.body.data();
  11220. while (written < body_size) {
  11221. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11222. if (!detail::write_data(strm, data + written, to_write)) {
  11223. error = Error::Write;
  11224. output_error_log(error, &req);
  11225. return false;
  11226. }
  11227. written += to_write;
  11228. if (!req.upload_progress(written, body_size)) {
  11229. error = Error::Canceled;
  11230. output_error_log(error, &req);
  11231. return false;
  11232. }
  11233. }
  11234. } else {
  11235. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11236. error = Error::Write;
  11237. output_error_log(error, &req);
  11238. return false;
  11239. }
  11240. }
  11241. return true;
  11242. }
  11243. inline std::unique_ptr<Response>
  11244. ClientImpl::send_with_content_provider_and_receiver(
  11245. Request &req, const char *body, size_t content_length,
  11246. ContentProvider content_provider,
  11247. ContentProviderWithoutLength content_provider_without_length,
  11248. const std::string &content_type, ContentReceiver content_receiver,
  11249. Error &error) {
  11250. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11251. auto enc = compress_
  11252. ? detail::create_compressor()
  11253. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11254. nullptr, nullptr);
  11255. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11256. if (enc.first && !content_provider_without_length) {
  11257. auto &compressor = enc.first;
  11258. if (content_provider) {
  11259. auto ok = true;
  11260. size_t offset = 0;
  11261. DataSink data_sink;
  11262. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11263. if (ok) {
  11264. auto last = offset + data_len == content_length;
  11265. auto ret = compressor->compress(
  11266. data, data_len, last,
  11267. [&](const char *compressed_data, size_t compressed_data_len) {
  11268. req.body.append(compressed_data, compressed_data_len);
  11269. return true;
  11270. });
  11271. if (ret) {
  11272. offset += data_len;
  11273. } else {
  11274. ok = false;
  11275. }
  11276. }
  11277. return ok;
  11278. };
  11279. while (ok && offset < content_length) {
  11280. if (!content_provider(offset, content_length - offset, data_sink)) {
  11281. error = Error::Canceled;
  11282. output_error_log(error, &req);
  11283. return nullptr;
  11284. }
  11285. }
  11286. } else {
  11287. if (!compressor->compress(body, content_length, true,
  11288. [&](const char *data, size_t data_len) {
  11289. req.body.append(data, data_len);
  11290. return true;
  11291. })) {
  11292. error = Error::Compression;
  11293. output_error_log(error, &req);
  11294. return nullptr;
  11295. }
  11296. }
  11297. } else {
  11298. if (content_provider) {
  11299. req.content_length_ = content_length;
  11300. req.content_provider_ = std::move(content_provider);
  11301. req.is_chunked_content_provider_ = false;
  11302. } else if (content_provider_without_length) {
  11303. req.content_length_ = 0;
  11304. req.content_provider_ = detail::ContentProviderAdapter(
  11305. std::move(content_provider_without_length));
  11306. req.is_chunked_content_provider_ = true;
  11307. req.set_header("Transfer-Encoding", "chunked");
  11308. } else {
  11309. req.body.assign(body, content_length);
  11310. }
  11311. }
  11312. if (content_receiver) {
  11313. req.content_receiver =
  11314. [content_receiver](const char *data, size_t data_length,
  11315. size_t /*offset*/, size_t /*total_length*/) {
  11316. return content_receiver(data, data_length);
  11317. };
  11318. }
  11319. auto res = detail::make_unique<Response>();
  11320. return send(req, *res, error) ? std::move(res) : nullptr;
  11321. }
  11322. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11323. const std::string &method, const std::string &path, const Headers &headers,
  11324. const char *body, size_t content_length, ContentProvider content_provider,
  11325. ContentProviderWithoutLength content_provider_without_length,
  11326. const std::string &content_type, ContentReceiver content_receiver,
  11327. UploadProgress progress) {
  11328. Request req;
  11329. req.method = method;
  11330. req.headers = headers;
  11331. req.path = path;
  11332. req.upload_progress = std::move(progress);
  11333. if (max_timeout_msec_ > 0) {
  11334. req.start_time_ = std::chrono::steady_clock::now();
  11335. }
  11336. auto error = Error::Success;
  11337. auto res = send_with_content_provider_and_receiver(
  11338. req, body, content_length, std::move(content_provider),
  11339. std::move(content_provider_without_length), content_type,
  11340. std::move(content_receiver), error);
  11341. #ifdef CPPHTTPLIB_SSL_ENABLED
  11342. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11343. last_backend_error_};
  11344. #else
  11345. return Result{std::move(res), error, std::move(req.headers)};
  11346. #endif
  11347. }
  11348. inline void ClientImpl::output_log(const Request &req,
  11349. const Response &res) const {
  11350. if (logger_) {
  11351. std::lock_guard<std::mutex> guard(logger_mutex_);
  11352. logger_(req, res);
  11353. }
  11354. }
  11355. inline void ClientImpl::output_error_log(const Error &err,
  11356. const Request *req) const {
  11357. if (error_logger_) {
  11358. std::lock_guard<std::mutex> guard(logger_mutex_);
  11359. error_logger_(err, req);
  11360. }
  11361. }
  11362. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11363. Response &res, bool close_connection,
  11364. Error &error) {
  11365. // Auto-add Expect: 100-continue for large bodies
  11366. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11367. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11368. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11369. req.set_header("Expect", "100-continue");
  11370. }
  11371. }
  11372. // Check for Expect: 100-continue
  11373. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11374. // Send request (skip body if using Expect: 100-continue)
  11375. auto write_request_success =
  11376. write_request(strm, req, close_connection, error, expect_100_continue);
  11377. #ifdef CPPHTTPLIB_SSL_ENABLED
  11378. if (is_ssl() && !expect_100_continue) {
  11379. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  11380. if (!is_proxy_enabled) {
  11381. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11382. error = Error::SSLPeerCouldBeClosed_;
  11383. output_error_log(error, &req);
  11384. return false;
  11385. }
  11386. }
  11387. }
  11388. #endif
  11389. // Handle Expect: 100-continue with timeout
  11390. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11391. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11392. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11393. auto ret = detail::select_read(strm.socket(), sec, usec);
  11394. if (ret <= 0) {
  11395. // Timeout or error: send body anyway (server didn't respond in time)
  11396. if (!write_request_body(strm, req, error)) { return false; }
  11397. expect_100_continue = false; // Switch to normal response handling
  11398. }
  11399. }
  11400. // Receive response and headers
  11401. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11402. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  11403. !detail::read_headers(strm, res.headers)) {
  11404. if (write_request_success) { error = Error::Read; }
  11405. output_error_log(error, &req);
  11406. return false;
  11407. }
  11408. if (!write_request_success) { return false; }
  11409. // Handle Expect: 100-continue response
  11410. if (expect_100_continue) {
  11411. if (res.status == StatusCode::Continue_100) {
  11412. // Server accepted, send the body
  11413. if (!write_request_body(strm, req, error)) { return false; }
  11414. // Read the actual response
  11415. res.headers.clear();
  11416. res.body.clear();
  11417. if (!read_response_line(strm, req, res) ||
  11418. !detail::read_headers(strm, res.headers)) {
  11419. error = Error::Read;
  11420. output_error_log(error, &req);
  11421. return false;
  11422. }
  11423. }
  11424. // If not 100 Continue, server returned an error; proceed with that response
  11425. }
  11426. // Body
  11427. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11428. req.method != "CONNECT") {
  11429. auto redirect = 300 < res.status && res.status < 400 &&
  11430. res.status != StatusCode::NotModified_304 &&
  11431. follow_location_;
  11432. if (req.response_handler && !redirect) {
  11433. if (!req.response_handler(res)) {
  11434. error = Error::Canceled;
  11435. output_error_log(error, &req);
  11436. return false;
  11437. }
  11438. }
  11439. auto out =
  11440. req.content_receiver
  11441. ? static_cast<ContentReceiverWithProgress>(
  11442. [&](const char *buf, size_t n, size_t off, size_t len) {
  11443. if (redirect) { return true; }
  11444. auto ret = req.content_receiver(buf, n, off, len);
  11445. if (!ret) {
  11446. error = Error::Canceled;
  11447. output_error_log(error, &req);
  11448. }
  11449. return ret;
  11450. })
  11451. : static_cast<ContentReceiverWithProgress>(
  11452. [&](const char *buf, size_t n, size_t /*off*/,
  11453. size_t /*len*/) {
  11454. assert(res.body.size() + n <= res.body.max_size());
  11455. if (payload_max_length_ > 0 &&
  11456. (res.body.size() >= payload_max_length_ ||
  11457. n > payload_max_length_ - res.body.size())) {
  11458. return false;
  11459. }
  11460. res.body.append(buf, n);
  11461. return true;
  11462. });
  11463. auto progress = [&](size_t current, size_t total) {
  11464. if (!req.download_progress || redirect) { return true; }
  11465. auto ret = req.download_progress(current, total);
  11466. if (!ret) {
  11467. error = Error::Canceled;
  11468. output_error_log(error, &req);
  11469. }
  11470. return ret;
  11471. };
  11472. if (res.has_header("Content-Length")) {
  11473. if (!req.content_receiver) {
  11474. auto len = res.get_header_value_u64("Content-Length");
  11475. if (len > res.body.max_size()) {
  11476. error = Error::Read;
  11477. output_error_log(error, &req);
  11478. return false;
  11479. }
  11480. res.body.reserve(static_cast<size_t>(len));
  11481. }
  11482. }
  11483. if (res.status != StatusCode::NotModified_304) {
  11484. int dummy_status;
  11485. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  11486. ? (std::numeric_limits<size_t>::max)()
  11487. : payload_max_length_;
  11488. if (!detail::read_content(strm, res, max_length, dummy_status,
  11489. std::move(progress), std::move(out),
  11490. decompress_)) {
  11491. if (error != Error::Canceled) { error = Error::Read; }
  11492. output_error_log(error, &req);
  11493. return false;
  11494. }
  11495. }
  11496. }
  11497. // Log
  11498. output_log(req, res);
  11499. return true;
  11500. }
  11501. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  11502. const std::string &boundary, const UploadFormDataItems &items,
  11503. const FormDataProviderItems &provider_items) const {
  11504. size_t cur_item = 0;
  11505. size_t cur_start = 0;
  11506. // cur_item and cur_start are copied to within the std::function and
  11507. // maintain state between successive calls
  11508. return [&, cur_item, cur_start](size_t offset,
  11509. DataSink &sink) mutable -> bool {
  11510. if (!offset && !items.empty()) {
  11511. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  11512. return true;
  11513. } else if (cur_item < provider_items.size()) {
  11514. if (!cur_start) {
  11515. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  11516. provider_items[cur_item], boundary);
  11517. offset += begin.size();
  11518. cur_start = offset;
  11519. sink.os << begin;
  11520. }
  11521. DataSink cur_sink;
  11522. auto has_data = true;
  11523. cur_sink.write = sink.write;
  11524. cur_sink.done = [&]() { has_data = false; };
  11525. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  11526. return false;
  11527. }
  11528. if (!has_data) {
  11529. sink.os << detail::serialize_multipart_formdata_item_end();
  11530. cur_item++;
  11531. cur_start = 0;
  11532. }
  11533. return true;
  11534. } else {
  11535. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  11536. sink.done();
  11537. return true;
  11538. }
  11539. };
  11540. }
  11541. inline bool ClientImpl::process_socket(
  11542. const Socket &socket,
  11543. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11544. std::function<bool(Stream &strm)> callback) {
  11545. return detail::process_client_socket(
  11546. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11547. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  11548. }
  11549. inline bool ClientImpl::is_ssl() const { return false; }
  11550. inline Result ClientImpl::Get(const std::string &path,
  11551. DownloadProgress progress) {
  11552. return Get(path, Headers(), std::move(progress));
  11553. }
  11554. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11555. const Headers &headers,
  11556. DownloadProgress progress) {
  11557. if (params.empty()) { return Get(path, headers); }
  11558. std::string path_with_query = append_query_params(path, params);
  11559. return Get(path_with_query, headers, std::move(progress));
  11560. }
  11561. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11562. DownloadProgress progress) {
  11563. Request req;
  11564. req.method = "GET";
  11565. req.path = path;
  11566. req.headers = headers;
  11567. req.download_progress = std::move(progress);
  11568. if (max_timeout_msec_ > 0) {
  11569. req.start_time_ = std::chrono::steady_clock::now();
  11570. }
  11571. return send_(std::move(req));
  11572. }
  11573. inline Result ClientImpl::Get(const std::string &path,
  11574. ContentReceiver content_receiver,
  11575. DownloadProgress progress) {
  11576. return Get(path, Headers(), nullptr, std::move(content_receiver),
  11577. std::move(progress));
  11578. }
  11579. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11580. ContentReceiver content_receiver,
  11581. DownloadProgress progress) {
  11582. return Get(path, headers, nullptr, std::move(content_receiver),
  11583. std::move(progress));
  11584. }
  11585. inline Result ClientImpl::Get(const std::string &path,
  11586. ResponseHandler response_handler,
  11587. ContentReceiver content_receiver,
  11588. DownloadProgress progress) {
  11589. return Get(path, Headers(), std::move(response_handler),
  11590. std::move(content_receiver), std::move(progress));
  11591. }
  11592. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  11593. ResponseHandler response_handler,
  11594. ContentReceiver content_receiver,
  11595. DownloadProgress progress) {
  11596. Request req;
  11597. req.method = "GET";
  11598. req.path = path;
  11599. req.headers = headers;
  11600. req.response_handler = std::move(response_handler);
  11601. req.content_receiver =
  11602. [content_receiver](const char *data, size_t data_length,
  11603. size_t /*offset*/, size_t /*total_length*/) {
  11604. return content_receiver(data, data_length);
  11605. };
  11606. req.download_progress = std::move(progress);
  11607. if (max_timeout_msec_ > 0) {
  11608. req.start_time_ = std::chrono::steady_clock::now();
  11609. }
  11610. return send_(std::move(req));
  11611. }
  11612. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11613. const Headers &headers,
  11614. ContentReceiver content_receiver,
  11615. DownloadProgress progress) {
  11616. return Get(path, params, headers, nullptr, std::move(content_receiver),
  11617. std::move(progress));
  11618. }
  11619. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  11620. const Headers &headers,
  11621. ResponseHandler response_handler,
  11622. ContentReceiver content_receiver,
  11623. DownloadProgress progress) {
  11624. if (params.empty()) {
  11625. return Get(path, headers, std::move(response_handler),
  11626. std::move(content_receiver), std::move(progress));
  11627. }
  11628. std::string path_with_query = append_query_params(path, params);
  11629. return Get(path_with_query, headers, std::move(response_handler),
  11630. std::move(content_receiver), std::move(progress));
  11631. }
  11632. inline Result ClientImpl::Head(const std::string &path) {
  11633. return Head(path, Headers());
  11634. }
  11635. inline Result ClientImpl::Head(const std::string &path,
  11636. const Headers &headers) {
  11637. Request req;
  11638. req.method = "HEAD";
  11639. req.headers = headers;
  11640. req.path = path;
  11641. if (max_timeout_msec_ > 0) {
  11642. req.start_time_ = std::chrono::steady_clock::now();
  11643. }
  11644. return send_(std::move(req));
  11645. }
  11646. inline Result ClientImpl::Post(const std::string &path) {
  11647. return Post(path, std::string(), std::string());
  11648. }
  11649. inline Result ClientImpl::Post(const std::string &path,
  11650. const Headers &headers) {
  11651. return Post(path, headers, nullptr, 0, std::string());
  11652. }
  11653. inline Result ClientImpl::Post(const std::string &path, const char *body,
  11654. size_t content_length,
  11655. const std::string &content_type,
  11656. UploadProgress progress) {
  11657. return Post(path, Headers(), body, content_length, content_type, progress);
  11658. }
  11659. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  11660. const std::string &content_type,
  11661. UploadProgress progress) {
  11662. return Post(path, Headers(), body, content_type, progress);
  11663. }
  11664. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  11665. return Post(path, Headers(), params);
  11666. }
  11667. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  11668. ContentProvider content_provider,
  11669. const std::string &content_type,
  11670. UploadProgress progress) {
  11671. return Post(path, Headers(), content_length, std::move(content_provider),
  11672. content_type, progress);
  11673. }
  11674. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  11675. ContentProvider content_provider,
  11676. const std::string &content_type,
  11677. ContentReceiver content_receiver,
  11678. UploadProgress progress) {
  11679. return Post(path, Headers(), content_length, std::move(content_provider),
  11680. content_type, std::move(content_receiver), progress);
  11681. }
  11682. inline Result ClientImpl::Post(const std::string &path,
  11683. ContentProviderWithoutLength content_provider,
  11684. const std::string &content_type,
  11685. UploadProgress progress) {
  11686. return Post(path, Headers(), std::move(content_provider), content_type,
  11687. progress);
  11688. }
  11689. inline Result ClientImpl::Post(const std::string &path,
  11690. ContentProviderWithoutLength content_provider,
  11691. const std::string &content_type,
  11692. ContentReceiver content_receiver,
  11693. UploadProgress progress) {
  11694. return Post(path, Headers(), std::move(content_provider), content_type,
  11695. std::move(content_receiver), progress);
  11696. }
  11697. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11698. const Params &params) {
  11699. auto query = detail::params_to_query_str(params);
  11700. return Post(path, headers, query, "application/x-www-form-urlencoded");
  11701. }
  11702. inline Result ClientImpl::Post(const std::string &path,
  11703. const UploadFormDataItems &items,
  11704. UploadProgress progress) {
  11705. return Post(path, Headers(), items, progress);
  11706. }
  11707. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11708. const UploadFormDataItems &items,
  11709. UploadProgress progress) {
  11710. const auto &boundary = detail::make_multipart_data_boundary();
  11711. const auto &content_type =
  11712. detail::serialize_multipart_formdata_get_content_type(boundary);
  11713. auto content_length = detail::get_multipart_content_length(items, boundary);
  11714. return Post(path, headers, content_length,
  11715. detail::make_multipart_content_provider(items, boundary),
  11716. content_type, progress);
  11717. }
  11718. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11719. const UploadFormDataItems &items,
  11720. const std::string &boundary,
  11721. UploadProgress progress) {
  11722. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  11723. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  11724. }
  11725. const auto &content_type =
  11726. detail::serialize_multipart_formdata_get_content_type(boundary);
  11727. auto content_length = detail::get_multipart_content_length(items, boundary);
  11728. return Post(path, headers, content_length,
  11729. detail::make_multipart_content_provider(items, boundary),
  11730. content_type, progress);
  11731. }
  11732. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11733. const char *body, size_t content_length,
  11734. const std::string &content_type,
  11735. UploadProgress progress) {
  11736. return send_with_content_provider_and_receiver(
  11737. "POST", path, headers, body, content_length, nullptr, nullptr,
  11738. content_type, nullptr, progress);
  11739. }
  11740. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11741. const std::string &body,
  11742. const std::string &content_type,
  11743. UploadProgress progress) {
  11744. return send_with_content_provider_and_receiver(
  11745. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  11746. content_type, nullptr, progress);
  11747. }
  11748. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11749. size_t content_length,
  11750. ContentProvider content_provider,
  11751. const std::string &content_type,
  11752. UploadProgress progress) {
  11753. return send_with_content_provider_and_receiver(
  11754. "POST", path, headers, nullptr, content_length,
  11755. std::move(content_provider), nullptr, content_type, nullptr, progress);
  11756. }
  11757. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11758. size_t content_length,
  11759. ContentProvider content_provider,
  11760. const std::string &content_type,
  11761. ContentReceiver content_receiver,
  11762. DownloadProgress progress) {
  11763. return send_with_content_provider_and_receiver(
  11764. "POST", path, headers, nullptr, content_length,
  11765. std::move(content_provider), nullptr, content_type,
  11766. std::move(content_receiver), std::move(progress));
  11767. }
  11768. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11769. ContentProviderWithoutLength content_provider,
  11770. const std::string &content_type,
  11771. UploadProgress progress) {
  11772. return send_with_content_provider_and_receiver(
  11773. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11774. content_type, nullptr, progress);
  11775. }
  11776. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11777. ContentProviderWithoutLength content_provider,
  11778. const std::string &content_type,
  11779. ContentReceiver content_receiver,
  11780. DownloadProgress progress) {
  11781. return send_with_content_provider_and_receiver(
  11782. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11783. content_type, std::move(content_receiver), std::move(progress));
  11784. }
  11785. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11786. const UploadFormDataItems &items,
  11787. const FormDataProviderItems &provider_items,
  11788. UploadProgress progress) {
  11789. const auto &boundary = detail::make_multipart_data_boundary();
  11790. const auto &content_type =
  11791. detail::serialize_multipart_formdata_get_content_type(boundary);
  11792. return send_with_content_provider_and_receiver(
  11793. "POST", path, headers, nullptr, 0, nullptr,
  11794. get_multipart_content_provider(boundary, items, provider_items),
  11795. content_type, nullptr, progress);
  11796. }
  11797. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  11798. const std::string &body,
  11799. const std::string &content_type,
  11800. ContentReceiver content_receiver,
  11801. DownloadProgress progress) {
  11802. Request req;
  11803. req.method = "POST";
  11804. req.path = path;
  11805. req.headers = headers;
  11806. req.body = body;
  11807. req.content_receiver =
  11808. [content_receiver](const char *data, size_t data_length,
  11809. size_t /*offset*/, size_t /*total_length*/) {
  11810. return content_receiver(data, data_length);
  11811. };
  11812. req.download_progress = std::move(progress);
  11813. if (max_timeout_msec_ > 0) {
  11814. req.start_time_ = std::chrono::steady_clock::now();
  11815. }
  11816. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11817. return send_(std::move(req));
  11818. }
  11819. inline Result ClientImpl::Put(const std::string &path) {
  11820. return Put(path, std::string(), std::string());
  11821. }
  11822. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  11823. return Put(path, headers, nullptr, 0, std::string());
  11824. }
  11825. inline Result ClientImpl::Put(const std::string &path, const char *body,
  11826. size_t content_length,
  11827. const std::string &content_type,
  11828. UploadProgress progress) {
  11829. return Put(path, Headers(), body, content_length, content_type, progress);
  11830. }
  11831. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  11832. const std::string &content_type,
  11833. UploadProgress progress) {
  11834. return Put(path, Headers(), body, content_type, progress);
  11835. }
  11836. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  11837. return Put(path, Headers(), params);
  11838. }
  11839. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  11840. ContentProvider content_provider,
  11841. const std::string &content_type,
  11842. UploadProgress progress) {
  11843. return Put(path, Headers(), content_length, std::move(content_provider),
  11844. content_type, progress);
  11845. }
  11846. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  11847. ContentProvider content_provider,
  11848. const std::string &content_type,
  11849. ContentReceiver content_receiver,
  11850. UploadProgress progress) {
  11851. return Put(path, Headers(), content_length, std::move(content_provider),
  11852. content_type, std::move(content_receiver), progress);
  11853. }
  11854. inline Result ClientImpl::Put(const std::string &path,
  11855. ContentProviderWithoutLength content_provider,
  11856. const std::string &content_type,
  11857. UploadProgress progress) {
  11858. return Put(path, Headers(), std::move(content_provider), content_type,
  11859. progress);
  11860. }
  11861. inline Result ClientImpl::Put(const std::string &path,
  11862. ContentProviderWithoutLength content_provider,
  11863. const std::string &content_type,
  11864. ContentReceiver content_receiver,
  11865. UploadProgress progress) {
  11866. return Put(path, Headers(), std::move(content_provider), content_type,
  11867. std::move(content_receiver), progress);
  11868. }
  11869. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11870. const Params &params) {
  11871. auto query = detail::params_to_query_str(params);
  11872. return Put(path, headers, query, "application/x-www-form-urlencoded");
  11873. }
  11874. inline Result ClientImpl::Put(const std::string &path,
  11875. const UploadFormDataItems &items,
  11876. UploadProgress progress) {
  11877. return Put(path, Headers(), items, progress);
  11878. }
  11879. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11880. const UploadFormDataItems &items,
  11881. UploadProgress progress) {
  11882. const auto &boundary = detail::make_multipart_data_boundary();
  11883. const auto &content_type =
  11884. detail::serialize_multipart_formdata_get_content_type(boundary);
  11885. auto content_length = detail::get_multipart_content_length(items, boundary);
  11886. return Put(path, headers, content_length,
  11887. detail::make_multipart_content_provider(items, boundary),
  11888. content_type, progress);
  11889. }
  11890. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11891. const UploadFormDataItems &items,
  11892. const std::string &boundary,
  11893. UploadProgress progress) {
  11894. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  11895. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  11896. }
  11897. const auto &content_type =
  11898. detail::serialize_multipart_formdata_get_content_type(boundary);
  11899. auto content_length = detail::get_multipart_content_length(items, boundary);
  11900. return Put(path, headers, content_length,
  11901. detail::make_multipart_content_provider(items, boundary),
  11902. content_type, progress);
  11903. }
  11904. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11905. const char *body, size_t content_length,
  11906. const std::string &content_type,
  11907. UploadProgress progress) {
  11908. return send_with_content_provider_and_receiver(
  11909. "PUT", path, headers, body, content_length, nullptr, nullptr,
  11910. content_type, nullptr, progress);
  11911. }
  11912. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11913. const std::string &body,
  11914. const std::string &content_type,
  11915. UploadProgress progress) {
  11916. return send_with_content_provider_and_receiver(
  11917. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  11918. content_type, nullptr, progress);
  11919. }
  11920. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11921. size_t content_length,
  11922. ContentProvider content_provider,
  11923. const std::string &content_type,
  11924. UploadProgress progress) {
  11925. return send_with_content_provider_and_receiver(
  11926. "PUT", path, headers, nullptr, content_length,
  11927. std::move(content_provider), nullptr, content_type, nullptr, progress);
  11928. }
  11929. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11930. size_t content_length,
  11931. ContentProvider content_provider,
  11932. const std::string &content_type,
  11933. ContentReceiver content_receiver,
  11934. UploadProgress progress) {
  11935. return send_with_content_provider_and_receiver(
  11936. "PUT", path, headers, nullptr, content_length,
  11937. std::move(content_provider), nullptr, content_type,
  11938. std::move(content_receiver), progress);
  11939. }
  11940. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11941. ContentProviderWithoutLength content_provider,
  11942. const std::string &content_type,
  11943. UploadProgress progress) {
  11944. return send_with_content_provider_and_receiver(
  11945. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11946. content_type, nullptr, progress);
  11947. }
  11948. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11949. ContentProviderWithoutLength content_provider,
  11950. const std::string &content_type,
  11951. ContentReceiver content_receiver,
  11952. UploadProgress progress) {
  11953. return send_with_content_provider_and_receiver(
  11954. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  11955. content_type, std::move(content_receiver), progress);
  11956. }
  11957. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11958. const UploadFormDataItems &items,
  11959. const FormDataProviderItems &provider_items,
  11960. UploadProgress progress) {
  11961. const auto &boundary = detail::make_multipart_data_boundary();
  11962. const auto &content_type =
  11963. detail::serialize_multipart_formdata_get_content_type(boundary);
  11964. return send_with_content_provider_and_receiver(
  11965. "PUT", path, headers, nullptr, 0, nullptr,
  11966. get_multipart_content_provider(boundary, items, provider_items),
  11967. content_type, nullptr, progress);
  11968. }
  11969. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  11970. const std::string &body,
  11971. const std::string &content_type,
  11972. ContentReceiver content_receiver,
  11973. DownloadProgress progress) {
  11974. Request req;
  11975. req.method = "PUT";
  11976. req.path = path;
  11977. req.headers = headers;
  11978. req.body = body;
  11979. req.content_receiver =
  11980. [content_receiver](const char *data, size_t data_length,
  11981. size_t /*offset*/, size_t /*total_length*/) {
  11982. return content_receiver(data, data_length);
  11983. };
  11984. req.download_progress = std::move(progress);
  11985. if (max_timeout_msec_ > 0) {
  11986. req.start_time_ = std::chrono::steady_clock::now();
  11987. }
  11988. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11989. return send_(std::move(req));
  11990. }
  11991. inline Result ClientImpl::Patch(const std::string &path) {
  11992. return Patch(path, std::string(), std::string());
  11993. }
  11994. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  11995. UploadProgress progress) {
  11996. return Patch(path, headers, nullptr, 0, std::string(), progress);
  11997. }
  11998. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  11999. size_t content_length,
  12000. const std::string &content_type,
  12001. UploadProgress progress) {
  12002. return Patch(path, Headers(), body, content_length, content_type, progress);
  12003. }
  12004. inline Result ClientImpl::Patch(const std::string &path,
  12005. const std::string &body,
  12006. const std::string &content_type,
  12007. UploadProgress progress) {
  12008. return Patch(path, Headers(), body, content_type, progress);
  12009. }
  12010. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12011. return Patch(path, Headers(), params);
  12012. }
  12013. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12014. ContentProvider content_provider,
  12015. const std::string &content_type,
  12016. UploadProgress progress) {
  12017. return Patch(path, Headers(), content_length, std::move(content_provider),
  12018. content_type, progress);
  12019. }
  12020. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12021. ContentProvider content_provider,
  12022. const std::string &content_type,
  12023. ContentReceiver content_receiver,
  12024. UploadProgress progress) {
  12025. return Patch(path, Headers(), content_length, std::move(content_provider),
  12026. content_type, std::move(content_receiver), progress);
  12027. }
  12028. inline Result ClientImpl::Patch(const std::string &path,
  12029. ContentProviderWithoutLength content_provider,
  12030. const std::string &content_type,
  12031. UploadProgress progress) {
  12032. return Patch(path, Headers(), std::move(content_provider), content_type,
  12033. progress);
  12034. }
  12035. inline Result ClientImpl::Patch(const std::string &path,
  12036. ContentProviderWithoutLength content_provider,
  12037. const std::string &content_type,
  12038. ContentReceiver content_receiver,
  12039. UploadProgress progress) {
  12040. return Patch(path, Headers(), std::move(content_provider), content_type,
  12041. std::move(content_receiver), progress);
  12042. }
  12043. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12044. const Params &params) {
  12045. auto query = detail::params_to_query_str(params);
  12046. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12047. }
  12048. inline Result ClientImpl::Patch(const std::string &path,
  12049. const UploadFormDataItems &items,
  12050. UploadProgress progress) {
  12051. return Patch(path, Headers(), items, progress);
  12052. }
  12053. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12054. const UploadFormDataItems &items,
  12055. UploadProgress progress) {
  12056. const auto &boundary = detail::make_multipart_data_boundary();
  12057. const auto &content_type =
  12058. detail::serialize_multipart_formdata_get_content_type(boundary);
  12059. auto content_length = detail::get_multipart_content_length(items, boundary);
  12060. return Patch(path, headers, content_length,
  12061. detail::make_multipart_content_provider(items, boundary),
  12062. content_type, progress);
  12063. }
  12064. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12065. const UploadFormDataItems &items,
  12066. const std::string &boundary,
  12067. UploadProgress progress) {
  12068. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12069. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12070. }
  12071. const auto &content_type =
  12072. detail::serialize_multipart_formdata_get_content_type(boundary);
  12073. auto content_length = detail::get_multipart_content_length(items, boundary);
  12074. return Patch(path, headers, content_length,
  12075. detail::make_multipart_content_provider(items, boundary),
  12076. content_type, progress);
  12077. }
  12078. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12079. const char *body, size_t content_length,
  12080. const std::string &content_type,
  12081. UploadProgress progress) {
  12082. return send_with_content_provider_and_receiver(
  12083. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12084. content_type, nullptr, progress);
  12085. }
  12086. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12087. const std::string &body,
  12088. const std::string &content_type,
  12089. UploadProgress progress) {
  12090. return send_with_content_provider_and_receiver(
  12091. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12092. content_type, nullptr, progress);
  12093. }
  12094. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12095. size_t content_length,
  12096. ContentProvider content_provider,
  12097. const std::string &content_type,
  12098. UploadProgress progress) {
  12099. return send_with_content_provider_and_receiver(
  12100. "PATCH", path, headers, nullptr, content_length,
  12101. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12102. }
  12103. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12104. size_t content_length,
  12105. ContentProvider content_provider,
  12106. const std::string &content_type,
  12107. ContentReceiver content_receiver,
  12108. UploadProgress progress) {
  12109. return send_with_content_provider_and_receiver(
  12110. "PATCH", path, headers, nullptr, content_length,
  12111. std::move(content_provider), nullptr, content_type,
  12112. std::move(content_receiver), progress);
  12113. }
  12114. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12115. ContentProviderWithoutLength content_provider,
  12116. const std::string &content_type,
  12117. UploadProgress progress) {
  12118. return send_with_content_provider_and_receiver(
  12119. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12120. content_type, nullptr, progress);
  12121. }
  12122. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12123. ContentProviderWithoutLength content_provider,
  12124. const std::string &content_type,
  12125. ContentReceiver content_receiver,
  12126. UploadProgress progress) {
  12127. return send_with_content_provider_and_receiver(
  12128. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12129. content_type, std::move(content_receiver), progress);
  12130. }
  12131. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12132. const UploadFormDataItems &items,
  12133. const FormDataProviderItems &provider_items,
  12134. UploadProgress progress) {
  12135. const auto &boundary = detail::make_multipart_data_boundary();
  12136. const auto &content_type =
  12137. detail::serialize_multipart_formdata_get_content_type(boundary);
  12138. return send_with_content_provider_and_receiver(
  12139. "PATCH", path, headers, nullptr, 0, nullptr,
  12140. get_multipart_content_provider(boundary, items, provider_items),
  12141. content_type, nullptr, progress);
  12142. }
  12143. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12144. const std::string &body,
  12145. const std::string &content_type,
  12146. ContentReceiver content_receiver,
  12147. DownloadProgress progress) {
  12148. Request req;
  12149. req.method = "PATCH";
  12150. req.path = path;
  12151. req.headers = headers;
  12152. req.body = body;
  12153. req.content_receiver =
  12154. [content_receiver](const char *data, size_t data_length,
  12155. size_t /*offset*/, size_t /*total_length*/) {
  12156. return content_receiver(data, data_length);
  12157. };
  12158. req.download_progress = std::move(progress);
  12159. if (max_timeout_msec_ > 0) {
  12160. req.start_time_ = std::chrono::steady_clock::now();
  12161. }
  12162. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12163. return send_(std::move(req));
  12164. }
  12165. inline Result ClientImpl::Delete(const std::string &path,
  12166. DownloadProgress progress) {
  12167. return Delete(path, Headers(), std::string(), std::string(), progress);
  12168. }
  12169. inline Result ClientImpl::Delete(const std::string &path,
  12170. const Headers &headers,
  12171. DownloadProgress progress) {
  12172. return Delete(path, headers, std::string(), std::string(), progress);
  12173. }
  12174. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12175. size_t content_length,
  12176. const std::string &content_type,
  12177. DownloadProgress progress) {
  12178. return Delete(path, Headers(), body, content_length, content_type, progress);
  12179. }
  12180. inline Result ClientImpl::Delete(const std::string &path,
  12181. const std::string &body,
  12182. const std::string &content_type,
  12183. DownloadProgress progress) {
  12184. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12185. progress);
  12186. }
  12187. inline Result ClientImpl::Delete(const std::string &path,
  12188. const Headers &headers,
  12189. const std::string &body,
  12190. const std::string &content_type,
  12191. DownloadProgress progress) {
  12192. return Delete(path, headers, body.data(), body.size(), content_type,
  12193. progress);
  12194. }
  12195. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12196. DownloadProgress progress) {
  12197. return Delete(path, Headers(), params, progress);
  12198. }
  12199. inline Result ClientImpl::Delete(const std::string &path,
  12200. const Headers &headers, const Params &params,
  12201. DownloadProgress progress) {
  12202. auto query = detail::params_to_query_str(params);
  12203. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12204. progress);
  12205. }
  12206. inline Result ClientImpl::Delete(const std::string &path,
  12207. const Headers &headers, const char *body,
  12208. size_t content_length,
  12209. const std::string &content_type,
  12210. DownloadProgress progress) {
  12211. Request req;
  12212. req.method = "DELETE";
  12213. req.headers = headers;
  12214. req.path = path;
  12215. req.download_progress = std::move(progress);
  12216. if (max_timeout_msec_ > 0) {
  12217. req.start_time_ = std::chrono::steady_clock::now();
  12218. }
  12219. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12220. req.body.assign(body, content_length);
  12221. return send_(std::move(req));
  12222. }
  12223. inline Result ClientImpl::Options(const std::string &path) {
  12224. return Options(path, Headers());
  12225. }
  12226. inline Result ClientImpl::Options(const std::string &path,
  12227. const Headers &headers) {
  12228. Request req;
  12229. req.method = "OPTIONS";
  12230. req.headers = headers;
  12231. req.path = path;
  12232. if (max_timeout_msec_ > 0) {
  12233. req.start_time_ = std::chrono::steady_clock::now();
  12234. }
  12235. return send_(std::move(req));
  12236. }
  12237. inline void ClientImpl::stop() {
  12238. std::lock_guard<std::mutex> guard(socket_mutex_);
  12239. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12240. // do is to shutdown_socket, so that threads using this socket suddenly
  12241. // discover they can't read/write any more and error out. Everything else
  12242. // (closing the socket, shutting ssl down) is unsafe because these actions
  12243. // are not thread-safe.
  12244. if (socket_requests_in_flight_ > 0) {
  12245. shutdown_socket(socket_);
  12246. // Aside from that, we set a flag for the socket to be closed when we're
  12247. // done.
  12248. socket_should_be_closed_when_request_is_done_ = true;
  12249. return;
  12250. }
  12251. // Otherwise, still holding the mutex, we can shut everything down ourselves
  12252. shutdown_ssl(socket_, true);
  12253. shutdown_socket(socket_);
  12254. close_socket(socket_);
  12255. }
  12256. inline std::string ClientImpl::host() const { return host_; }
  12257. inline int ClientImpl::port() const { return port_; }
  12258. inline size_t ClientImpl::is_socket_open() const {
  12259. std::lock_guard<std::mutex> guard(socket_mutex_);
  12260. return socket_.is_open();
  12261. }
  12262. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12263. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12264. connection_timeout_sec_ = sec;
  12265. connection_timeout_usec_ = usec;
  12266. }
  12267. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12268. read_timeout_sec_ = sec;
  12269. read_timeout_usec_ = usec;
  12270. }
  12271. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12272. write_timeout_sec_ = sec;
  12273. write_timeout_usec_ = usec;
  12274. }
  12275. inline void ClientImpl::set_max_timeout(time_t msec) {
  12276. max_timeout_msec_ = msec;
  12277. }
  12278. inline void ClientImpl::set_basic_auth(const std::string &username,
  12279. const std::string &password) {
  12280. basic_auth_username_ = username;
  12281. basic_auth_password_ = password;
  12282. }
  12283. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12284. bearer_token_auth_token_ = token;
  12285. }
  12286. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12287. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12288. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12289. inline void
  12290. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12291. addr_map_ = std::move(addr_map);
  12292. }
  12293. inline void ClientImpl::set_default_headers(Headers headers) {
  12294. default_headers_ = std::move(headers);
  12295. }
  12296. inline void ClientImpl::set_header_writer(
  12297. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12298. header_writer_ = writer;
  12299. }
  12300. inline void ClientImpl::set_address_family(int family) {
  12301. address_family_ = family;
  12302. }
  12303. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12304. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12305. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12306. socket_options_ = std::move(socket_options);
  12307. }
  12308. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12309. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12310. inline void ClientImpl::set_payload_max_length(size_t length) {
  12311. payload_max_length_ = length;
  12312. has_payload_max_length_ = true;
  12313. }
  12314. inline void ClientImpl::set_interface(const std::string &intf) {
  12315. interface_ = intf;
  12316. }
  12317. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12318. proxy_host_ = host;
  12319. proxy_port_ = port;
  12320. }
  12321. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12322. const std::string &password) {
  12323. proxy_basic_auth_username_ = username;
  12324. proxy_basic_auth_password_ = password;
  12325. }
  12326. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12327. proxy_bearer_token_auth_token_ = token;
  12328. }
  12329. #ifdef CPPHTTPLIB_SSL_ENABLED
  12330. inline void ClientImpl::set_digest_auth(const std::string &username,
  12331. const std::string &password) {
  12332. digest_auth_username_ = username;
  12333. digest_auth_password_ = password;
  12334. }
  12335. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12336. const std::string &ca_cert_dir_path) {
  12337. ca_cert_file_path_ = ca_cert_file_path;
  12338. ca_cert_dir_path_ = ca_cert_dir_path;
  12339. }
  12340. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12341. const std::string &password) {
  12342. proxy_digest_auth_username_ = username;
  12343. proxy_digest_auth_password_ = password;
  12344. }
  12345. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12346. server_certificate_verification_ = enabled;
  12347. }
  12348. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12349. server_hostname_verification_ = enabled;
  12350. }
  12351. #endif
  12352. inline void ClientImpl::set_logger(Logger logger) {
  12353. logger_ = std::move(logger);
  12354. }
  12355. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12356. error_logger_ = std::move(error_logger);
  12357. }
  12358. /*
  12359. * SSL/TLS Common Implementation
  12360. */
  12361. inline ClientConnection::~ClientConnection() {
  12362. #ifdef CPPHTTPLIB_SSL_ENABLED
  12363. if (session) {
  12364. tls::shutdown(session, true);
  12365. tls::free_session(session);
  12366. session = nullptr;
  12367. }
  12368. #endif
  12369. if (sock != INVALID_SOCKET) {
  12370. detail::close_socket(sock);
  12371. sock = INVALID_SOCKET;
  12372. }
  12373. }
  12374. // Universal client implementation
  12375. inline Client::Client(const std::string &scheme_host_port)
  12376. : Client(scheme_host_port, std::string(), std::string()) {}
  12377. inline Client::Client(const std::string &scheme_host_port,
  12378. const std::string &client_cert_path,
  12379. const std::string &client_key_path) {
  12380. detail::UrlComponents uc;
  12381. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  12382. auto &scheme = uc.scheme;
  12383. #ifdef CPPHTTPLIB_SSL_ENABLED
  12384. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12385. #else
  12386. if (!scheme.empty() && scheme != "http") {
  12387. #endif
  12388. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12389. std::string msg = "'" + scheme + "' scheme is not supported.";
  12390. throw std::invalid_argument(msg);
  12391. #endif
  12392. return;
  12393. }
  12394. auto is_ssl = scheme == "https";
  12395. auto host = std::move(uc.host);
  12396. auto port = is_ssl ? 443 : 80;
  12397. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  12398. if (is_ssl) {
  12399. #ifdef CPPHTTPLIB_SSL_ENABLED
  12400. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12401. client_key_path);
  12402. is_ssl_ = is_ssl;
  12403. #endif
  12404. } else {
  12405. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12406. client_key_path);
  12407. }
  12408. } else {
  12409. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12410. // if port param below changes.
  12411. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12412. client_cert_path, client_key_path);
  12413. }
  12414. }
  12415. inline Client::Client(const std::string &host, int port)
  12416. : Client(host, port, std::string(), std::string()) {}
  12417. inline Client::Client(const std::string &host, int port,
  12418. const std::string &client_cert_path,
  12419. const std::string &client_key_path)
  12420. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12421. client_key_path)) {}
  12422. inline Client::~Client() = default;
  12423. inline bool Client::is_valid() const {
  12424. return cli_ != nullptr && cli_->is_valid();
  12425. }
  12426. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12427. return cli_->Get(path, std::move(progress));
  12428. }
  12429. inline Result Client::Get(const std::string &path, const Headers &headers,
  12430. DownloadProgress progress) {
  12431. return cli_->Get(path, headers, std::move(progress));
  12432. }
  12433. inline Result Client::Get(const std::string &path,
  12434. ContentReceiver content_receiver,
  12435. DownloadProgress progress) {
  12436. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  12437. }
  12438. inline Result Client::Get(const std::string &path, const Headers &headers,
  12439. ContentReceiver content_receiver,
  12440. DownloadProgress progress) {
  12441. return cli_->Get(path, headers, std::move(content_receiver),
  12442. std::move(progress));
  12443. }
  12444. inline Result Client::Get(const std::string &path,
  12445. ResponseHandler response_handler,
  12446. ContentReceiver content_receiver,
  12447. DownloadProgress progress) {
  12448. return cli_->Get(path, std::move(response_handler),
  12449. std::move(content_receiver), std::move(progress));
  12450. }
  12451. inline Result Client::Get(const std::string &path, const Headers &headers,
  12452. ResponseHandler response_handler,
  12453. ContentReceiver content_receiver,
  12454. DownloadProgress progress) {
  12455. return cli_->Get(path, headers, std::move(response_handler),
  12456. std::move(content_receiver), std::move(progress));
  12457. }
  12458. inline Result Client::Get(const std::string &path, const Params &params,
  12459. const Headers &headers, DownloadProgress progress) {
  12460. return cli_->Get(path, params, headers, std::move(progress));
  12461. }
  12462. inline Result Client::Get(const std::string &path, const Params &params,
  12463. const Headers &headers,
  12464. ContentReceiver content_receiver,
  12465. DownloadProgress progress) {
  12466. return cli_->Get(path, params, headers, std::move(content_receiver),
  12467. std::move(progress));
  12468. }
  12469. inline Result Client::Get(const std::string &path, const Params &params,
  12470. const Headers &headers,
  12471. ResponseHandler response_handler,
  12472. ContentReceiver content_receiver,
  12473. DownloadProgress progress) {
  12474. return cli_->Get(path, params, headers, std::move(response_handler),
  12475. std::move(content_receiver), std::move(progress));
  12476. }
  12477. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  12478. inline Result Client::Head(const std::string &path, const Headers &headers) {
  12479. return cli_->Head(path, headers);
  12480. }
  12481. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  12482. inline Result Client::Post(const std::string &path, const Headers &headers) {
  12483. return cli_->Post(path, headers);
  12484. }
  12485. inline Result Client::Post(const std::string &path, const char *body,
  12486. size_t content_length,
  12487. const std::string &content_type,
  12488. UploadProgress progress) {
  12489. return cli_->Post(path, body, content_length, content_type, progress);
  12490. }
  12491. inline Result Client::Post(const std::string &path, const Headers &headers,
  12492. const char *body, size_t content_length,
  12493. const std::string &content_type,
  12494. UploadProgress progress) {
  12495. return cli_->Post(path, headers, body, content_length, content_type,
  12496. progress);
  12497. }
  12498. inline Result Client::Post(const std::string &path, const std::string &body,
  12499. const std::string &content_type,
  12500. UploadProgress progress) {
  12501. return cli_->Post(path, body, content_type, progress);
  12502. }
  12503. inline Result Client::Post(const std::string &path, const Headers &headers,
  12504. const std::string &body,
  12505. const std::string &content_type,
  12506. UploadProgress progress) {
  12507. return cli_->Post(path, headers, body, content_type, progress);
  12508. }
  12509. inline Result Client::Post(const std::string &path, size_t content_length,
  12510. ContentProvider content_provider,
  12511. const std::string &content_type,
  12512. UploadProgress progress) {
  12513. return cli_->Post(path, content_length, std::move(content_provider),
  12514. content_type, progress);
  12515. }
  12516. inline Result Client::Post(const std::string &path, size_t content_length,
  12517. ContentProvider content_provider,
  12518. const std::string &content_type,
  12519. ContentReceiver content_receiver,
  12520. UploadProgress progress) {
  12521. return cli_->Post(path, content_length, std::move(content_provider),
  12522. content_type, std::move(content_receiver), progress);
  12523. }
  12524. inline Result Client::Post(const std::string &path,
  12525. ContentProviderWithoutLength content_provider,
  12526. const std::string &content_type,
  12527. UploadProgress progress) {
  12528. return cli_->Post(path, std::move(content_provider), content_type, progress);
  12529. }
  12530. inline Result Client::Post(const std::string &path,
  12531. ContentProviderWithoutLength content_provider,
  12532. const std::string &content_type,
  12533. ContentReceiver content_receiver,
  12534. UploadProgress progress) {
  12535. return cli_->Post(path, std::move(content_provider), content_type,
  12536. std::move(content_receiver), progress);
  12537. }
  12538. inline Result Client::Post(const std::string &path, const Headers &headers,
  12539. size_t content_length,
  12540. ContentProvider content_provider,
  12541. const std::string &content_type,
  12542. UploadProgress progress) {
  12543. return cli_->Post(path, headers, content_length, std::move(content_provider),
  12544. content_type, progress);
  12545. }
  12546. inline Result Client::Post(const std::string &path, const Headers &headers,
  12547. size_t content_length,
  12548. ContentProvider content_provider,
  12549. const std::string &content_type,
  12550. ContentReceiver content_receiver,
  12551. DownloadProgress progress) {
  12552. return cli_->Post(path, headers, content_length, std::move(content_provider),
  12553. content_type, std::move(content_receiver), progress);
  12554. }
  12555. inline Result Client::Post(const std::string &path, const Headers &headers,
  12556. ContentProviderWithoutLength content_provider,
  12557. const std::string &content_type,
  12558. UploadProgress progress) {
  12559. return cli_->Post(path, headers, std::move(content_provider), content_type,
  12560. progress);
  12561. }
  12562. inline Result Client::Post(const std::string &path, const Headers &headers,
  12563. ContentProviderWithoutLength content_provider,
  12564. const std::string &content_type,
  12565. ContentReceiver content_receiver,
  12566. DownloadProgress progress) {
  12567. return cli_->Post(path, headers, std::move(content_provider), content_type,
  12568. std::move(content_receiver), progress);
  12569. }
  12570. inline Result Client::Post(const std::string &path, const Params &params) {
  12571. return cli_->Post(path, params);
  12572. }
  12573. inline Result Client::Post(const std::string &path, const Headers &headers,
  12574. const Params &params) {
  12575. return cli_->Post(path, headers, params);
  12576. }
  12577. inline Result Client::Post(const std::string &path,
  12578. const UploadFormDataItems &items,
  12579. UploadProgress progress) {
  12580. return cli_->Post(path, items, progress);
  12581. }
  12582. inline Result Client::Post(const std::string &path, const Headers &headers,
  12583. const UploadFormDataItems &items,
  12584. UploadProgress progress) {
  12585. return cli_->Post(path, headers, items, progress);
  12586. }
  12587. inline Result Client::Post(const std::string &path, const Headers &headers,
  12588. const UploadFormDataItems &items,
  12589. const std::string &boundary,
  12590. UploadProgress progress) {
  12591. return cli_->Post(path, headers, items, boundary, progress);
  12592. }
  12593. inline Result Client::Post(const std::string &path, const Headers &headers,
  12594. const UploadFormDataItems &items,
  12595. const FormDataProviderItems &provider_items,
  12596. UploadProgress progress) {
  12597. return cli_->Post(path, headers, items, provider_items, progress);
  12598. }
  12599. inline Result Client::Post(const std::string &path, const Headers &headers,
  12600. const std::string &body,
  12601. const std::string &content_type,
  12602. ContentReceiver content_receiver,
  12603. DownloadProgress progress) {
  12604. return cli_->Post(path, headers, body, content_type,
  12605. std::move(content_receiver), progress);
  12606. }
  12607. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  12608. inline Result Client::Put(const std::string &path, const Headers &headers) {
  12609. return cli_->Put(path, headers);
  12610. }
  12611. inline Result Client::Put(const std::string &path, const char *body,
  12612. size_t content_length,
  12613. const std::string &content_type,
  12614. UploadProgress progress) {
  12615. return cli_->Put(path, body, content_length, content_type, progress);
  12616. }
  12617. inline Result Client::Put(const std::string &path, const Headers &headers,
  12618. const char *body, size_t content_length,
  12619. const std::string &content_type,
  12620. UploadProgress progress) {
  12621. return cli_->Put(path, headers, body, content_length, content_type, progress);
  12622. }
  12623. inline Result Client::Put(const std::string &path, const std::string &body,
  12624. const std::string &content_type,
  12625. UploadProgress progress) {
  12626. return cli_->Put(path, body, content_type, progress);
  12627. }
  12628. inline Result Client::Put(const std::string &path, const Headers &headers,
  12629. const std::string &body,
  12630. const std::string &content_type,
  12631. UploadProgress progress) {
  12632. return cli_->Put(path, headers, body, content_type, progress);
  12633. }
  12634. inline Result Client::Put(const std::string &path, size_t content_length,
  12635. ContentProvider content_provider,
  12636. const std::string &content_type,
  12637. UploadProgress progress) {
  12638. return cli_->Put(path, content_length, std::move(content_provider),
  12639. content_type, progress);
  12640. }
  12641. inline Result Client::Put(const std::string &path, size_t content_length,
  12642. ContentProvider content_provider,
  12643. const std::string &content_type,
  12644. ContentReceiver content_receiver,
  12645. UploadProgress progress) {
  12646. return cli_->Put(path, content_length, std::move(content_provider),
  12647. content_type, std::move(content_receiver), progress);
  12648. }
  12649. inline Result Client::Put(const std::string &path,
  12650. ContentProviderWithoutLength content_provider,
  12651. const std::string &content_type,
  12652. UploadProgress progress) {
  12653. return cli_->Put(path, std::move(content_provider), content_type, progress);
  12654. }
  12655. inline Result Client::Put(const std::string &path,
  12656. ContentProviderWithoutLength content_provider,
  12657. const std::string &content_type,
  12658. ContentReceiver content_receiver,
  12659. UploadProgress progress) {
  12660. return cli_->Put(path, std::move(content_provider), content_type,
  12661. std::move(content_receiver), progress);
  12662. }
  12663. inline Result Client::Put(const std::string &path, const Headers &headers,
  12664. size_t content_length,
  12665. ContentProvider content_provider,
  12666. const std::string &content_type,
  12667. UploadProgress progress) {
  12668. return cli_->Put(path, headers, content_length, std::move(content_provider),
  12669. content_type, progress);
  12670. }
  12671. inline Result Client::Put(const std::string &path, const Headers &headers,
  12672. size_t content_length,
  12673. ContentProvider content_provider,
  12674. const std::string &content_type,
  12675. ContentReceiver content_receiver,
  12676. UploadProgress progress) {
  12677. return cli_->Put(path, headers, content_length, std::move(content_provider),
  12678. content_type, std::move(content_receiver), progress);
  12679. }
  12680. inline Result Client::Put(const std::string &path, const Headers &headers,
  12681. ContentProviderWithoutLength content_provider,
  12682. const std::string &content_type,
  12683. UploadProgress progress) {
  12684. return cli_->Put(path, headers, std::move(content_provider), content_type,
  12685. progress);
  12686. }
  12687. inline Result Client::Put(const std::string &path, const Headers &headers,
  12688. ContentProviderWithoutLength content_provider,
  12689. const std::string &content_type,
  12690. ContentReceiver content_receiver,
  12691. UploadProgress progress) {
  12692. return cli_->Put(path, headers, std::move(content_provider), content_type,
  12693. std::move(content_receiver), progress);
  12694. }
  12695. inline Result Client::Put(const std::string &path, const Params &params) {
  12696. return cli_->Put(path, params);
  12697. }
  12698. inline Result Client::Put(const std::string &path, const Headers &headers,
  12699. const Params &params) {
  12700. return cli_->Put(path, headers, params);
  12701. }
  12702. inline Result Client::Put(const std::string &path,
  12703. const UploadFormDataItems &items,
  12704. UploadProgress progress) {
  12705. return cli_->Put(path, items, progress);
  12706. }
  12707. inline Result Client::Put(const std::string &path, const Headers &headers,
  12708. const UploadFormDataItems &items,
  12709. UploadProgress progress) {
  12710. return cli_->Put(path, headers, items, progress);
  12711. }
  12712. inline Result Client::Put(const std::string &path, const Headers &headers,
  12713. const UploadFormDataItems &items,
  12714. const std::string &boundary,
  12715. UploadProgress progress) {
  12716. return cli_->Put(path, headers, items, boundary, progress);
  12717. }
  12718. inline Result Client::Put(const std::string &path, const Headers &headers,
  12719. const UploadFormDataItems &items,
  12720. const FormDataProviderItems &provider_items,
  12721. UploadProgress progress) {
  12722. return cli_->Put(path, headers, items, provider_items, progress);
  12723. }
  12724. inline Result Client::Put(const std::string &path, const Headers &headers,
  12725. const std::string &body,
  12726. const std::string &content_type,
  12727. ContentReceiver content_receiver,
  12728. DownloadProgress progress) {
  12729. return cli_->Put(path, headers, body, content_type, content_receiver,
  12730. progress);
  12731. }
  12732. inline Result Client::Patch(const std::string &path) {
  12733. return cli_->Patch(path);
  12734. }
  12735. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  12736. return cli_->Patch(path, headers);
  12737. }
  12738. inline Result Client::Patch(const std::string &path, const char *body,
  12739. size_t content_length,
  12740. const std::string &content_type,
  12741. UploadProgress progress) {
  12742. return cli_->Patch(path, body, content_length, content_type, progress);
  12743. }
  12744. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12745. const char *body, size_t content_length,
  12746. const std::string &content_type,
  12747. UploadProgress progress) {
  12748. return cli_->Patch(path, headers, body, content_length, content_type,
  12749. progress);
  12750. }
  12751. inline Result Client::Patch(const std::string &path, const std::string &body,
  12752. const std::string &content_type,
  12753. UploadProgress progress) {
  12754. return cli_->Patch(path, body, content_type, progress);
  12755. }
  12756. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12757. const std::string &body,
  12758. const std::string &content_type,
  12759. UploadProgress progress) {
  12760. return cli_->Patch(path, headers, body, content_type, progress);
  12761. }
  12762. inline Result Client::Patch(const std::string &path, size_t content_length,
  12763. ContentProvider content_provider,
  12764. const std::string &content_type,
  12765. UploadProgress progress) {
  12766. return cli_->Patch(path, content_length, std::move(content_provider),
  12767. content_type, progress);
  12768. }
  12769. inline Result Client::Patch(const std::string &path, size_t content_length,
  12770. ContentProvider content_provider,
  12771. const std::string &content_type,
  12772. ContentReceiver content_receiver,
  12773. UploadProgress progress) {
  12774. return cli_->Patch(path, content_length, std::move(content_provider),
  12775. content_type, std::move(content_receiver), progress);
  12776. }
  12777. inline Result Client::Patch(const std::string &path,
  12778. ContentProviderWithoutLength content_provider,
  12779. const std::string &content_type,
  12780. UploadProgress progress) {
  12781. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  12782. }
  12783. inline Result Client::Patch(const std::string &path,
  12784. ContentProviderWithoutLength content_provider,
  12785. const std::string &content_type,
  12786. ContentReceiver content_receiver,
  12787. UploadProgress progress) {
  12788. return cli_->Patch(path, std::move(content_provider), content_type,
  12789. std::move(content_receiver), progress);
  12790. }
  12791. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12792. size_t content_length,
  12793. ContentProvider content_provider,
  12794. const std::string &content_type,
  12795. UploadProgress progress) {
  12796. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  12797. content_type, progress);
  12798. }
  12799. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12800. size_t content_length,
  12801. ContentProvider content_provider,
  12802. const std::string &content_type,
  12803. ContentReceiver content_receiver,
  12804. UploadProgress progress) {
  12805. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  12806. content_type, std::move(content_receiver), progress);
  12807. }
  12808. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12809. ContentProviderWithoutLength content_provider,
  12810. const std::string &content_type,
  12811. UploadProgress progress) {
  12812. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  12813. progress);
  12814. }
  12815. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12816. ContentProviderWithoutLength content_provider,
  12817. const std::string &content_type,
  12818. ContentReceiver content_receiver,
  12819. UploadProgress progress) {
  12820. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  12821. std::move(content_receiver), progress);
  12822. }
  12823. inline Result Client::Patch(const std::string &path, const Params &params) {
  12824. return cli_->Patch(path, params);
  12825. }
  12826. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12827. const Params &params) {
  12828. return cli_->Patch(path, headers, params);
  12829. }
  12830. inline Result Client::Patch(const std::string &path,
  12831. const UploadFormDataItems &items,
  12832. UploadProgress progress) {
  12833. return cli_->Patch(path, items, progress);
  12834. }
  12835. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12836. const UploadFormDataItems &items,
  12837. UploadProgress progress) {
  12838. return cli_->Patch(path, headers, items, progress);
  12839. }
  12840. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12841. const UploadFormDataItems &items,
  12842. const std::string &boundary,
  12843. UploadProgress progress) {
  12844. return cli_->Patch(path, headers, items, boundary, progress);
  12845. }
  12846. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12847. const UploadFormDataItems &items,
  12848. const FormDataProviderItems &provider_items,
  12849. UploadProgress progress) {
  12850. return cli_->Patch(path, headers, items, provider_items, progress);
  12851. }
  12852. inline Result Client::Patch(const std::string &path, const Headers &headers,
  12853. const std::string &body,
  12854. const std::string &content_type,
  12855. ContentReceiver content_receiver,
  12856. DownloadProgress progress) {
  12857. return cli_->Patch(path, headers, body, content_type, content_receiver,
  12858. progress);
  12859. }
  12860. inline Result Client::Delete(const std::string &path,
  12861. DownloadProgress progress) {
  12862. return cli_->Delete(path, progress);
  12863. }
  12864. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12865. DownloadProgress progress) {
  12866. return cli_->Delete(path, headers, progress);
  12867. }
  12868. inline Result Client::Delete(const std::string &path, const char *body,
  12869. size_t content_length,
  12870. const std::string &content_type,
  12871. DownloadProgress progress) {
  12872. return cli_->Delete(path, body, content_length, content_type, progress);
  12873. }
  12874. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12875. const char *body, size_t content_length,
  12876. const std::string &content_type,
  12877. DownloadProgress progress) {
  12878. return cli_->Delete(path, headers, body, content_length, content_type,
  12879. progress);
  12880. }
  12881. inline Result Client::Delete(const std::string &path, const std::string &body,
  12882. const std::string &content_type,
  12883. DownloadProgress progress) {
  12884. return cli_->Delete(path, body, content_type, progress);
  12885. }
  12886. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12887. const std::string &body,
  12888. const std::string &content_type,
  12889. DownloadProgress progress) {
  12890. return cli_->Delete(path, headers, body, content_type, progress);
  12891. }
  12892. inline Result Client::Delete(const std::string &path, const Params &params,
  12893. DownloadProgress progress) {
  12894. return cli_->Delete(path, params, progress);
  12895. }
  12896. inline Result Client::Delete(const std::string &path, const Headers &headers,
  12897. const Params &params, DownloadProgress progress) {
  12898. return cli_->Delete(path, headers, params, progress);
  12899. }
  12900. inline Result Client::Options(const std::string &path) {
  12901. return cli_->Options(path);
  12902. }
  12903. inline Result Client::Options(const std::string &path, const Headers &headers) {
  12904. return cli_->Options(path, headers);
  12905. }
  12906. inline ClientImpl::StreamHandle
  12907. Client::open_stream(const std::string &method, const std::string &path,
  12908. const Params &params, const Headers &headers,
  12909. const std::string &body, const std::string &content_type) {
  12910. return cli_->open_stream(method, path, params, headers, body, content_type);
  12911. }
  12912. inline bool Client::send(Request &req, Response &res, Error &error) {
  12913. return cli_->send(req, res, error);
  12914. }
  12915. inline Result Client::send(const Request &req) { return cli_->send(req); }
  12916. inline void Client::stop() { cli_->stop(); }
  12917. inline std::string Client::host() const { return cli_->host(); }
  12918. inline int Client::port() const { return cli_->port(); }
  12919. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  12920. inline socket_t Client::socket() const { return cli_->socket(); }
  12921. inline void
  12922. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12923. cli_->set_hostname_addr_map(std::move(addr_map));
  12924. }
  12925. inline void Client::set_default_headers(Headers headers) {
  12926. cli_->set_default_headers(std::move(headers));
  12927. }
  12928. inline void Client::set_header_writer(
  12929. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12930. cli_->set_header_writer(writer);
  12931. }
  12932. inline void Client::set_address_family(int family) {
  12933. cli_->set_address_family(family);
  12934. }
  12935. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  12936. inline void Client::set_socket_options(SocketOptions socket_options) {
  12937. cli_->set_socket_options(std::move(socket_options));
  12938. }
  12939. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  12940. cli_->set_connection_timeout(sec, usec);
  12941. }
  12942. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  12943. cli_->set_read_timeout(sec, usec);
  12944. }
  12945. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  12946. cli_->set_write_timeout(sec, usec);
  12947. }
  12948. inline void Client::set_basic_auth(const std::string &username,
  12949. const std::string &password) {
  12950. cli_->set_basic_auth(username, password);
  12951. }
  12952. inline void Client::set_bearer_token_auth(const std::string &token) {
  12953. cli_->set_bearer_token_auth(token);
  12954. }
  12955. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  12956. inline void Client::set_follow_location(bool on) {
  12957. cli_->set_follow_location(on);
  12958. }
  12959. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  12960. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  12961. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  12962. inline void Client::set_payload_max_length(size_t length) {
  12963. cli_->set_payload_max_length(length);
  12964. }
  12965. inline void Client::set_interface(const std::string &intf) {
  12966. cli_->set_interface(intf);
  12967. }
  12968. inline void Client::set_proxy(const std::string &host, int port) {
  12969. cli_->set_proxy(host, port);
  12970. }
  12971. inline void Client::set_proxy_basic_auth(const std::string &username,
  12972. const std::string &password) {
  12973. cli_->set_proxy_basic_auth(username, password);
  12974. }
  12975. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  12976. cli_->set_proxy_bearer_token_auth(token);
  12977. }
  12978. inline void Client::set_logger(Logger logger) {
  12979. cli_->set_logger(std::move(logger));
  12980. }
  12981. inline void Client::set_error_logger(ErrorLogger error_logger) {
  12982. cli_->set_error_logger(std::move(error_logger));
  12983. }
  12984. /*
  12985. * Group 6: SSL Server and Client implementation
  12986. */
  12987. #ifdef CPPHTTPLIB_SSL_ENABLED
  12988. // SSL HTTP server implementation
  12989. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  12990. const char *client_ca_cert_file_path,
  12991. const char *client_ca_cert_dir_path,
  12992. const char *private_key_password) {
  12993. using namespace tls;
  12994. ctx_ = create_server_context();
  12995. if (!ctx_) { return; }
  12996. // Load server certificate and private key
  12997. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  12998. private_key_password)) {
  12999. last_ssl_error_ = static_cast<int>(get_error());
  13000. free_context(ctx_);
  13001. ctx_ = nullptr;
  13002. return;
  13003. }
  13004. // Load client CA certificates for client authentication
  13005. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13006. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13007. client_ca_cert_dir_path)) {
  13008. last_ssl_error_ = static_cast<int>(get_error());
  13009. free_context(ctx_);
  13010. ctx_ = nullptr;
  13011. return;
  13012. }
  13013. // Enable client certificate verification
  13014. set_verify_client(ctx_, true);
  13015. }
  13016. }
  13017. inline SSLServer::SSLServer(const PemMemory &pem) {
  13018. using namespace tls;
  13019. ctx_ = create_server_context();
  13020. if (ctx_) {
  13021. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13022. pem.private_key_password)) {
  13023. last_ssl_error_ = static_cast<int>(get_error());
  13024. free_context(ctx_);
  13025. ctx_ = nullptr;
  13026. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13027. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13028. last_ssl_error_ = static_cast<int>(get_error());
  13029. free_context(ctx_);
  13030. ctx_ = nullptr;
  13031. } else {
  13032. set_verify_client(ctx_, true);
  13033. }
  13034. }
  13035. }
  13036. }
  13037. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13038. using namespace tls;
  13039. ctx_ = create_server_context();
  13040. if (ctx_) {
  13041. if (!setup_callback(ctx_)) {
  13042. free_context(ctx_);
  13043. ctx_ = nullptr;
  13044. }
  13045. }
  13046. }
  13047. inline SSLServer::~SSLServer() {
  13048. if (ctx_) { tls::free_context(ctx_); }
  13049. }
  13050. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13051. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13052. using namespace tls;
  13053. // Create TLS session with mutex protection
  13054. session_t session = nullptr;
  13055. {
  13056. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13057. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13058. }
  13059. if (!session) {
  13060. last_ssl_error_ = static_cast<int>(get_error());
  13061. detail::shutdown_socket(sock);
  13062. detail::close_socket(sock);
  13063. return false;
  13064. }
  13065. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13066. bool handshake_done = false;
  13067. bool ret = false;
  13068. bool websocket_upgraded = false;
  13069. auto cleanup = detail::scope_exit([&] {
  13070. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13071. free_session(session);
  13072. detail::shutdown_socket(sock);
  13073. detail::close_socket(sock);
  13074. });
  13075. // Perform TLS accept handshake with timeout
  13076. TlsError tls_err;
  13077. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13078. &tls_err)) {
  13079. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13080. // Map TlsError to legacy ssl_error for backward compatibility
  13081. if (tls_err.code == ErrorCode::WantRead) {
  13082. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13083. } else if (tls_err.code == ErrorCode::WantWrite) {
  13084. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13085. } else {
  13086. last_ssl_error_ = SSL_ERROR_SSL;
  13087. }
  13088. #else
  13089. last_ssl_error_ = static_cast<int>(get_error());
  13090. #endif
  13091. return false;
  13092. }
  13093. handshake_done = true;
  13094. std::string remote_addr;
  13095. int remote_port = 0;
  13096. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13097. std::string local_addr;
  13098. int local_port = 0;
  13099. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13100. ret = detail::process_server_socket_ssl(
  13101. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13102. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13103. write_timeout_usec_,
  13104. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13105. return process_request(
  13106. strm, remote_addr, remote_port, local_addr, local_port,
  13107. close_connection, connection_closed,
  13108. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13109. });
  13110. return ret;
  13111. }
  13112. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13113. const char *key_pem,
  13114. const char *client_ca_pem,
  13115. const char *password) {
  13116. if (!ctx_) { return false; }
  13117. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13118. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13119. return false;
  13120. }
  13121. if (client_ca_pem) {
  13122. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13123. }
  13124. return true;
  13125. }
  13126. // SSL HTTP client implementation
  13127. inline SSLClient::~SSLClient() {
  13128. if (ctx_) { tls::free_context(ctx_); }
  13129. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13130. // base function rather than the derived function once we get to the
  13131. // base class destructor, and won't free the SSL (causing a leak).
  13132. shutdown_ssl_impl(socket_, true);
  13133. }
  13134. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13135. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13136. shutdown_ssl_impl(socket, shutdown_gracefully);
  13137. }
  13138. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13139. bool shutdown_gracefully) {
  13140. if (socket.sock == INVALID_SOCKET) {
  13141. assert(socket.ssl == nullptr);
  13142. return;
  13143. }
  13144. if (socket.ssl) {
  13145. tls::shutdown(socket.ssl, shutdown_gracefully);
  13146. {
  13147. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13148. tls::free_session(socket.ssl);
  13149. }
  13150. socket.ssl = nullptr;
  13151. }
  13152. assert(socket.ssl == nullptr);
  13153. }
  13154. inline bool SSLClient::process_socket(
  13155. const Socket &socket,
  13156. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13157. std::function<bool(Stream &strm)> callback) {
  13158. assert(socket.ssl);
  13159. return detail::process_client_socket_ssl(
  13160. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13161. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13162. std::move(callback));
  13163. }
  13164. inline bool SSLClient::is_ssl() const { return true; }
  13165. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13166. if (!is_valid()) {
  13167. error = Error::SSLConnection;
  13168. return false;
  13169. }
  13170. return ClientImpl::create_and_connect_socket(socket, error);
  13171. }
  13172. inline bool SSLClient::setup_proxy_connection(
  13173. Socket &socket,
  13174. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13175. Response &res, bool &success, Error &error) {
  13176. if (proxy_host_.empty() || proxy_port_ == -1) { return true; }
  13177. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13178. return false;
  13179. }
  13180. if (!initialize_ssl(socket, error)) {
  13181. success = false;
  13182. return false;
  13183. }
  13184. return true;
  13185. }
  13186. // Assumes that socket_mutex_ is locked and that there are no requests in
  13187. // flight
  13188. inline bool SSLClient::connect_with_proxy(
  13189. Socket &socket,
  13190. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13191. Response &res, bool &success, Error &error) {
  13192. success = true;
  13193. Response proxy_res;
  13194. if (!detail::process_client_socket(
  13195. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13196. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13197. start_time, [&](Stream &strm) {
  13198. Request req2;
  13199. req2.method = "CONNECT";
  13200. req2.path =
  13201. detail::make_host_and_port_string_always_port(host_, port_);
  13202. if (max_timeout_msec_ > 0) {
  13203. req2.start_time_ = std::chrono::steady_clock::now();
  13204. }
  13205. return process_request(strm, req2, proxy_res, false, error);
  13206. })) {
  13207. // Thread-safe to close everything because we are assuming there are no
  13208. // requests in flight
  13209. shutdown_ssl(socket, true);
  13210. shutdown_socket(socket);
  13211. close_socket(socket);
  13212. success = false;
  13213. return false;
  13214. }
  13215. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13216. if (!proxy_digest_auth_username_.empty() &&
  13217. !proxy_digest_auth_password_.empty()) {
  13218. std::map<std::string, std::string> auth;
  13219. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13220. // Close the current socket and create a new one for the authenticated
  13221. // request
  13222. shutdown_ssl(socket, true);
  13223. shutdown_socket(socket);
  13224. close_socket(socket);
  13225. // Create a new socket for the authenticated CONNECT request
  13226. if (!ensure_socket_connection(socket, error)) {
  13227. success = false;
  13228. output_error_log(error, nullptr);
  13229. return false;
  13230. }
  13231. proxy_res = Response();
  13232. if (!detail::process_client_socket(
  13233. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13234. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13235. start_time, [&](Stream &strm) {
  13236. Request req3;
  13237. req3.method = "CONNECT";
  13238. req3.path = detail::make_host_and_port_string_always_port(
  13239. host_, port_);
  13240. req3.headers.insert(detail::make_digest_authentication_header(
  13241. req3, auth, 1, detail::random_string(10),
  13242. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13243. true));
  13244. if (max_timeout_msec_ > 0) {
  13245. req3.start_time_ = std::chrono::steady_clock::now();
  13246. }
  13247. return process_request(strm, req3, proxy_res, false, error);
  13248. })) {
  13249. // Thread-safe to close everything because we are assuming there are
  13250. // no requests in flight
  13251. shutdown_ssl(socket, true);
  13252. shutdown_socket(socket);
  13253. close_socket(socket);
  13254. success = false;
  13255. return false;
  13256. }
  13257. }
  13258. }
  13259. }
  13260. // If status code is not 200, proxy request is failed.
  13261. // Set error to ProxyConnection and return proxy response
  13262. // as the response of the request
  13263. if (proxy_res.status != StatusCode::OK_200) {
  13264. error = Error::ProxyConnection;
  13265. output_error_log(error, nullptr);
  13266. res = std::move(proxy_res);
  13267. // Thread-safe to close everything because we are assuming there are
  13268. // no requests in flight
  13269. shutdown_ssl(socket, true);
  13270. shutdown_socket(socket);
  13271. close_socket(socket);
  13272. return false;
  13273. }
  13274. return true;
  13275. }
  13276. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13277. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13278. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  13279. if (!initialize_ssl(socket, error)) {
  13280. shutdown_socket(socket);
  13281. close_socket(socket);
  13282. return false;
  13283. }
  13284. return true;
  13285. }
  13286. // SSL HTTP client implementation
  13287. inline SSLClient::SSLClient(const std::string &host)
  13288. : SSLClient(host, 443, std::string(), std::string()) {}
  13289. inline SSLClient::SSLClient(const std::string &host, int port)
  13290. : SSLClient(host, port, std::string(), std::string()) {}
  13291. inline void SSLClient::init_ctx() {
  13292. ctx_ = tls::create_client_context();
  13293. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13294. }
  13295. inline void SSLClient::reset_ctx_on_error() {
  13296. last_backend_error_ = tls::get_error();
  13297. tls::free_context(ctx_);
  13298. ctx_ = nullptr;
  13299. }
  13300. inline SSLClient::SSLClient(const std::string &host, int port,
  13301. const std::string &client_cert_path,
  13302. const std::string &client_key_path,
  13303. const std::string &private_key_password)
  13304. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13305. init_ctx();
  13306. if (!ctx_) { return; }
  13307. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13308. const char *password =
  13309. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13310. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13311. client_key_path.c_str(), password)) {
  13312. reset_ctx_on_error();
  13313. }
  13314. }
  13315. }
  13316. inline SSLClient::SSLClient(const std::string &host, int port,
  13317. const PemMemory &pem)
  13318. : ClientImpl(host, port) {
  13319. init_ctx();
  13320. if (!ctx_) { return; }
  13321. if (pem.cert_pem && pem.key_pem) {
  13322. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13323. pem.private_key_password)) {
  13324. reset_ctx_on_error();
  13325. }
  13326. }
  13327. }
  13328. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13329. if (ca_cert_store && ctx_) {
  13330. // set_ca_store takes ownership of ca_cert_store
  13331. tls::set_ca_store(ctx_, ca_cert_store);
  13332. } else if (ca_cert_store) {
  13333. tls::free_ca_store(ca_cert_store);
  13334. }
  13335. }
  13336. inline void
  13337. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13338. if (!ctx_) { return; }
  13339. tls::set_verify_callback(ctx_, verifier);
  13340. }
  13341. inline void SSLClient::set_session_verifier(
  13342. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13343. session_verifier_ = std::move(verifier);
  13344. }
  13345. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13346. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13347. enable_windows_cert_verification_ = enabled;
  13348. }
  13349. #endif
  13350. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13351. std::size_t size) {
  13352. if (ctx_ && ca_cert && size > 0) {
  13353. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13354. tls::load_ca_pem(ctx_, ca_cert, size);
  13355. }
  13356. }
  13357. inline bool SSLClient::load_certs() {
  13358. auto ret = true;
  13359. std::call_once(initialize_cert_, [&]() {
  13360. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13361. if (!ca_cert_file_path_.empty()) {
  13362. if (!tls::load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  13363. last_backend_error_ = tls::get_error();
  13364. ret = false;
  13365. }
  13366. } else if (!ca_cert_dir_path_.empty()) {
  13367. if (!tls::load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  13368. last_backend_error_ = tls::get_error();
  13369. ret = false;
  13370. }
  13371. } else if (ca_cert_pem_.empty()) {
  13372. if (!tls::load_system_certs(ctx_)) {
  13373. last_backend_error_ = tls::get_error();
  13374. }
  13375. }
  13376. });
  13377. return ret;
  13378. }
  13379. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13380. using namespace tls;
  13381. // Load CA certificates if server verification is enabled
  13382. if (server_certificate_verification_) {
  13383. if (!load_certs()) {
  13384. error = Error::SSLLoadingCerts;
  13385. output_error_log(error, nullptr);
  13386. return false;
  13387. }
  13388. }
  13389. bool is_ip = detail::is_ip_address(host_);
  13390. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13391. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13392. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13393. // For IP addresses with verification enabled, use OPTIONAL mode since
  13394. // these backends require hostname for strict verification.
  13395. if (is_ip && server_certificate_verification_) {
  13396. set_verify_client(ctx_, false);
  13397. } else {
  13398. set_verify_client(ctx_, server_certificate_verification_);
  13399. }
  13400. #endif
  13401. // Create TLS session
  13402. session_t session = nullptr;
  13403. {
  13404. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13405. session = create_session(ctx_, socket.sock);
  13406. }
  13407. if (!session) {
  13408. error = Error::SSLConnection;
  13409. last_backend_error_ = get_error();
  13410. return false;
  13411. }
  13412. // Use scope_exit to ensure session is freed on error paths
  13413. bool success = false;
  13414. auto session_guard = detail::scope_exit([&] {
  13415. if (!success) { free_session(session); }
  13416. });
  13417. // Set SNI extension (skip for IP addresses per RFC 6066).
  13418. // On MbedTLS, set_sni also enables hostname verification internally.
  13419. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13420. if (!is_ip) {
  13421. if (!set_sni(session, host_.c_str())) {
  13422. error = Error::SSLConnection;
  13423. last_backend_error_ = get_error();
  13424. return false;
  13425. }
  13426. }
  13427. // Perform non-blocking TLS handshake with timeout
  13428. TlsError tls_err;
  13429. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13430. connection_timeout_usec_, &tls_err)) {
  13431. last_ssl_error_ = static_cast<int>(tls_err.code);
  13432. last_backend_error_ = tls_err.backend_code;
  13433. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13434. error = Error::SSLServerVerification;
  13435. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13436. error = Error::SSLServerHostnameVerification;
  13437. } else {
  13438. error = Error::SSLConnection;
  13439. }
  13440. output_error_log(error, nullptr);
  13441. return false;
  13442. }
  13443. // Post-handshake session verifier callback
  13444. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13445. if (session_verifier_) { verification_status = session_verifier_(session); }
  13446. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13447. last_backend_error_ = get_error();
  13448. error = Error::SSLServerVerification;
  13449. output_error_log(error, nullptr);
  13450. return false;
  13451. }
  13452. // Default server certificate verification
  13453. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  13454. server_certificate_verification_) {
  13455. verify_result_ = tls::get_verify_result(session);
  13456. if (verify_result_ != 0) {
  13457. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  13458. error = Error::SSLServerVerification;
  13459. output_error_log(error, nullptr);
  13460. return false;
  13461. }
  13462. auto server_cert = get_peer_cert(session);
  13463. if (!server_cert) {
  13464. last_backend_error_ = get_error();
  13465. error = Error::SSLServerVerification;
  13466. output_error_log(error, nullptr);
  13467. return false;
  13468. }
  13469. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  13470. // Hostname verification (post-handshake for all cases).
  13471. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  13472. // On MbedTLS, set_sni already enabled hostname verification during
  13473. // handshake for non-IP hosts, but this check is still needed for IP
  13474. // addresses where SNI is not set.
  13475. if (server_hostname_verification_) {
  13476. if (!verify_hostname(server_cert, host_.c_str())) {
  13477. last_backend_error_ = hostname_mismatch_code();
  13478. error = Error::SSLServerHostnameVerification;
  13479. output_error_log(error, nullptr);
  13480. return false;
  13481. }
  13482. }
  13483. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13484. // Additional Windows Schannel verification.
  13485. // This provides real-time certificate validation with Windows Update
  13486. // integration, working with both OpenSSL and MbedTLS backends.
  13487. // Skip when a custom CA cert is specified, as the Windows certificate
  13488. // store would not know about user-provided CA certificates.
  13489. if (enable_windows_cert_verification_ && ca_cert_file_path_.empty() &&
  13490. ca_cert_dir_path_.empty() && ca_cert_pem_.empty()) {
  13491. std::vector<unsigned char> der;
  13492. if (get_cert_der(server_cert, der)) {
  13493. uint64_t wincrypt_error = 0;
  13494. if (!detail::verify_cert_with_windows_schannel(
  13495. der, host_, server_hostname_verification_, wincrypt_error)) {
  13496. last_backend_error_ = wincrypt_error;
  13497. error = Error::SSLServerVerification;
  13498. output_error_log(error, nullptr);
  13499. return false;
  13500. }
  13501. }
  13502. }
  13503. #endif
  13504. }
  13505. success = true;
  13506. socket.ssl = session;
  13507. return true;
  13508. }
  13509. inline void Client::set_digest_auth(const std::string &username,
  13510. const std::string &password) {
  13511. cli_->set_digest_auth(username, password);
  13512. }
  13513. inline void Client::set_proxy_digest_auth(const std::string &username,
  13514. const std::string &password) {
  13515. cli_->set_proxy_digest_auth(username, password);
  13516. }
  13517. inline void Client::enable_server_certificate_verification(bool enabled) {
  13518. cli_->enable_server_certificate_verification(enabled);
  13519. }
  13520. inline void Client::enable_server_hostname_verification(bool enabled) {
  13521. cli_->enable_server_hostname_verification(enabled);
  13522. }
  13523. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13524. inline void Client::enable_windows_certificate_verification(bool enabled) {
  13525. if (is_ssl_) {
  13526. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  13527. enabled);
  13528. }
  13529. }
  13530. #endif
  13531. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  13532. const std::string &ca_cert_dir_path) {
  13533. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  13534. }
  13535. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13536. if (is_ssl_) {
  13537. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  13538. } else if (ca_cert_store) {
  13539. tls::free_ca_store(ca_cert_store);
  13540. }
  13541. }
  13542. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  13543. set_ca_cert_store(tls::create_ca_store(ca_cert, size));
  13544. }
  13545. inline void
  13546. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13547. if (is_ssl_) {
  13548. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  13549. std::move(verifier));
  13550. }
  13551. }
  13552. inline void Client::set_session_verifier(
  13553. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13554. if (is_ssl_) {
  13555. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  13556. }
  13557. }
  13558. inline tls::ctx_t Client::tls_context() const {
  13559. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  13560. return nullptr;
  13561. }
  13562. #endif // CPPHTTPLIB_SSL_ENABLED
  13563. /*
  13564. * Group 7: TLS abstraction layer - Common API
  13565. */
  13566. #ifdef CPPHTTPLIB_SSL_ENABLED
  13567. namespace tls {
  13568. // Helper for PeerCert construction
  13569. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  13570. return PeerCert(get_peer_cert(session));
  13571. }
  13572. namespace impl {
  13573. inline VerifyCallback &get_verify_callback() {
  13574. static thread_local VerifyCallback callback;
  13575. return callback;
  13576. }
  13577. inline VerifyCallback &get_mbedtls_verify_callback() {
  13578. static thread_local VerifyCallback callback;
  13579. return callback;
  13580. }
  13581. // Check if a string is an IPv4 address
  13582. inline bool is_ipv4_address(const std::string &str) {
  13583. int dots = 0;
  13584. for (char c : str) {
  13585. if (c == '.') {
  13586. dots++;
  13587. } else if (!isdigit(static_cast<unsigned char>(c))) {
  13588. return false;
  13589. }
  13590. }
  13591. return dots == 3;
  13592. }
  13593. // Parse IPv4 address string to bytes
  13594. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  13595. const char *p = str.c_str();
  13596. for (int i = 0; i < 4; i++) {
  13597. if (i > 0) {
  13598. if (*p != '.') { return false; }
  13599. p++;
  13600. }
  13601. int val = 0;
  13602. int digits = 0;
  13603. while (*p >= '0' && *p <= '9') {
  13604. val = val * 10 + (*p - '0');
  13605. if (val > 255) { return false; }
  13606. p++;
  13607. digits++;
  13608. }
  13609. if (digits == 0) { return false; }
  13610. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  13611. if (digits > 1 && *(p - digits) == '0') { return false; }
  13612. out[i] = static_cast<unsigned char>(val);
  13613. }
  13614. return *p == '\0';
  13615. }
  13616. #ifdef _WIN32
  13617. // Enumerate Windows system certificates and call callback with DER data
  13618. template <typename Callback>
  13619. inline bool enumerate_windows_system_certs(Callback cb) {
  13620. bool loaded = false;
  13621. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  13622. for (auto store_name : store_names) {
  13623. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  13624. if (hStore) {
  13625. PCCERT_CONTEXT pContext = nullptr;
  13626. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  13627. nullptr) {
  13628. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  13629. loaded = true;
  13630. }
  13631. }
  13632. CertCloseStore(hStore, 0);
  13633. }
  13634. }
  13635. return loaded;
  13636. }
  13637. #endif
  13638. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  13639. // Enumerate macOS Keychain certificates and call callback with DER data
  13640. template <typename Callback>
  13641. inline bool enumerate_macos_keychain_certs(Callback cb) {
  13642. bool loaded = false;
  13643. CFArrayRef certs = nullptr;
  13644. OSStatus status = SecTrustCopyAnchorCertificates(&certs);
  13645. if (status == errSecSuccess && certs) {
  13646. CFIndex count = CFArrayGetCount(certs);
  13647. for (CFIndex i = 0; i < count; i++) {
  13648. SecCertificateRef cert =
  13649. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  13650. CFDataRef data = SecCertificateCopyData(cert);
  13651. if (data) {
  13652. if (cb(CFDataGetBytePtr(data),
  13653. static_cast<size_t>(CFDataGetLength(data)))) {
  13654. loaded = true;
  13655. }
  13656. CFRelease(data);
  13657. }
  13658. }
  13659. CFRelease(certs);
  13660. }
  13661. return loaded;
  13662. }
  13663. #endif
  13664. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  13665. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  13666. // Common CA certificate file paths on Linux/Unix
  13667. inline const char **system_ca_paths() {
  13668. static const char *paths[] = {
  13669. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  13670. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  13671. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  13672. "/etc/pki/tls/cacert.pem", // OpenELEC
  13673. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  13674. nullptr};
  13675. return paths;
  13676. }
  13677. // Common CA certificate directory paths on Linux/Unix
  13678. inline const char **system_ca_dirs() {
  13679. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  13680. "/etc/pki/tls/certs", // RHEL/CentOS
  13681. "/usr/share/ca-certificates", // Other
  13682. nullptr};
  13683. return dirs;
  13684. }
  13685. #endif
  13686. } // namespace impl
  13687. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  13688. const char *ca_dir) {
  13689. if (!ctx) { return false; }
  13690. bool success = true;
  13691. if (ca_file && *ca_file) {
  13692. if (!load_ca_file(ctx, ca_file)) { success = false; }
  13693. }
  13694. if (ca_dir && *ca_dir) {
  13695. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  13696. }
  13697. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13698. // Set CA list for client certificate request (CertificateRequest message)
  13699. if (ca_file && *ca_file) {
  13700. auto list = SSL_load_client_CA_file(ca_file);
  13701. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  13702. }
  13703. #endif
  13704. return success;
  13705. }
  13706. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  13707. const char *password) {
  13708. return set_client_cert_pem(ctx, cert, key, password);
  13709. }
  13710. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  13711. const char *key_path, const char *password) {
  13712. return set_client_cert_file(ctx, cert_path, key_path, password);
  13713. }
  13714. // PeerCert implementation
  13715. inline PeerCert::PeerCert() = default;
  13716. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  13717. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  13718. other.cert_ = nullptr;
  13719. }
  13720. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  13721. if (this != &other) {
  13722. if (cert_) { free_cert(cert_); }
  13723. cert_ = other.cert_;
  13724. other.cert_ = nullptr;
  13725. }
  13726. return *this;
  13727. }
  13728. inline PeerCert::~PeerCert() {
  13729. if (cert_) { free_cert(cert_); }
  13730. }
  13731. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  13732. inline std::string PeerCert::subject_cn() const {
  13733. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  13734. }
  13735. inline std::string PeerCert::issuer_name() const {
  13736. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  13737. }
  13738. inline bool PeerCert::check_hostname(const char *hostname) const {
  13739. return cert_ ? verify_hostname(cert_, hostname) : false;
  13740. }
  13741. inline std::vector<SanEntry> PeerCert::sans() const {
  13742. std::vector<SanEntry> result;
  13743. if (cert_) { get_cert_sans(cert_, result); }
  13744. return result;
  13745. }
  13746. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  13747. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  13748. }
  13749. inline std::string PeerCert::serial() const {
  13750. return cert_ ? get_cert_serial(cert_) : std::string();
  13751. }
  13752. // VerifyContext method implementations
  13753. inline std::string VerifyContext::subject_cn() const {
  13754. return cert ? get_cert_subject_cn(cert) : std::string();
  13755. }
  13756. inline std::string VerifyContext::issuer_name() const {
  13757. return cert ? get_cert_issuer_name(cert) : std::string();
  13758. }
  13759. inline bool VerifyContext::check_hostname(const char *hostname) const {
  13760. return cert ? verify_hostname(cert, hostname) : false;
  13761. }
  13762. inline std::vector<SanEntry> VerifyContext::sans() const {
  13763. std::vector<SanEntry> result;
  13764. if (cert) { get_cert_sans(cert, result); }
  13765. return result;
  13766. }
  13767. inline bool VerifyContext::validity(time_t &not_before,
  13768. time_t &not_after) const {
  13769. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  13770. }
  13771. inline std::string VerifyContext::serial() const {
  13772. return cert ? get_cert_serial(cert) : std::string();
  13773. }
  13774. // TlsError static method implementation
  13775. inline std::string TlsError::verify_error_to_string(long error_code) {
  13776. return verify_error_string(error_code);
  13777. }
  13778. } // namespace tls
  13779. // Request::peer_cert() implementation
  13780. inline tls::PeerCert Request::peer_cert() const {
  13781. return tls::get_peer_cert_from_session(ssl);
  13782. }
  13783. // Request::sni() implementation
  13784. inline std::string Request::sni() const {
  13785. if (!ssl) { return std::string(); }
  13786. const char *s = tls::get_sni(ssl);
  13787. return s ? std::string(s) : std::string();
  13788. }
  13789. #endif // CPPHTTPLIB_SSL_ENABLED
  13790. /*
  13791. * Group 8: TLS abstraction layer - OpenSSL backend
  13792. */
  13793. /*
  13794. * OpenSSL Backend Implementation
  13795. */
  13796. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13797. namespace tls {
  13798. namespace impl {
  13799. // Helper to map OpenSSL SSL_get_error to ErrorCode
  13800. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  13801. switch (ssl_error) {
  13802. case SSL_ERROR_NONE: return ErrorCode::Success;
  13803. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  13804. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  13805. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  13806. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  13807. case SSL_ERROR_SSL:
  13808. default: return ErrorCode::Fatal;
  13809. }
  13810. }
  13811. // Helper: Create client CA list from PEM string
  13812. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  13813. // Caller takes ownership of returned list
  13814. inline STACK_OF(X509_NAME) *
  13815. create_client_ca_list_from_pem(const char *ca_pem) {
  13816. if (!ca_pem) { return nullptr; }
  13817. auto ca_list = sk_X509_NAME_new_null();
  13818. if (!ca_list) { return nullptr; }
  13819. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  13820. if (!bio) {
  13821. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  13822. return nullptr;
  13823. }
  13824. X509 *cert = nullptr;
  13825. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  13826. nullptr) {
  13827. const X509_NAME *name = X509_get_subject_name(cert);
  13828. if (name) {
  13829. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  13830. }
  13831. X509_free(cert);
  13832. }
  13833. BIO_free(bio);
  13834. return ca_list;
  13835. }
  13836. // OpenSSL verify callback wrapper
  13837. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  13838. auto &callback = get_verify_callback();
  13839. if (!callback) { return preverify_ok; }
  13840. // Get SSL object from X509_STORE_CTX
  13841. auto ssl = static_cast<SSL *>(
  13842. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  13843. if (!ssl) { return preverify_ok; }
  13844. // Get current certificate and depth
  13845. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  13846. int depth = X509_STORE_CTX_get_error_depth(ctx);
  13847. int error = X509_STORE_CTX_get_error(ctx);
  13848. // Build context
  13849. VerifyContext verify_ctx;
  13850. verify_ctx.session = static_cast<session_t>(ssl);
  13851. verify_ctx.cert = static_cast<cert_t>(cert);
  13852. verify_ctx.depth = depth;
  13853. verify_ctx.preverify_ok = (preverify_ok != 0);
  13854. verify_ctx.error_code = error;
  13855. verify_ctx.error_string =
  13856. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  13857. return callback(verify_ctx) ? 1 : 0;
  13858. }
  13859. } // namespace impl
  13860. inline ctx_t create_client_context() {
  13861. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  13862. if (ctx) {
  13863. // Disable auto-retry to properly handle non-blocking I/O
  13864. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  13865. // Set minimum TLS version
  13866. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  13867. }
  13868. return static_cast<ctx_t>(ctx);
  13869. }
  13870. inline void free_context(ctx_t ctx) {
  13871. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  13872. }
  13873. inline bool set_min_version(ctx_t ctx, Version version) {
  13874. if (!ctx) return false;
  13875. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  13876. static_cast<int>(version)) == 1;
  13877. }
  13878. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  13879. if (!ctx || !pem || len == 0) return false;
  13880. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13881. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13882. if (!store) return false;
  13883. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  13884. if (!bio) return false;
  13885. bool ok = true;
  13886. X509 *cert = nullptr;
  13887. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  13888. nullptr) {
  13889. if (X509_STORE_add_cert(store, cert) != 1) {
  13890. // Ignore duplicate errors
  13891. auto err = ERR_peek_last_error();
  13892. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  13893. ok = false;
  13894. }
  13895. }
  13896. X509_free(cert);
  13897. if (!ok) break;
  13898. }
  13899. BIO_free(bio);
  13900. // Clear any "no more certificates" errors
  13901. ERR_clear_error();
  13902. return ok;
  13903. }
  13904. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  13905. if (!ctx || !file_path) return false;
  13906. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  13907. nullptr) == 1;
  13908. }
  13909. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  13910. if (!ctx || !dir_path) return false;
  13911. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  13912. dir_path) == 1;
  13913. }
  13914. inline bool load_system_certs(ctx_t ctx) {
  13915. if (!ctx) return false;
  13916. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13917. #ifdef _WIN32
  13918. // Windows: Load from system certificate store (ROOT and CA)
  13919. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13920. if (!store) return false;
  13921. bool loaded_any = false;
  13922. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  13923. for (auto store_name : store_names) {
  13924. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  13925. if (!hStore) continue;
  13926. PCCERT_CONTEXT pContext = nullptr;
  13927. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  13928. nullptr) {
  13929. const unsigned char *data = pContext->pbCertEncoded;
  13930. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  13931. if (x509) {
  13932. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  13933. X509_free(x509);
  13934. }
  13935. }
  13936. CertCloseStore(hStore, 0);
  13937. }
  13938. return loaded_any;
  13939. #elif defined(__APPLE__)
  13940. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  13941. // macOS: Load from Keychain
  13942. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13943. if (!store) return false;
  13944. CFArrayRef certs = nullptr;
  13945. if (SecTrustCopyAnchorCertificates(&certs) != errSecSuccess || !certs) {
  13946. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  13947. }
  13948. bool loaded_any = false;
  13949. auto count = CFArrayGetCount(certs);
  13950. for (CFIndex i = 0; i < count; i++) {
  13951. auto cert = reinterpret_cast<SecCertificateRef>(
  13952. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  13953. CFDataRef der = SecCertificateCopyData(cert);
  13954. if (der) {
  13955. const unsigned char *data = CFDataGetBytePtr(der);
  13956. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  13957. if (x509) {
  13958. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  13959. X509_free(x509);
  13960. }
  13961. CFRelease(der);
  13962. }
  13963. }
  13964. CFRelease(certs);
  13965. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  13966. #else
  13967. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  13968. #endif
  13969. #else
  13970. // Other Unix: use default verify paths
  13971. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  13972. #endif
  13973. }
  13974. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  13975. const char *password) {
  13976. if (!ctx || !cert || !key) return false;
  13977. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13978. // Load certificate
  13979. auto cert_bio = BIO_new_mem_buf(cert, -1);
  13980. if (!cert_bio) return false;
  13981. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  13982. BIO_free(cert_bio);
  13983. if (!x509) return false;
  13984. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  13985. X509_free(x509);
  13986. if (!cert_ok) return false;
  13987. // Load private key
  13988. auto key_bio = BIO_new_mem_buf(key, -1);
  13989. if (!key_bio) return false;
  13990. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  13991. password ? const_cast<char *>(password)
  13992. : nullptr);
  13993. BIO_free(key_bio);
  13994. if (!pkey) return false;
  13995. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  13996. EVP_PKEY_free(pkey);
  13997. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  13998. }
  13999. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14000. const char *key_path, const char *password) {
  14001. if (!ctx || !cert_path || !key_path) return false;
  14002. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14003. if (password && password[0] != '\0') {
  14004. SSL_CTX_set_default_passwd_cb_userdata(
  14005. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14006. }
  14007. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14008. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14009. }
  14010. inline ctx_t create_server_context() {
  14011. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14012. if (ctx) {
  14013. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14014. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14015. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14016. }
  14017. return static_cast<ctx_t>(ctx);
  14018. }
  14019. inline void set_verify_client(ctx_t ctx, bool require) {
  14020. if (!ctx) return;
  14021. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14022. require
  14023. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14024. : SSL_VERIFY_NONE,
  14025. nullptr);
  14026. }
  14027. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14028. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14029. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14030. SSL *ssl = SSL_new(ssl_ctx);
  14031. if (!ssl) return nullptr;
  14032. // Disable auto-retry for proper non-blocking I/O handling
  14033. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14034. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14035. if (!bio) {
  14036. SSL_free(ssl);
  14037. return nullptr;
  14038. }
  14039. SSL_set_bio(ssl, bio, bio);
  14040. return static_cast<session_t>(ssl);
  14041. }
  14042. inline void free_session(session_t session) {
  14043. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14044. }
  14045. inline bool set_sni(session_t session, const char *hostname) {
  14046. if (!session || !hostname) return false;
  14047. auto ssl = static_cast<SSL *>(session);
  14048. // Set SNI (Server Name Indication) only - does not enable verification
  14049. #if defined(OPENSSL_IS_BORINGSSL)
  14050. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14051. #else
  14052. // Direct call instead of macro to suppress -Wold-style-cast warning
  14053. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14054. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14055. #endif
  14056. }
  14057. inline bool set_hostname(session_t session, const char *hostname) {
  14058. if (!session || !hostname) return false;
  14059. auto ssl = static_cast<SSL *>(session);
  14060. // Set SNI (Server Name Indication)
  14061. if (!set_sni(session, hostname)) { return false; }
  14062. // Enable hostname verification
  14063. auto param = SSL_get0_param(ssl);
  14064. if (!param) return false;
  14065. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14066. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14067. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14068. return true;
  14069. }
  14070. inline TlsError connect(session_t session) {
  14071. if (!session) { return TlsError(); }
  14072. auto ssl = static_cast<SSL *>(session);
  14073. auto ret = SSL_connect(ssl);
  14074. TlsError err;
  14075. if (ret == 1) {
  14076. err.code = ErrorCode::Success;
  14077. } else {
  14078. auto ssl_err = SSL_get_error(ssl, ret);
  14079. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14080. err.backend_code = ERR_get_error();
  14081. }
  14082. return err;
  14083. }
  14084. inline TlsError accept(session_t session) {
  14085. if (!session) { return TlsError(); }
  14086. auto ssl = static_cast<SSL *>(session);
  14087. auto ret = SSL_accept(ssl);
  14088. TlsError err;
  14089. if (ret == 1) {
  14090. err.code = ErrorCode::Success;
  14091. } else {
  14092. auto ssl_err = SSL_get_error(ssl, ret);
  14093. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14094. err.backend_code = ERR_get_error();
  14095. }
  14096. return err;
  14097. }
  14098. inline bool connect_nonblocking(session_t session, socket_t sock,
  14099. time_t timeout_sec, time_t timeout_usec,
  14100. TlsError *err) {
  14101. if (!session) {
  14102. if (err) { err->code = ErrorCode::Fatal; }
  14103. return false;
  14104. }
  14105. auto ssl = static_cast<SSL *>(session);
  14106. auto bio = SSL_get_rbio(ssl);
  14107. // Set non-blocking mode for handshake
  14108. detail::set_nonblocking(sock, true);
  14109. if (bio) { BIO_set_nbio(bio, 1); }
  14110. auto cleanup = detail::scope_exit([&]() {
  14111. // Restore blocking mode after handshake
  14112. if (bio) { BIO_set_nbio(bio, 0); }
  14113. detail::set_nonblocking(sock, false);
  14114. });
  14115. auto res = 0;
  14116. while ((res = SSL_connect(ssl)) != 1) {
  14117. auto ssl_err = SSL_get_error(ssl, res);
  14118. switch (ssl_err) {
  14119. case SSL_ERROR_WANT_READ:
  14120. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14121. continue;
  14122. }
  14123. break;
  14124. case SSL_ERROR_WANT_WRITE:
  14125. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14126. continue;
  14127. }
  14128. break;
  14129. default: break;
  14130. }
  14131. if (err) {
  14132. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14133. err->backend_code = ERR_get_error();
  14134. }
  14135. return false;
  14136. }
  14137. if (err) { err->code = ErrorCode::Success; }
  14138. return true;
  14139. }
  14140. inline bool accept_nonblocking(session_t session, socket_t sock,
  14141. time_t timeout_sec, time_t timeout_usec,
  14142. TlsError *err) {
  14143. if (!session) {
  14144. if (err) { err->code = ErrorCode::Fatal; }
  14145. return false;
  14146. }
  14147. auto ssl = static_cast<SSL *>(session);
  14148. auto bio = SSL_get_rbio(ssl);
  14149. // Set non-blocking mode for handshake
  14150. detail::set_nonblocking(sock, true);
  14151. if (bio) { BIO_set_nbio(bio, 1); }
  14152. auto cleanup = detail::scope_exit([&]() {
  14153. // Restore blocking mode after handshake
  14154. if (bio) { BIO_set_nbio(bio, 0); }
  14155. detail::set_nonblocking(sock, false);
  14156. });
  14157. auto res = 0;
  14158. while ((res = SSL_accept(ssl)) != 1) {
  14159. auto ssl_err = SSL_get_error(ssl, res);
  14160. switch (ssl_err) {
  14161. case SSL_ERROR_WANT_READ:
  14162. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14163. continue;
  14164. }
  14165. break;
  14166. case SSL_ERROR_WANT_WRITE:
  14167. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14168. continue;
  14169. }
  14170. break;
  14171. default: break;
  14172. }
  14173. if (err) {
  14174. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14175. err->backend_code = ERR_get_error();
  14176. }
  14177. return false;
  14178. }
  14179. if (err) { err->code = ErrorCode::Success; }
  14180. return true;
  14181. }
  14182. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14183. if (!session || !buf) {
  14184. err.code = ErrorCode::Fatal;
  14185. return -1;
  14186. }
  14187. auto ssl = static_cast<SSL *>(session);
  14188. constexpr auto max_len =
  14189. static_cast<size_t>((std::numeric_limits<int>::max)());
  14190. if (len > max_len) { len = max_len; }
  14191. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14192. if (ret > 0) {
  14193. err.code = ErrorCode::Success;
  14194. return ret;
  14195. }
  14196. auto ssl_err = SSL_get_error(ssl, ret);
  14197. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14198. if (err.code == ErrorCode::PeerClosed) {
  14199. return 0;
  14200. } // Gracefully handle the peer closed state.
  14201. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14202. return -1;
  14203. }
  14204. inline ssize_t write(session_t session, const void *buf, size_t len,
  14205. TlsError &err) {
  14206. if (!session || !buf) {
  14207. err.code = ErrorCode::Fatal;
  14208. return -1;
  14209. }
  14210. auto ssl = static_cast<SSL *>(session);
  14211. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14212. if (ret > 0) {
  14213. err.code = ErrorCode::Success;
  14214. return ret;
  14215. }
  14216. auto ssl_err = SSL_get_error(ssl, ret);
  14217. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14218. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14219. return -1;
  14220. }
  14221. inline int pending(const_session_t session) {
  14222. if (!session) return 0;
  14223. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14224. }
  14225. inline void shutdown(session_t session, bool graceful) {
  14226. if (!session) return;
  14227. auto ssl = static_cast<SSL *>(session);
  14228. if (graceful) {
  14229. // First call sends close_notify
  14230. if (SSL_shutdown(ssl) == 0) {
  14231. // Second call waits for peer's close_notify
  14232. SSL_shutdown(ssl);
  14233. }
  14234. }
  14235. }
  14236. inline bool is_peer_closed(session_t session, socket_t sock) {
  14237. if (!session) return true;
  14238. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14239. detail::set_nonblocking(sock, true);
  14240. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14241. auto ssl = static_cast<SSL *>(session);
  14242. char buf;
  14243. auto ret = SSL_peek(ssl, &buf, 1);
  14244. if (ret > 0) return false;
  14245. auto err = SSL_get_error(ssl, ret);
  14246. return err == SSL_ERROR_ZERO_RETURN;
  14247. }
  14248. inline cert_t get_peer_cert(const_session_t session) {
  14249. if (!session) return nullptr;
  14250. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14251. static_cast<SSL *>(const_cast<void *>(session))));
  14252. }
  14253. inline void free_cert(cert_t cert) {
  14254. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14255. }
  14256. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14257. if (!cert || !hostname) return false;
  14258. auto x509 = static_cast<X509 *>(cert);
  14259. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14260. if (detail::is_ip_address(hostname)) {
  14261. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14262. }
  14263. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14264. }
  14265. inline uint64_t hostname_mismatch_code() {
  14266. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14267. }
  14268. inline long get_verify_result(const_session_t session) {
  14269. if (!session) return X509_V_ERR_UNSPECIFIED;
  14270. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14271. }
  14272. inline std::string get_cert_subject_cn(cert_t cert) {
  14273. if (!cert) return "";
  14274. auto x509 = static_cast<X509 *>(cert);
  14275. auto subject_name = X509_get_subject_name(x509);
  14276. if (!subject_name) return "";
  14277. char buf[256];
  14278. auto len =
  14279. X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf, sizeof(buf));
  14280. if (len < 0) return "";
  14281. return std::string(buf, static_cast<size_t>(len));
  14282. }
  14283. inline std::string get_cert_issuer_name(cert_t cert) {
  14284. if (!cert) return "";
  14285. auto x509 = static_cast<X509 *>(cert);
  14286. auto issuer_name = X509_get_issuer_name(x509);
  14287. if (!issuer_name) return "";
  14288. char buf[256];
  14289. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14290. return std::string(buf);
  14291. }
  14292. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14293. sans.clear();
  14294. if (!cert) return false;
  14295. auto x509 = static_cast<X509 *>(cert);
  14296. auto names = static_cast<GENERAL_NAMES *>(
  14297. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14298. if (!names) return true; // No SANs is valid
  14299. auto count = sk_GENERAL_NAME_num(names);
  14300. for (decltype(count) i = 0; i < count; i++) {
  14301. auto gen = sk_GENERAL_NAME_value(names, i);
  14302. if (!gen) continue;
  14303. SanEntry entry;
  14304. switch (gen->type) {
  14305. case GEN_DNS:
  14306. entry.type = SanType::DNS;
  14307. if (gen->d.dNSName) {
  14308. entry.value = std::string(
  14309. reinterpret_cast<const char *>(
  14310. ASN1_STRING_get0_data(gen->d.dNSName)),
  14311. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14312. }
  14313. break;
  14314. case GEN_IPADD:
  14315. entry.type = SanType::IP;
  14316. if (gen->d.iPAddress) {
  14317. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14318. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14319. if (len == 4) {
  14320. // IPv4
  14321. char buf[INET_ADDRSTRLEN];
  14322. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14323. entry.value = buf;
  14324. } else if (len == 16) {
  14325. // IPv6
  14326. char buf[INET6_ADDRSTRLEN];
  14327. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14328. entry.value = buf;
  14329. }
  14330. }
  14331. break;
  14332. case GEN_EMAIL:
  14333. entry.type = SanType::EMAIL;
  14334. if (gen->d.rfc822Name) {
  14335. entry.value = std::string(
  14336. reinterpret_cast<const char *>(
  14337. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14338. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14339. }
  14340. break;
  14341. case GEN_URI:
  14342. entry.type = SanType::URI;
  14343. if (gen->d.uniformResourceIdentifier) {
  14344. entry.value = std::string(
  14345. reinterpret_cast<const char *>(
  14346. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14347. static_cast<size_t>(
  14348. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14349. }
  14350. break;
  14351. default: entry.type = SanType::OTHER; break;
  14352. }
  14353. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14354. }
  14355. GENERAL_NAMES_free(names);
  14356. return true;
  14357. }
  14358. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14359. time_t &not_after) {
  14360. if (!cert) return false;
  14361. auto x509 = static_cast<X509 *>(cert);
  14362. auto nb = X509_get0_notBefore(x509);
  14363. auto na = X509_get0_notAfter(x509);
  14364. if (!nb || !na) return false;
  14365. ASN1_TIME *epoch = ASN1_TIME_new();
  14366. if (!epoch) return false;
  14367. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  14368. if (!ASN1_TIME_set(epoch, 0)) return false;
  14369. int pday, psec;
  14370. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  14371. not_before = 86400 * (time_t)pday + psec;
  14372. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  14373. not_after = 86400 * (time_t)pday + psec;
  14374. return true;
  14375. }
  14376. inline std::string get_cert_serial(cert_t cert) {
  14377. if (!cert) return "";
  14378. auto x509 = static_cast<X509 *>(cert);
  14379. auto serial = X509_get_serialNumber(x509);
  14380. if (!serial) return "";
  14381. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  14382. if (!bn) return "";
  14383. auto hex = BN_bn2hex(bn);
  14384. BN_free(bn);
  14385. if (!hex) return "";
  14386. std::string result(hex);
  14387. OPENSSL_free(hex);
  14388. return result;
  14389. }
  14390. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14391. if (!cert) return false;
  14392. auto x509 = static_cast<X509 *>(cert);
  14393. auto len = i2d_X509(x509, nullptr);
  14394. if (len < 0) return false;
  14395. der.resize(static_cast<size_t>(len));
  14396. auto p = der.data();
  14397. i2d_X509(x509, &p);
  14398. return true;
  14399. }
  14400. inline const char *get_sni(const_session_t session) {
  14401. if (!session) return nullptr;
  14402. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14403. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14404. }
  14405. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  14406. inline uint64_t get_error() { return ERR_get_error(); }
  14407. inline std::string error_string(uint64_t code) {
  14408. char buf[256];
  14409. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  14410. return std::string(buf);
  14411. }
  14412. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14413. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  14414. if (!mem) { return nullptr; }
  14415. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  14416. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  14417. if (!inf) { return nullptr; }
  14418. auto store = X509_STORE_new();
  14419. if (store) {
  14420. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  14421. auto itmp = sk_X509_INFO_value(inf, i);
  14422. if (!itmp) { continue; }
  14423. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  14424. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  14425. }
  14426. }
  14427. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  14428. return static_cast<ca_store_t>(store);
  14429. }
  14430. inline void free_ca_store(ca_store_t store) {
  14431. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  14432. }
  14433. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  14434. if (!ctx || !store) { return false; }
  14435. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14436. auto x509_store = static_cast<X509_STORE *>(store);
  14437. // Check if same store is already set
  14438. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  14439. // SSL_CTX_set_cert_store takes ownership and frees the old store
  14440. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  14441. return true;
  14442. }
  14443. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  14444. certs.clear();
  14445. if (!ctx) { return 0; }
  14446. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14447. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14448. if (!store) { return 0; }
  14449. auto objs = X509_STORE_get0_objects(store);
  14450. if (!objs) { return 0; }
  14451. auto count = sk_X509_OBJECT_num(objs);
  14452. for (decltype(count) i = 0; i < count; i++) {
  14453. auto obj = sk_X509_OBJECT_value(objs, i);
  14454. if (!obj) { continue; }
  14455. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  14456. auto x509 = X509_OBJECT_get0_X509(obj);
  14457. if (x509) {
  14458. // Increment reference count so caller can free it
  14459. X509_up_ref(x509);
  14460. certs.push_back(static_cast<cert_t>(x509));
  14461. }
  14462. }
  14463. }
  14464. return certs.size();
  14465. }
  14466. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  14467. std::vector<std::string> names;
  14468. if (!ctx) { return names; }
  14469. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14470. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14471. if (!store) { return names; }
  14472. auto objs = X509_STORE_get0_objects(store);
  14473. if (!objs) { return names; }
  14474. auto count = sk_X509_OBJECT_num(objs);
  14475. for (decltype(count) i = 0; i < count; i++) {
  14476. auto obj = sk_X509_OBJECT_value(objs, i);
  14477. if (!obj) { continue; }
  14478. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  14479. auto x509 = X509_OBJECT_get0_X509(obj);
  14480. if (x509) {
  14481. auto subject = X509_get_subject_name(x509);
  14482. if (subject) {
  14483. char buf[512];
  14484. X509_NAME_oneline(subject, buf, sizeof(buf));
  14485. names.push_back(buf);
  14486. }
  14487. }
  14488. }
  14489. }
  14490. return names;
  14491. }
  14492. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  14493. const char *key_pem, const char *password) {
  14494. if (!ctx || !cert_pem || !key_pem) { return false; }
  14495. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14496. // Load certificate from PEM
  14497. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  14498. if (!cert_bio) { return false; }
  14499. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14500. BIO_free(cert_bio);
  14501. if (!cert) { return false; }
  14502. // Load private key from PEM
  14503. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  14504. if (!key_bio) {
  14505. X509_free(cert);
  14506. return false;
  14507. }
  14508. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14509. password ? const_cast<char *>(password)
  14510. : nullptr);
  14511. BIO_free(key_bio);
  14512. if (!key) {
  14513. X509_free(cert);
  14514. return false;
  14515. }
  14516. // Update certificate and key
  14517. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  14518. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  14519. X509_free(cert);
  14520. EVP_PKEY_free(key);
  14521. return ret;
  14522. }
  14523. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  14524. if (!ctx || !ca_pem) { return false; }
  14525. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14526. // Create new X509_STORE from PEM
  14527. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  14528. if (!store) { return false; }
  14529. // SSL_CTX_set_cert_store takes ownership
  14530. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  14531. // Set client CA list for client certificate request
  14532. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  14533. if (ca_list) {
  14534. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  14535. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  14536. }
  14537. return true;
  14538. }
  14539. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  14540. if (!ctx) { return false; }
  14541. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14542. impl::get_verify_callback() = std::move(callback);
  14543. if (impl::get_verify_callback()) {
  14544. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  14545. } else {
  14546. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  14547. }
  14548. return true;
  14549. }
  14550. inline long get_verify_error(const_session_t session) {
  14551. if (!session) { return -1; }
  14552. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14553. return SSL_get_verify_result(ssl);
  14554. }
  14555. inline std::string verify_error_string(long error_code) {
  14556. if (error_code == X509_V_OK) { return ""; }
  14557. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  14558. return str ? str : "unknown error";
  14559. }
  14560. } // namespace tls
  14561. inline bool SSLClient::verify_host(X509 *server_cert) const {
  14562. /* Quote from RFC2818 section 3.1 "Server Identity"
  14563. If a subjectAltName extension of type dNSName is present, that MUST
  14564. be used as the identity. Otherwise, the (most specific) Common Name
  14565. field in the Subject field of the certificate MUST be used. Although
  14566. the use of the Common Name is existing practice, it is deprecated and
  14567. Certification Authorities are encouraged to use the dNSName instead.
  14568. Matching is performed using the matching rules specified by
  14569. [RFC2459]. If more than one identity of a given type is present in
  14570. the certificate (e.g., more than one dNSName name, a match in any one
  14571. of the set is considered acceptable.) Names may contain the wildcard
  14572. character * which is considered to match any single domain name
  14573. component or component fragment. E.g., *.a.com matches foo.a.com but
  14574. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  14575. In some cases, the URI is specified as an IP address rather than a
  14576. hostname. In this case, the iPAddress subjectAltName must be present
  14577. in the certificate and must exactly match the IP in the URI.
  14578. */
  14579. return verify_host_with_subject_alt_name(server_cert) ||
  14580. verify_host_with_common_name(server_cert);
  14581. }
  14582. inline bool
  14583. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  14584. auto ret = false;
  14585. auto type = GEN_DNS;
  14586. struct in6_addr addr6 = {};
  14587. struct in_addr addr = {};
  14588. size_t addr_len = 0;
  14589. #ifndef __MINGW32__
  14590. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  14591. type = GEN_IPADD;
  14592. addr_len = sizeof(struct in6_addr);
  14593. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  14594. type = GEN_IPADD;
  14595. addr_len = sizeof(struct in_addr);
  14596. }
  14597. #endif
  14598. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  14599. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  14600. if (alt_names) {
  14601. auto dsn_matched = false;
  14602. auto ip_matched = false;
  14603. auto count = sk_GENERAL_NAME_num(alt_names);
  14604. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  14605. auto val = sk_GENERAL_NAME_value(alt_names, i);
  14606. if (!val || val->type != type) { continue; }
  14607. auto name =
  14608. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  14609. if (name == nullptr) { continue; }
  14610. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  14611. switch (type) {
  14612. case GEN_DNS:
  14613. dsn_matched =
  14614. detail::match_hostname(std::string(name, name_len), host_);
  14615. break;
  14616. case GEN_IPADD:
  14617. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  14618. ip_matched = true;
  14619. }
  14620. break;
  14621. }
  14622. }
  14623. if (dsn_matched || ip_matched) { ret = true; }
  14624. }
  14625. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  14626. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  14627. return ret;
  14628. }
  14629. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  14630. const auto subject_name = X509_get_subject_name(server_cert);
  14631. if (subject_name != nullptr) {
  14632. char name[BUFSIZ];
  14633. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  14634. name, sizeof(name));
  14635. if (name_len != -1) {
  14636. return detail::match_hostname(
  14637. std::string(name, static_cast<size_t>(name_len)), host_);
  14638. }
  14639. }
  14640. return false;
  14641. }
  14642. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  14643. /*
  14644. * Group 9: TLS abstraction layer - Mbed TLS backend
  14645. */
  14646. /*
  14647. * Mbed TLS Backend Implementation
  14648. */
  14649. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14650. namespace tls {
  14651. namespace impl {
  14652. // Mbed TLS session wrapper
  14653. struct MbedTlsSession {
  14654. mbedtls_ssl_context ssl;
  14655. socket_t sock = INVALID_SOCKET;
  14656. std::string hostname; // For client: set via set_sni
  14657. std::string sni_hostname; // For server: received from client via SNI callback
  14658. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  14659. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  14660. MbedTlsSession(const MbedTlsSession &) = delete;
  14661. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  14662. };
  14663. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  14664. // queue)
  14665. inline int &mbedtls_last_error() {
  14666. static thread_local int err = 0;
  14667. return err;
  14668. }
  14669. // Helper to map Mbed TLS error to ErrorCode
  14670. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  14671. if (ret == 0) { return ErrorCode::Success; }
  14672. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  14673. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  14674. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  14675. return ErrorCode::PeerClosed;
  14676. }
  14677. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  14678. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  14679. out_errno = errno;
  14680. return ErrorCode::SyscallError;
  14681. }
  14682. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  14683. return ErrorCode::CertVerifyFailed;
  14684. }
  14685. return ErrorCode::Fatal;
  14686. }
  14687. // BIO-like send callback for Mbed TLS
  14688. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  14689. size_t len) {
  14690. auto sock = *static_cast<socket_t *>(ctx);
  14691. #ifdef _WIN32
  14692. auto ret =
  14693. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  14694. if (ret == SOCKET_ERROR) {
  14695. int err = WSAGetLastError();
  14696. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  14697. return MBEDTLS_ERR_NET_SEND_FAILED;
  14698. }
  14699. #else
  14700. auto ret = send(sock, buf, len, 0);
  14701. if (ret < 0) {
  14702. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  14703. return MBEDTLS_ERR_SSL_WANT_WRITE;
  14704. }
  14705. return MBEDTLS_ERR_NET_SEND_FAILED;
  14706. }
  14707. #endif
  14708. return static_cast<int>(ret);
  14709. }
  14710. // BIO-like recv callback for Mbed TLS
  14711. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  14712. auto sock = *static_cast<socket_t *>(ctx);
  14713. #ifdef _WIN32
  14714. auto ret =
  14715. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  14716. if (ret == SOCKET_ERROR) {
  14717. int err = WSAGetLastError();
  14718. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  14719. return MBEDTLS_ERR_NET_RECV_FAILED;
  14720. }
  14721. #else
  14722. auto ret = recv(sock, buf, len, 0);
  14723. if (ret < 0) {
  14724. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  14725. return MBEDTLS_ERR_SSL_WANT_READ;
  14726. }
  14727. return MBEDTLS_ERR_NET_RECV_FAILED;
  14728. }
  14729. #endif
  14730. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  14731. return static_cast<int>(ret);
  14732. }
  14733. // MbedTlsContext constructor/destructor implementations
  14734. inline MbedTlsContext::MbedTlsContext() {
  14735. mbedtls_ssl_config_init(&conf);
  14736. mbedtls_entropy_init(&entropy);
  14737. mbedtls_ctr_drbg_init(&ctr_drbg);
  14738. mbedtls_x509_crt_init(&ca_chain);
  14739. mbedtls_x509_crt_init(&own_cert);
  14740. mbedtls_pk_init(&own_key);
  14741. }
  14742. inline MbedTlsContext::~MbedTlsContext() {
  14743. mbedtls_pk_free(&own_key);
  14744. mbedtls_x509_crt_free(&own_cert);
  14745. mbedtls_x509_crt_free(&ca_chain);
  14746. mbedtls_ctr_drbg_free(&ctr_drbg);
  14747. mbedtls_entropy_free(&entropy);
  14748. mbedtls_ssl_config_free(&conf);
  14749. }
  14750. // Thread-local storage for SNI captured during handshake
  14751. // This is needed because the SNI callback doesn't have a way to pass
  14752. // session-specific data before the session is fully set up
  14753. inline std::string &mbedpending_sni() {
  14754. static thread_local std::string sni;
  14755. return sni;
  14756. }
  14757. // SNI callback for Mbed TLS server to capture client's SNI hostname
  14758. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  14759. const unsigned char *name, size_t name_len) {
  14760. (void)p_ctx;
  14761. (void)ssl;
  14762. // Store SNI name in thread-local storage
  14763. // It will be retrieved and stored in the session after handshake
  14764. if (name && name_len > 0) {
  14765. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  14766. } else {
  14767. mbedpending_sni().clear();
  14768. }
  14769. return 0; // Accept any SNI
  14770. }
  14771. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  14772. int cert_depth, uint32_t *flags);
  14773. // MbedTLS verify callback wrapper
  14774. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  14775. int cert_depth, uint32_t *flags) {
  14776. auto &callback = get_verify_callback();
  14777. if (!callback) { return 0; } // Continue with default verification
  14778. // data points to the MbedTlsSession
  14779. auto *session = static_cast<MbedTlsSession *>(data);
  14780. // Build context
  14781. VerifyContext verify_ctx;
  14782. verify_ctx.session = static_cast<session_t>(session);
  14783. verify_ctx.cert = static_cast<cert_t>(crt);
  14784. verify_ctx.depth = cert_depth;
  14785. verify_ctx.preverify_ok = (*flags == 0);
  14786. verify_ctx.error_code = static_cast<long>(*flags);
  14787. // Convert Mbed TLS flags to error string
  14788. static thread_local char error_buf[256];
  14789. if (*flags != 0) {
  14790. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  14791. verify_ctx.error_string = error_buf;
  14792. } else {
  14793. verify_ctx.error_string = nullptr;
  14794. }
  14795. bool accepted = callback(verify_ctx);
  14796. if (accepted) {
  14797. *flags = 0; // Clear all error flags
  14798. return 0;
  14799. }
  14800. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  14801. }
  14802. } // namespace impl
  14803. inline ctx_t create_client_context() {
  14804. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  14805. if (!ctx) { return nullptr; }
  14806. ctx->is_server = false;
  14807. // Seed the random number generator
  14808. const char *pers = "httplib_client";
  14809. int ret = mbedtls_ctr_drbg_seed(
  14810. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  14811. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  14812. if (ret != 0) {
  14813. impl::mbedtls_last_error() = ret;
  14814. delete ctx;
  14815. return nullptr;
  14816. }
  14817. // Set up SSL config for client
  14818. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  14819. MBEDTLS_SSL_TRANSPORT_STREAM,
  14820. MBEDTLS_SSL_PRESET_DEFAULT);
  14821. if (ret != 0) {
  14822. impl::mbedtls_last_error() = ret;
  14823. delete ctx;
  14824. return nullptr;
  14825. }
  14826. // Set random number generator
  14827. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  14828. // Default: verify peer certificate
  14829. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14830. // Set minimum TLS version to 1.2
  14831. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14832. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14833. #else
  14834. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14835. MBEDTLS_SSL_MINOR_VERSION_3);
  14836. #endif
  14837. return static_cast<ctx_t>(ctx);
  14838. }
  14839. inline ctx_t create_server_context() {
  14840. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  14841. if (!ctx) { return nullptr; }
  14842. ctx->is_server = true;
  14843. // Seed the random number generator
  14844. const char *pers = "httplib_server";
  14845. int ret = mbedtls_ctr_drbg_seed(
  14846. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  14847. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  14848. if (ret != 0) {
  14849. impl::mbedtls_last_error() = ret;
  14850. delete ctx;
  14851. return nullptr;
  14852. }
  14853. // Set up SSL config for server
  14854. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  14855. MBEDTLS_SSL_TRANSPORT_STREAM,
  14856. MBEDTLS_SSL_PRESET_DEFAULT);
  14857. if (ret != 0) {
  14858. impl::mbedtls_last_error() = ret;
  14859. delete ctx;
  14860. return nullptr;
  14861. }
  14862. // Set random number generator
  14863. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  14864. // Default: don't verify client
  14865. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  14866. // Set minimum TLS version to 1.2
  14867. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14868. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14869. #else
  14870. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14871. MBEDTLS_SSL_MINOR_VERSION_3);
  14872. #endif
  14873. // Set SNI callback to capture client's SNI hostname
  14874. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  14875. return static_cast<ctx_t>(ctx);
  14876. }
  14877. inline void free_context(ctx_t ctx) {
  14878. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  14879. }
  14880. inline bool set_min_version(ctx_t ctx, Version version) {
  14881. if (!ctx) { return false; }
  14882. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14883. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14884. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  14885. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  14886. if (version >= Version::TLS1_3) {
  14887. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  14888. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  14889. #endif
  14890. }
  14891. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  14892. #else
  14893. // Mbed TLS 2.x uses major/minor version numbers
  14894. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  14895. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  14896. if (version >= Version::TLS1_3) {
  14897. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  14898. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  14899. #else
  14900. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  14901. #endif
  14902. }
  14903. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  14904. #endif
  14905. return true;
  14906. }
  14907. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14908. if (!ctx || !pem) { return false; }
  14909. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14910. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  14911. // Add null terminator if not present
  14912. std::string pem_str(pem, len);
  14913. int ret = mbedtls_x509_crt_parse(
  14914. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  14915. pem_str.size() + 1);
  14916. if (ret != 0) {
  14917. impl::mbedtls_last_error() = ret;
  14918. return false;
  14919. }
  14920. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  14921. return true;
  14922. }
  14923. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14924. if (!ctx || !file_path) { return false; }
  14925. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14926. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  14927. if (ret != 0) {
  14928. impl::mbedtls_last_error() = ret;
  14929. return false;
  14930. }
  14931. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  14932. return true;
  14933. }
  14934. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14935. if (!ctx || !dir_path) { return false; }
  14936. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14937. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  14938. if (ret < 0) { // Returns number of certs on success, negative on error
  14939. impl::mbedtls_last_error() = ret;
  14940. return false;
  14941. }
  14942. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  14943. return true;
  14944. }
  14945. inline bool load_system_certs(ctx_t ctx) {
  14946. if (!ctx) { return false; }
  14947. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14948. bool loaded = false;
  14949. #ifdef _WIN32
  14950. loaded = impl::enumerate_windows_system_certs(
  14951. [&](const unsigned char *data, size_t len) {
  14952. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  14953. });
  14954. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  14955. loaded = impl::enumerate_macos_keychain_certs(
  14956. [&](const unsigned char *data, size_t len) {
  14957. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  14958. });
  14959. #else
  14960. for (auto path = impl::system_ca_paths(); *path; ++path) {
  14961. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  14962. loaded = true;
  14963. break;
  14964. }
  14965. }
  14966. if (!loaded) {
  14967. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  14968. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  14969. loaded = true;
  14970. break;
  14971. }
  14972. }
  14973. }
  14974. #endif
  14975. if (loaded) {
  14976. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  14977. }
  14978. return loaded;
  14979. }
  14980. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14981. const char *password) {
  14982. if (!ctx || !cert || !key) { return false; }
  14983. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  14984. // Parse certificate
  14985. std::string cert_str(cert);
  14986. int ret = mbedtls_x509_crt_parse(
  14987. &mctx->own_cert,
  14988. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  14989. cert_str.size() + 1);
  14990. if (ret != 0) {
  14991. impl::mbedtls_last_error() = ret;
  14992. return false;
  14993. }
  14994. // Parse private key
  14995. std::string key_str(key);
  14996. const unsigned char *pwd =
  14997. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  14998. size_t pwd_len = password ? strlen(password) : 0;
  14999. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15000. ret = mbedtls_pk_parse_key(
  15001. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15002. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15003. &mctx->ctr_drbg);
  15004. #else
  15005. ret = mbedtls_pk_parse_key(
  15006. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15007. key_str.size() + 1, pwd, pwd_len);
  15008. #endif
  15009. if (ret != 0) {
  15010. impl::mbedtls_last_error() = ret;
  15011. return false;
  15012. }
  15013. // Verify that the certificate and private key match
  15014. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15015. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15016. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15017. #else
  15018. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15019. #endif
  15020. if (ret != 0) {
  15021. impl::mbedtls_last_error() = ret;
  15022. return false;
  15023. }
  15024. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15025. if (ret != 0) {
  15026. impl::mbedtls_last_error() = ret;
  15027. return false;
  15028. }
  15029. return true;
  15030. }
  15031. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15032. const char *key_path, const char *password) {
  15033. if (!ctx || !cert_path || !key_path) { return false; }
  15034. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15035. // Parse certificate file
  15036. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15037. if (ret != 0) {
  15038. impl::mbedtls_last_error() = ret;
  15039. return false;
  15040. }
  15041. // Parse private key file
  15042. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15043. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15044. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15045. #else
  15046. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15047. #endif
  15048. if (ret != 0) {
  15049. impl::mbedtls_last_error() = ret;
  15050. return false;
  15051. }
  15052. // Verify that the certificate and private key match
  15053. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15054. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15055. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15056. #else
  15057. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15058. #endif
  15059. if (ret != 0) {
  15060. impl::mbedtls_last_error() = ret;
  15061. return false;
  15062. }
  15063. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15064. if (ret != 0) {
  15065. impl::mbedtls_last_error() = ret;
  15066. return false;
  15067. }
  15068. return true;
  15069. }
  15070. inline void set_verify_client(ctx_t ctx, bool require) {
  15071. if (!ctx) { return; }
  15072. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15073. mctx->verify_client = require;
  15074. if (require) {
  15075. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15076. } else {
  15077. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15078. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15079. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15080. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15081. : MBEDTLS_SSL_VERIFY_NONE);
  15082. }
  15083. }
  15084. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15085. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15086. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15087. auto session = new (std::nothrow) impl::MbedTlsSession();
  15088. if (!session) { return nullptr; }
  15089. session->sock = sock;
  15090. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15091. if (ret != 0) {
  15092. impl::mbedtls_last_error() = ret;
  15093. delete session;
  15094. return nullptr;
  15095. }
  15096. // Set BIO callbacks
  15097. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15098. impl::mbedtls_net_recv_cb, nullptr);
  15099. // Set per-session verify callback with session pointer if callback is
  15100. // registered
  15101. if (mctx->has_verify_callback) {
  15102. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15103. session);
  15104. }
  15105. return static_cast<session_t>(session);
  15106. }
  15107. inline void free_session(session_t session) {
  15108. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15109. }
  15110. inline bool set_sni(session_t session, const char *hostname) {
  15111. if (!session || !hostname) { return false; }
  15112. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15113. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15114. if (ret != 0) {
  15115. impl::mbedtls_last_error() = ret;
  15116. return false;
  15117. }
  15118. msession->hostname = hostname;
  15119. return true;
  15120. }
  15121. inline bool set_hostname(session_t session, const char *hostname) {
  15122. // In Mbed TLS, set_hostname also sets up hostname verification
  15123. return set_sni(session, hostname);
  15124. }
  15125. inline TlsError connect(session_t session) {
  15126. TlsError err;
  15127. if (!session) {
  15128. err.code = ErrorCode::Fatal;
  15129. return err;
  15130. }
  15131. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15132. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15133. if (ret == 0) {
  15134. err.code = ErrorCode::Success;
  15135. } else {
  15136. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15137. err.backend_code = static_cast<uint64_t>(-ret);
  15138. impl::mbedtls_last_error() = ret;
  15139. }
  15140. return err;
  15141. }
  15142. inline TlsError accept(session_t session) {
  15143. // Same as connect for Mbed TLS - handshake works for both client and server
  15144. auto result = connect(session);
  15145. // After successful handshake, capture SNI from thread-local storage
  15146. if (result.code == ErrorCode::Success && session) {
  15147. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15148. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15149. impl::mbedpending_sni().clear();
  15150. }
  15151. return result;
  15152. }
  15153. inline bool connect_nonblocking(session_t session, socket_t sock,
  15154. time_t timeout_sec, time_t timeout_usec,
  15155. TlsError *err) {
  15156. if (!session) {
  15157. if (err) { err->code = ErrorCode::Fatal; }
  15158. return false;
  15159. }
  15160. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15161. // Set socket to non-blocking mode
  15162. detail::set_nonblocking(sock, true);
  15163. auto cleanup =
  15164. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15165. int ret;
  15166. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15167. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15168. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15169. continue;
  15170. }
  15171. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15172. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15173. continue;
  15174. }
  15175. }
  15176. // TlsError or timeout
  15177. if (err) {
  15178. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15179. err->backend_code = static_cast<uint64_t>(-ret);
  15180. }
  15181. impl::mbedtls_last_error() = ret;
  15182. return false;
  15183. }
  15184. if (err) { err->code = ErrorCode::Success; }
  15185. return true;
  15186. }
  15187. inline bool accept_nonblocking(session_t session, socket_t sock,
  15188. time_t timeout_sec, time_t timeout_usec,
  15189. TlsError *err) {
  15190. // Same implementation as connect for Mbed TLS
  15191. bool result =
  15192. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15193. // After successful handshake, capture SNI from thread-local storage
  15194. if (result && session) {
  15195. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15196. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15197. impl::mbedpending_sni().clear();
  15198. }
  15199. return result;
  15200. }
  15201. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15202. if (!session || !buf) {
  15203. err.code = ErrorCode::Fatal;
  15204. return -1;
  15205. }
  15206. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15207. int ret =
  15208. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15209. if (ret > 0) {
  15210. err.code = ErrorCode::Success;
  15211. return static_cast<ssize_t>(ret);
  15212. }
  15213. if (ret == 0) {
  15214. err.code = ErrorCode::PeerClosed;
  15215. return 0;
  15216. }
  15217. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15218. err.backend_code = static_cast<uint64_t>(-ret);
  15219. impl::mbedtls_last_error() = ret;
  15220. // mbedTLS signals a clean close_notify via a negative error code rather
  15221. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15222. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15223. return -1;
  15224. }
  15225. inline ssize_t write(session_t session, const void *buf, size_t len,
  15226. TlsError &err) {
  15227. if (!session || !buf) {
  15228. err.code = ErrorCode::Fatal;
  15229. return -1;
  15230. }
  15231. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15232. int ret = mbedtls_ssl_write(&msession->ssl,
  15233. static_cast<const unsigned char *>(buf), len);
  15234. if (ret > 0) {
  15235. err.code = ErrorCode::Success;
  15236. return static_cast<ssize_t>(ret);
  15237. }
  15238. if (ret == 0) {
  15239. err.code = ErrorCode::PeerClosed;
  15240. return 0;
  15241. }
  15242. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15243. err.backend_code = static_cast<uint64_t>(-ret);
  15244. impl::mbedtls_last_error() = ret;
  15245. return -1;
  15246. }
  15247. inline int pending(const_session_t session) {
  15248. if (!session) { return 0; }
  15249. auto msession =
  15250. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15251. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15252. }
  15253. inline void shutdown(session_t session, bool graceful) {
  15254. if (!session) { return; }
  15255. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15256. if (graceful) {
  15257. // Try to send close_notify, but don't block forever
  15258. int ret;
  15259. int attempts = 0;
  15260. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15261. attempts < 3) {
  15262. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15263. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15264. break;
  15265. }
  15266. attempts++;
  15267. }
  15268. }
  15269. }
  15270. inline bool is_peer_closed(session_t session, socket_t sock) {
  15271. if (!session || sock == INVALID_SOCKET) { return true; }
  15272. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15273. // Check if there's already decrypted data available in the TLS buffer
  15274. // If so, the connection is definitely alive
  15275. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15276. // Set socket to non-blocking to avoid blocking on read
  15277. detail::set_nonblocking(sock, true);
  15278. auto cleanup =
  15279. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15280. // Try a 1-byte read to check connection status
  15281. // Note: This will consume the byte if data is available, but for the
  15282. // purpose of checking if peer is closed, this should be acceptable
  15283. // since we're only called when we expect the connection might be closing
  15284. unsigned char buf;
  15285. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15286. // If we got data or WANT_READ (would block), connection is alive
  15287. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15288. // If we get a peer close notify or a connection reset, the peer is closed
  15289. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15290. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15291. }
  15292. inline cert_t get_peer_cert(const_session_t session) {
  15293. if (!session) { return nullptr; }
  15294. auto msession =
  15295. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15296. // Mbed TLS returns a pointer to the internal peer cert chain.
  15297. // WARNING: This pointer is only valid while the session is active.
  15298. // Do not use the certificate after calling free_session().
  15299. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15300. return const_cast<mbedtls_x509_crt *>(cert);
  15301. }
  15302. inline void free_cert(cert_t cert) {
  15303. // Mbed TLS: peer certificate is owned by the SSL context.
  15304. // No-op here, but callers should still call this for cross-backend
  15305. // portability.
  15306. (void)cert;
  15307. }
  15308. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15309. if (!cert || !hostname) { return false; }
  15310. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15311. std::string host_str(hostname);
  15312. // Check if hostname is an IP address
  15313. bool is_ip = impl::is_ipv4_address(host_str);
  15314. unsigned char ip_bytes[4];
  15315. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  15316. // Check Subject Alternative Names (SAN)
  15317. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15318. // - DNS names: raw string bytes
  15319. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15320. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15321. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15322. const unsigned char *p = san->buf.p;
  15323. size_t len = san->buf.len;
  15324. if (is_ip) {
  15325. // Check if this SAN is an IPv4 address (4 bytes)
  15326. if (len == 4 && memcmp(p, ip_bytes, 4) == 0) { return true; }
  15327. // Check if this SAN is an IPv6 address (16 bytes) - skip for now
  15328. } else {
  15329. // Check if this SAN is a DNS name (printable ASCII string)
  15330. bool is_dns = len > 0;
  15331. for (size_t i = 0; i < len && is_dns; i++) {
  15332. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15333. }
  15334. if (is_dns) {
  15335. std::string san_name(reinterpret_cast<const char *>(p), len);
  15336. if (detail::match_hostname(san_name, host_str)) { return true; }
  15337. }
  15338. }
  15339. san = san->next;
  15340. }
  15341. // Fallback: Check Common Name (CN) in subject
  15342. char cn[256];
  15343. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15344. if (ret > 0) {
  15345. std::string cn_str(cn);
  15346. // Look for "CN=" in the DN string
  15347. size_t cn_pos = cn_str.find("CN=");
  15348. if (cn_pos != std::string::npos) {
  15349. size_t start = cn_pos + 3;
  15350. size_t end = cn_str.find(',', start);
  15351. std::string cn_value =
  15352. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15353. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15354. }
  15355. }
  15356. return false;
  15357. }
  15358. inline uint64_t hostname_mismatch_code() {
  15359. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15360. }
  15361. inline long get_verify_result(const_session_t session) {
  15362. if (!session) { return -1; }
  15363. auto msession =
  15364. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15365. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15366. // Return 0 (X509_V_OK equivalent) if verification passed
  15367. return flags == 0 ? 0 : static_cast<long>(flags);
  15368. }
  15369. inline std::string get_cert_subject_cn(cert_t cert) {
  15370. if (!cert) return "";
  15371. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15372. // Find the CN in the subject
  15373. const mbedtls_x509_name *name = &x509->subject;
  15374. while (name != nullptr) {
  15375. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15376. return std::string(reinterpret_cast<const char *>(name->val.p),
  15377. name->val.len);
  15378. }
  15379. name = name->next;
  15380. }
  15381. return "";
  15382. }
  15383. inline std::string get_cert_issuer_name(cert_t cert) {
  15384. if (!cert) return "";
  15385. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15386. // Build a human-readable issuer name string
  15387. char buf[512];
  15388. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15389. if (ret < 0) return "";
  15390. return std::string(buf);
  15391. }
  15392. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15393. sans.clear();
  15394. if (!cert) return false;
  15395. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15396. // Parse the Subject Alternative Name extension
  15397. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15398. while (cur != nullptr) {
  15399. if (cur->buf.len > 0) {
  15400. // Mbed TLS stores SAN as ASN.1 sequences
  15401. // The tag byte indicates the type
  15402. const unsigned char *p = cur->buf.p;
  15403. size_t len = cur->buf.len;
  15404. // First byte is the tag
  15405. unsigned char tag = *p;
  15406. p++;
  15407. len--;
  15408. // Parse length (simple single-byte length assumed)
  15409. if (len > 0 && *p < 0x80) {
  15410. size_t value_len = *p;
  15411. p++;
  15412. len--;
  15413. if (value_len <= len) {
  15414. SanEntry entry;
  15415. // ASN.1 context tags for GeneralName
  15416. switch (tag & 0x1F) {
  15417. case 2: // dNSName
  15418. entry.type = SanType::DNS;
  15419. entry.value =
  15420. std::string(reinterpret_cast<const char *>(p), value_len);
  15421. break;
  15422. case 7: // iPAddress
  15423. entry.type = SanType::IP;
  15424. if (value_len == 4) {
  15425. // IPv4
  15426. char buf[16];
  15427. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15428. entry.value = buf;
  15429. } else if (value_len == 16) {
  15430. // IPv6
  15431. char buf[64];
  15432. snprintf(buf, sizeof(buf),
  15433. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  15434. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  15435. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  15436. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  15437. entry.value = buf;
  15438. }
  15439. break;
  15440. case 1: // rfc822Name (email)
  15441. entry.type = SanType::EMAIL;
  15442. entry.value =
  15443. std::string(reinterpret_cast<const char *>(p), value_len);
  15444. break;
  15445. case 6: // uniformResourceIdentifier
  15446. entry.type = SanType::URI;
  15447. entry.value =
  15448. std::string(reinterpret_cast<const char *>(p), value_len);
  15449. break;
  15450. default: entry.type = SanType::OTHER; break;
  15451. }
  15452. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15453. }
  15454. }
  15455. }
  15456. cur = cur->next;
  15457. }
  15458. return true;
  15459. }
  15460. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15461. time_t &not_after) {
  15462. if (!cert) return false;
  15463. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15464. // Convert mbedtls_x509_time to time_t
  15465. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  15466. struct tm tm_time = {};
  15467. tm_time.tm_year = t.year - 1900;
  15468. tm_time.tm_mon = t.mon - 1;
  15469. tm_time.tm_mday = t.day;
  15470. tm_time.tm_hour = t.hour;
  15471. tm_time.tm_min = t.min;
  15472. tm_time.tm_sec = t.sec;
  15473. #ifdef _WIN32
  15474. return _mkgmtime(&tm_time);
  15475. #else
  15476. return timegm(&tm_time);
  15477. #endif
  15478. };
  15479. not_before = to_time_t(x509->valid_from);
  15480. not_after = to_time_t(x509->valid_to);
  15481. return true;
  15482. }
  15483. inline std::string get_cert_serial(cert_t cert) {
  15484. if (!cert) return "";
  15485. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15486. // Convert serial number to hex string
  15487. std::string result;
  15488. result.reserve(x509->serial.len * 2);
  15489. for (size_t i = 0; i < x509->serial.len; i++) {
  15490. char hex[3];
  15491. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  15492. result += hex;
  15493. }
  15494. return result;
  15495. }
  15496. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15497. if (!cert) return false;
  15498. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  15499. if (!crt->raw.p || crt->raw.len == 0) return false;
  15500. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  15501. return true;
  15502. }
  15503. inline const char *get_sni(const_session_t session) {
  15504. if (!session) return nullptr;
  15505. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  15506. // For server: return SNI received from client during handshake
  15507. if (!msession->sni_hostname.empty()) {
  15508. return msession->sni_hostname.c_str();
  15509. }
  15510. // For client: return the hostname set via set_sni
  15511. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  15512. return nullptr;
  15513. }
  15514. inline uint64_t peek_error() {
  15515. // Mbed TLS doesn't have an error queue, return the last error
  15516. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  15517. }
  15518. inline uint64_t get_error() {
  15519. // Mbed TLS doesn't have an error queue, return and clear the last error
  15520. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  15521. impl::mbedtls_last_error() = 0;
  15522. return err;
  15523. }
  15524. inline std::string error_string(uint64_t code) {
  15525. char buf[256];
  15526. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  15527. return std::string(buf);
  15528. }
  15529. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  15530. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  15531. if (!ca_chain) { return nullptr; }
  15532. mbedtls_x509_crt_init(ca_chain);
  15533. // mbedtls_x509_crt_parse expects null-terminated PEM
  15534. int ret = mbedtls_x509_crt_parse(ca_chain,
  15535. reinterpret_cast<const unsigned char *>(pem),
  15536. len + 1); // +1 for null terminator
  15537. if (ret != 0) {
  15538. // Try without +1 in case PEM is already null-terminated
  15539. ret = mbedtls_x509_crt_parse(
  15540. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  15541. if (ret != 0) {
  15542. mbedtls_x509_crt_free(ca_chain);
  15543. delete ca_chain;
  15544. return nullptr;
  15545. }
  15546. }
  15547. return static_cast<ca_store_t>(ca_chain);
  15548. }
  15549. inline void free_ca_store(ca_store_t store) {
  15550. if (store) {
  15551. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  15552. mbedtls_x509_crt_free(ca_chain);
  15553. delete ca_chain;
  15554. }
  15555. }
  15556. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15557. if (!ctx || !store) { return false; }
  15558. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15559. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  15560. // Free existing CA chain
  15561. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  15562. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  15563. // Copy the CA chain (deep copy)
  15564. // Parse from the raw data of the source cert
  15565. mbedtls_x509_crt *src = ca_chain;
  15566. while (src != nullptr) {
  15567. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  15568. src->raw.len);
  15569. if (ret != 0) { return false; }
  15570. src = src->next;
  15571. }
  15572. // Update the SSL config to use the new CA chain
  15573. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  15574. return true;
  15575. }
  15576. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15577. certs.clear();
  15578. if (!ctx) { return 0; }
  15579. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15580. // Iterate through the CA chain
  15581. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  15582. while (cert != nullptr && cert->raw.len > 0) {
  15583. // Create a copy of the certificate for the caller
  15584. auto *copy = new mbedtls_x509_crt;
  15585. mbedtls_x509_crt_init(copy);
  15586. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  15587. if (ret == 0) {
  15588. certs.push_back(static_cast<cert_t>(copy));
  15589. } else {
  15590. mbedtls_x509_crt_free(copy);
  15591. delete copy;
  15592. }
  15593. cert = cert->next;
  15594. }
  15595. return certs.size();
  15596. }
  15597. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15598. std::vector<std::string> names;
  15599. if (!ctx) { return names; }
  15600. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15601. // Iterate through the CA chain
  15602. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  15603. while (cert != nullptr && cert->raw.len > 0) {
  15604. char buf[512];
  15605. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  15606. if (ret > 0) { names.push_back(buf); }
  15607. cert = cert->next;
  15608. }
  15609. return names;
  15610. }
  15611. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15612. const char *key_pem, const char *password) {
  15613. if (!ctx || !cert_pem || !key_pem) { return false; }
  15614. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15615. // Free existing certificate and key
  15616. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  15617. mbedtls_pk_free(&mbed_ctx->own_key);
  15618. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  15619. mbedtls_pk_init(&mbed_ctx->own_key);
  15620. // Parse certificate PEM
  15621. int ret = mbedtls_x509_crt_parse(
  15622. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  15623. strlen(cert_pem) + 1);
  15624. if (ret != 0) {
  15625. impl::mbedtls_last_error() = ret;
  15626. return false;
  15627. }
  15628. // Parse private key PEM
  15629. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15630. ret = mbedtls_pk_parse_key(
  15631. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  15632. strlen(key_pem) + 1,
  15633. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  15634. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  15635. &mbed_ctx->ctr_drbg);
  15636. #else
  15637. ret = mbedtls_pk_parse_key(
  15638. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  15639. strlen(key_pem) + 1,
  15640. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  15641. password ? strlen(password) : 0);
  15642. #endif
  15643. if (ret != 0) {
  15644. impl::mbedtls_last_error() = ret;
  15645. return false;
  15646. }
  15647. // Configure SSL to use the new certificate and key
  15648. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  15649. &mbed_ctx->own_key);
  15650. if (ret != 0) {
  15651. impl::mbedtls_last_error() = ret;
  15652. return false;
  15653. }
  15654. return true;
  15655. }
  15656. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15657. if (!ctx || !ca_pem) { return false; }
  15658. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15659. // Free existing CA chain
  15660. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  15661. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  15662. // Parse CA PEM
  15663. int ret = mbedtls_x509_crt_parse(
  15664. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  15665. strlen(ca_pem) + 1);
  15666. if (ret != 0) {
  15667. impl::mbedtls_last_error() = ret;
  15668. return false;
  15669. }
  15670. // Update SSL config to use new CA chain
  15671. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  15672. return true;
  15673. }
  15674. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15675. if (!ctx) { return false; }
  15676. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  15677. impl::get_verify_callback() = std::move(callback);
  15678. mbed_ctx->has_verify_callback =
  15679. static_cast<bool>(impl::get_verify_callback());
  15680. if (mbed_ctx->has_verify_callback) {
  15681. // Set OPTIONAL mode to ensure callback is called even when verification
  15682. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  15683. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  15684. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  15685. nullptr);
  15686. } else {
  15687. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  15688. }
  15689. return true;
  15690. }
  15691. inline long get_verify_error(const_session_t session) {
  15692. if (!session) { return -1; }
  15693. auto *msession =
  15694. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15695. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  15696. }
  15697. inline std::string verify_error_string(long error_code) {
  15698. if (error_code == 0) { return ""; }
  15699. char buf[256];
  15700. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  15701. static_cast<uint32_t>(error_code));
  15702. // Remove trailing newline if present
  15703. std::string result(buf);
  15704. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  15705. result.pop_back();
  15706. }
  15707. return result;
  15708. }
  15709. } // namespace tls
  15710. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  15711. /*
  15712. * Group 10: TLS abstraction layer - wolfSSL backend
  15713. */
  15714. /*
  15715. * wolfSSL Backend Implementation
  15716. */
  15717. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  15718. namespace tls {
  15719. namespace impl {
  15720. // wolfSSL session wrapper
  15721. struct WolfSSLSession {
  15722. WOLFSSL *ssl = nullptr;
  15723. socket_t sock = INVALID_SOCKET;
  15724. std::string hostname; // For client: set via set_sni
  15725. std::string sni_hostname; // For server: received from client via SNI callback
  15726. WolfSSLSession() = default;
  15727. ~WolfSSLSession() {
  15728. if (ssl) { wolfSSL_free(ssl); }
  15729. }
  15730. WolfSSLSession(const WolfSSLSession &) = delete;
  15731. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  15732. };
  15733. // Thread-local error code accessor for wolfSSL
  15734. inline uint64_t &wolfssl_last_error() {
  15735. static thread_local uint64_t err = 0;
  15736. return err;
  15737. }
  15738. // Helper to map wolfSSL error to ErrorCode.
  15739. // ssl_error is the value from wolfSSL_get_error().
  15740. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  15741. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  15742. int &out_errno) {
  15743. switch (ssl_error) {
  15744. case SSL_ERROR_NONE: return ErrorCode::Success;
  15745. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  15746. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  15747. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  15748. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  15749. default:
  15750. if (ssl) {
  15751. // wolfSSL stores the low-level error code as a negative value.
  15752. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  15753. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  15754. if (low_err == DOMAIN_NAME_MISMATCH) {
  15755. return ErrorCode::HostnameMismatch;
  15756. }
  15757. // Check verify result to distinguish cert verification from generic SSL
  15758. // errors.
  15759. long vr = wolfSSL_get_verify_result(ssl);
  15760. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  15761. }
  15762. return ErrorCode::Fatal;
  15763. }
  15764. }
  15765. // WolfSSLContext constructor/destructor implementations
  15766. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  15767. inline WolfSSLContext::~WolfSSLContext() {
  15768. if (ctx) { wolfSSL_CTX_free(ctx); }
  15769. }
  15770. // Thread-local storage for SNI captured during handshake
  15771. inline std::string &wolfssl_pending_sni() {
  15772. static thread_local std::string sni;
  15773. return sni;
  15774. }
  15775. // SNI callback for wolfSSL server to capture client's SNI hostname
  15776. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  15777. (void)ret;
  15778. (void)exArg;
  15779. void *name_data = nullptr;
  15780. unsigned short name_len =
  15781. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  15782. if (name_data && name_len > 0) {
  15783. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  15784. name_len);
  15785. } else {
  15786. wolfssl_pending_sni().clear();
  15787. }
  15788. return 0; // Continue regardless
  15789. }
  15790. // wolfSSL verify callback wrapper
  15791. inline int wolfssl_verify_callback(int preverify_ok,
  15792. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  15793. auto &callback = get_verify_callback();
  15794. if (!callback) { return preverify_ok; }
  15795. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  15796. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  15797. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  15798. // Get the WOLFSSL object from the X509_STORE_CTX
  15799. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  15800. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  15801. VerifyContext verify_ctx;
  15802. verify_ctx.session = static_cast<session_t>(ssl);
  15803. verify_ctx.cert = static_cast<cert_t>(cert);
  15804. verify_ctx.depth = depth;
  15805. verify_ctx.preverify_ok = (preverify_ok != 0);
  15806. verify_ctx.error_code = static_cast<long>(err);
  15807. if (err != 0) {
  15808. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  15809. } else {
  15810. verify_ctx.error_string = nullptr;
  15811. }
  15812. bool accepted = callback(verify_ctx);
  15813. return accepted ? 1 : 0;
  15814. }
  15815. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  15816. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  15817. wolfSSL_CTX_set_default_passwd_cb(
  15818. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  15819. auto *pwd = static_cast<const char *>(userdata);
  15820. if (!pwd) return 0;
  15821. auto len = static_cast<int>(strlen(pwd));
  15822. if (len > size) len = size;
  15823. memcpy(buf, pwd, static_cast<size_t>(len));
  15824. return len;
  15825. });
  15826. }
  15827. } // namespace impl
  15828. inline ctx_t create_client_context() {
  15829. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  15830. if (!ctx) { return nullptr; }
  15831. ctx->is_server = false;
  15832. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  15833. if (!method) {
  15834. delete ctx;
  15835. return nullptr;
  15836. }
  15837. ctx->ctx = wolfSSL_CTX_new(method);
  15838. if (!ctx->ctx) {
  15839. delete ctx;
  15840. return nullptr;
  15841. }
  15842. // Default: verify peer certificate
  15843. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  15844. return static_cast<ctx_t>(ctx);
  15845. }
  15846. inline ctx_t create_server_context() {
  15847. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  15848. if (!ctx) { return nullptr; }
  15849. ctx->is_server = true;
  15850. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  15851. if (!method) {
  15852. delete ctx;
  15853. return nullptr;
  15854. }
  15855. ctx->ctx = wolfSSL_CTX_new(method);
  15856. if (!ctx->ctx) {
  15857. delete ctx;
  15858. return nullptr;
  15859. }
  15860. // Default: don't verify client
  15861. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  15862. // Enable SNI on server
  15863. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  15864. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  15865. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  15866. return static_cast<ctx_t>(ctx);
  15867. }
  15868. inline void free_context(ctx_t ctx) {
  15869. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  15870. }
  15871. inline bool set_min_version(ctx_t ctx, Version version) {
  15872. if (!ctx) { return false; }
  15873. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15874. int min_ver = WOLFSSL_TLSV1_2;
  15875. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  15876. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  15877. }
  15878. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15879. if (!ctx || !pem) { return false; }
  15880. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15881. int ret = wolfSSL_CTX_load_verify_buffer(
  15882. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  15883. static_cast<long>(len), SSL_FILETYPE_PEM);
  15884. if (ret != SSL_SUCCESS) {
  15885. impl::wolfssl_last_error() =
  15886. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15887. return false;
  15888. }
  15889. wctx->ca_pem_data_.append(pem, len);
  15890. return true;
  15891. }
  15892. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15893. if (!ctx || !file_path) { return false; }
  15894. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15895. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  15896. if (ret != SSL_SUCCESS) {
  15897. impl::wolfssl_last_error() =
  15898. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15899. return false;
  15900. }
  15901. return true;
  15902. }
  15903. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15904. if (!ctx || !dir_path) { return false; }
  15905. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15906. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  15907. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  15908. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  15909. // immediately. Return true even on failure since the CA file may have
  15910. // already been loaded, matching OpenSSL's lenient behavior.
  15911. (void)ret;
  15912. return true;
  15913. }
  15914. inline bool load_system_certs(ctx_t ctx) {
  15915. if (!ctx) { return false; }
  15916. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15917. bool loaded = false;
  15918. #ifdef _WIN32
  15919. loaded = impl::enumerate_windows_system_certs(
  15920. [&](const unsigned char *data, size_t len) {
  15921. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  15922. static_cast<long>(len),
  15923. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  15924. });
  15925. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15926. loaded = impl::enumerate_macos_keychain_certs(
  15927. [&](const unsigned char *data, size_t len) {
  15928. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  15929. static_cast<long>(len),
  15930. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  15931. });
  15932. #else
  15933. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15934. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  15935. SSL_SUCCESS) {
  15936. loaded = true;
  15937. break;
  15938. }
  15939. }
  15940. if (!loaded) {
  15941. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15942. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  15943. SSL_SUCCESS) {
  15944. loaded = true;
  15945. break;
  15946. }
  15947. }
  15948. }
  15949. #endif
  15950. return loaded;
  15951. }
  15952. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15953. const char *password) {
  15954. if (!ctx || !cert || !key) { return false; }
  15955. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15956. // Load certificate
  15957. int ret = wolfSSL_CTX_use_certificate_buffer(
  15958. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  15959. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  15960. if (ret != SSL_SUCCESS) {
  15961. impl::wolfssl_last_error() =
  15962. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15963. return false;
  15964. }
  15965. // Set password callback if password is provided
  15966. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  15967. // Load private key
  15968. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  15969. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  15970. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  15971. if (ret != SSL_SUCCESS) {
  15972. impl::wolfssl_last_error() =
  15973. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15974. return false;
  15975. }
  15976. // Verify that the certificate and private key match
  15977. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  15978. }
  15979. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15980. const char *key_path, const char *password) {
  15981. if (!ctx || !cert_path || !key_path) { return false; }
  15982. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  15983. // Load certificate file
  15984. int ret =
  15985. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  15986. if (ret != SSL_SUCCESS) {
  15987. impl::wolfssl_last_error() =
  15988. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15989. return false;
  15990. }
  15991. // Set password callback if password is provided
  15992. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  15993. // Load private key file
  15994. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  15995. if (ret != SSL_SUCCESS) {
  15996. impl::wolfssl_last_error() =
  15997. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  15998. return false;
  15999. }
  16000. // Verify that the certificate and private key match
  16001. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16002. }
  16003. inline void set_verify_client(ctx_t ctx, bool require) {
  16004. if (!ctx) { return; }
  16005. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16006. wctx->verify_client = require;
  16007. if (require) {
  16008. wolfSSL_CTX_set_verify(
  16009. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16010. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16011. } else {
  16012. if (wctx->has_verify_callback) {
  16013. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16014. impl::wolfssl_verify_callback);
  16015. } else {
  16016. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16017. }
  16018. }
  16019. }
  16020. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16021. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16022. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16023. auto session = new (std::nothrow) impl::WolfSSLSession();
  16024. if (!session) { return nullptr; }
  16025. session->sock = sock;
  16026. session->ssl = wolfSSL_new(wctx->ctx);
  16027. if (!session->ssl) {
  16028. impl::wolfssl_last_error() =
  16029. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16030. delete session;
  16031. return nullptr;
  16032. }
  16033. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16034. return static_cast<session_t>(session);
  16035. }
  16036. inline void free_session(session_t session) {
  16037. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16038. }
  16039. inline bool set_sni(session_t session, const char *hostname) {
  16040. if (!session || !hostname) { return false; }
  16041. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16042. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16043. static_cast<word16>(strlen(hostname)));
  16044. if (ret != WOLFSSL_SUCCESS) {
  16045. impl::wolfssl_last_error() =
  16046. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16047. return false;
  16048. }
  16049. // Also set hostname for verification
  16050. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16051. wsession->hostname = hostname;
  16052. return true;
  16053. }
  16054. inline bool set_hostname(session_t session, const char *hostname) {
  16055. // In wolfSSL, set_hostname also sets up hostname verification
  16056. return set_sni(session, hostname);
  16057. }
  16058. inline TlsError connect(session_t session) {
  16059. TlsError err;
  16060. if (!session) {
  16061. err.code = ErrorCode::Fatal;
  16062. return err;
  16063. }
  16064. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16065. int ret = wolfSSL_connect(wsession->ssl);
  16066. if (ret == SSL_SUCCESS) {
  16067. err.code = ErrorCode::Success;
  16068. } else {
  16069. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16070. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16071. err.backend_code = static_cast<uint64_t>(ssl_error);
  16072. impl::wolfssl_last_error() = err.backend_code;
  16073. }
  16074. return err;
  16075. }
  16076. inline TlsError accept(session_t session) {
  16077. TlsError err;
  16078. if (!session) {
  16079. err.code = ErrorCode::Fatal;
  16080. return err;
  16081. }
  16082. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16083. int ret = wolfSSL_accept(wsession->ssl);
  16084. if (ret == SSL_SUCCESS) {
  16085. err.code = ErrorCode::Success;
  16086. // Capture SNI from thread-local storage after successful handshake
  16087. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16088. impl::wolfssl_pending_sni().clear();
  16089. } else {
  16090. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16091. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16092. err.backend_code = static_cast<uint64_t>(ssl_error);
  16093. impl::wolfssl_last_error() = err.backend_code;
  16094. }
  16095. return err;
  16096. }
  16097. inline bool connect_nonblocking(session_t session, socket_t sock,
  16098. time_t timeout_sec, time_t timeout_usec,
  16099. TlsError *err) {
  16100. if (!session) {
  16101. if (err) { err->code = ErrorCode::Fatal; }
  16102. return false;
  16103. }
  16104. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16105. // Set socket to non-blocking mode
  16106. detail::set_nonblocking(sock, true);
  16107. auto cleanup =
  16108. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16109. int ret;
  16110. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16111. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16112. if (ssl_error == SSL_ERROR_WANT_READ) {
  16113. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16114. continue;
  16115. }
  16116. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16117. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16118. continue;
  16119. }
  16120. }
  16121. // Error or timeout
  16122. if (err) {
  16123. err->code =
  16124. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16125. err->backend_code = static_cast<uint64_t>(ssl_error);
  16126. }
  16127. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16128. return false;
  16129. }
  16130. if (err) { err->code = ErrorCode::Success; }
  16131. return true;
  16132. }
  16133. inline bool accept_nonblocking(session_t session, socket_t sock,
  16134. time_t timeout_sec, time_t timeout_usec,
  16135. TlsError *err) {
  16136. if (!session) {
  16137. if (err) { err->code = ErrorCode::Fatal; }
  16138. return false;
  16139. }
  16140. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16141. // Set socket to non-blocking mode
  16142. detail::set_nonblocking(sock, true);
  16143. auto cleanup =
  16144. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16145. int ret;
  16146. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16147. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16148. if (ssl_error == SSL_ERROR_WANT_READ) {
  16149. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16150. continue;
  16151. }
  16152. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16153. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16154. continue;
  16155. }
  16156. }
  16157. // Error or timeout
  16158. if (err) {
  16159. err->code =
  16160. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16161. err->backend_code = static_cast<uint64_t>(ssl_error);
  16162. }
  16163. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16164. return false;
  16165. }
  16166. if (err) { err->code = ErrorCode::Success; }
  16167. // Capture SNI from thread-local storage after successful handshake
  16168. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16169. impl::wolfssl_pending_sni().clear();
  16170. return true;
  16171. }
  16172. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16173. if (!session || !buf) {
  16174. err.code = ErrorCode::Fatal;
  16175. return -1;
  16176. }
  16177. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16178. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16179. if (ret > 0) {
  16180. err.code = ErrorCode::Success;
  16181. return static_cast<ssize_t>(ret);
  16182. }
  16183. if (ret == 0) {
  16184. err.code = ErrorCode::PeerClosed;
  16185. return 0;
  16186. }
  16187. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16188. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16189. err.backend_code = static_cast<uint64_t>(ssl_error);
  16190. impl::wolfssl_last_error() = err.backend_code;
  16191. return -1;
  16192. }
  16193. inline ssize_t write(session_t session, const void *buf, size_t len,
  16194. TlsError &err) {
  16195. if (!session || !buf) {
  16196. err.code = ErrorCode::Fatal;
  16197. return -1;
  16198. }
  16199. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16200. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16201. if (ret > 0) {
  16202. err.code = ErrorCode::Success;
  16203. return static_cast<ssize_t>(ret);
  16204. }
  16205. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16206. // Treat this as an error (return -1) so callers don't spin in a
  16207. // write loop adding zero to the offset.
  16208. if (ret == 0) {
  16209. err.code = ErrorCode::PeerClosed;
  16210. return -1;
  16211. }
  16212. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16213. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16214. err.backend_code = static_cast<uint64_t>(ssl_error);
  16215. impl::wolfssl_last_error() = err.backend_code;
  16216. return -1;
  16217. }
  16218. inline int pending(const_session_t session) {
  16219. if (!session) { return 0; }
  16220. auto wsession =
  16221. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16222. return wolfSSL_pending(wsession->ssl);
  16223. }
  16224. inline void shutdown(session_t session, bool graceful) {
  16225. if (!session) { return; }
  16226. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16227. if (graceful) {
  16228. int ret;
  16229. int attempts = 0;
  16230. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16231. attempts < 3) {
  16232. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16233. if (ssl_error != SSL_ERROR_WANT_READ &&
  16234. ssl_error != SSL_ERROR_WANT_WRITE) {
  16235. break;
  16236. }
  16237. attempts++;
  16238. }
  16239. } else {
  16240. wolfSSL_shutdown(wsession->ssl);
  16241. }
  16242. }
  16243. inline bool is_peer_closed(session_t session, socket_t sock) {
  16244. if (!session || sock == INVALID_SOCKET) { return true; }
  16245. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16246. // Check if there's already decrypted data available
  16247. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16248. // Set socket to non-blocking to avoid blocking on read
  16249. detail::set_nonblocking(sock, true);
  16250. auto cleanup =
  16251. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16252. // Peek 1 byte to check connection status without consuming data
  16253. unsigned char buf;
  16254. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16255. // If we got data or WANT_READ (would block), connection is alive
  16256. if (ret > 0) { return false; }
  16257. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16258. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16259. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16260. ret == 0;
  16261. }
  16262. inline cert_t get_peer_cert(const_session_t session) {
  16263. if (!session) { return nullptr; }
  16264. auto wsession =
  16265. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16266. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16267. return static_cast<cert_t>(cert);
  16268. }
  16269. inline void free_cert(cert_t cert) {
  16270. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16271. }
  16272. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16273. if (!cert || !hostname) { return false; }
  16274. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16275. std::string host_str(hostname);
  16276. // Check if hostname is an IP address
  16277. bool is_ip = impl::is_ipv4_address(host_str);
  16278. unsigned char ip_bytes[4];
  16279. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  16280. // Check Subject Alternative Names
  16281. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16282. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16283. if (san_names) {
  16284. int san_count = wolfSSL_sk_num(san_names);
  16285. for (int i = 0; i < san_count; i++) {
  16286. auto *names =
  16287. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16288. if (!names) continue;
  16289. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16290. // DNS name
  16291. unsigned char *dns_name = nullptr;
  16292. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16293. if (dns_name && dns_len > 0) {
  16294. std::string san_name(reinterpret_cast<char *>(dns_name),
  16295. static_cast<size_t>(dns_len));
  16296. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16297. if (detail::match_hostname(san_name, host_str)) {
  16298. wolfSSL_sk_free(san_names);
  16299. return true;
  16300. }
  16301. }
  16302. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16303. // IP address
  16304. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16305. int ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16306. if (ip_data && ip_len == 4 && memcmp(ip_data, ip_bytes, 4) == 0) {
  16307. wolfSSL_sk_free(san_names);
  16308. return true;
  16309. }
  16310. }
  16311. }
  16312. wolfSSL_sk_free(san_names);
  16313. }
  16314. // Fallback: Check Common Name (CN) in subject
  16315. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16316. if (subject) {
  16317. char cn[256] = {};
  16318. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16319. sizeof(cn));
  16320. if (cn_len > 0) {
  16321. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16322. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16323. }
  16324. }
  16325. return false;
  16326. }
  16327. inline uint64_t hostname_mismatch_code() {
  16328. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16329. }
  16330. inline long get_verify_result(const_session_t session) {
  16331. if (!session) { return -1; }
  16332. auto wsession =
  16333. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16334. long result = wolfSSL_get_verify_result(wsession->ssl);
  16335. return result;
  16336. }
  16337. inline std::string get_cert_subject_cn(cert_t cert) {
  16338. if (!cert) return "";
  16339. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16340. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16341. if (!subject) return "";
  16342. char cn[256] = {};
  16343. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16344. sizeof(cn));
  16345. if (cn_len <= 0) return "";
  16346. return std::string(cn, static_cast<size_t>(cn_len));
  16347. }
  16348. inline std::string get_cert_issuer_name(cert_t cert) {
  16349. if (!cert) return "";
  16350. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16351. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16352. if (!issuer) return "";
  16353. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16354. if (!name_str) return "";
  16355. std::string result(name_str);
  16356. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16357. return result;
  16358. }
  16359. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16360. sans.clear();
  16361. if (!cert) return false;
  16362. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16363. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16364. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16365. if (!san_names) return true; // No SANs is not an error
  16366. int count = wolfSSL_sk_num(san_names);
  16367. for (int i = 0; i < count; i++) {
  16368. auto *name =
  16369. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16370. if (!name) continue;
  16371. SanEntry entry;
  16372. switch (name->type) {
  16373. case WOLFSSL_GEN_DNS: {
  16374. entry.type = SanType::DNS;
  16375. unsigned char *dns_name = nullptr;
  16376. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16377. if (dns_name && dns_len > 0) {
  16378. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16379. static_cast<size_t>(dns_len));
  16380. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16381. }
  16382. break;
  16383. }
  16384. case WOLFSSL_GEN_IPADD: {
  16385. entry.type = SanType::IP;
  16386. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16387. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16388. if (ip_data && ip_len == 4) {
  16389. char buf[16];
  16390. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16391. ip_data[2], ip_data[3]);
  16392. entry.value = buf;
  16393. } else if (ip_data && ip_len == 16) {
  16394. char buf[64];
  16395. snprintf(buf, sizeof(buf),
  16396. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16397. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16398. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16399. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16400. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16401. ip_data[14], ip_data[15]);
  16402. entry.value = buf;
  16403. }
  16404. break;
  16405. }
  16406. case WOLFSSL_GEN_EMAIL:
  16407. entry.type = SanType::EMAIL;
  16408. {
  16409. unsigned char *email = nullptr;
  16410. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16411. if (email && email_len > 0) {
  16412. entry.value = std::string(reinterpret_cast<char *>(email),
  16413. static_cast<size_t>(email_len));
  16414. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16415. }
  16416. }
  16417. break;
  16418. case WOLFSSL_GEN_URI:
  16419. entry.type = SanType::URI;
  16420. {
  16421. unsigned char *uri = nullptr;
  16422. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  16423. &uri, name->d.uniformResourceIdentifier);
  16424. if (uri && uri_len > 0) {
  16425. entry.value = std::string(reinterpret_cast<char *>(uri),
  16426. static_cast<size_t>(uri_len));
  16427. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  16428. }
  16429. }
  16430. break;
  16431. default: entry.type = SanType::OTHER; break;
  16432. }
  16433. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16434. }
  16435. wolfSSL_sk_free(san_names);
  16436. return true;
  16437. }
  16438. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16439. time_t &not_after) {
  16440. if (!cert) return false;
  16441. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16442. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  16443. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  16444. if (!nb || !na) return false;
  16445. // wolfSSL_ASN1_TIME_to_tm is available
  16446. struct tm tm_nb = {}, tm_na = {};
  16447. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  16448. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  16449. #ifdef _WIN32
  16450. not_before = _mkgmtime(&tm_nb);
  16451. not_after = _mkgmtime(&tm_na);
  16452. #else
  16453. not_before = timegm(&tm_nb);
  16454. not_after = timegm(&tm_na);
  16455. #endif
  16456. return true;
  16457. }
  16458. inline std::string get_cert_serial(cert_t cert) {
  16459. if (!cert) return "";
  16460. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16461. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  16462. if (!serial_asn1) return "";
  16463. // Get the serial number data
  16464. int len = serial_asn1->length;
  16465. unsigned char *data = serial_asn1->data;
  16466. if (!data || len <= 0) return "";
  16467. std::string result;
  16468. result.reserve(static_cast<size_t>(len) * 2);
  16469. for (int i = 0; i < len; i++) {
  16470. char hex[3];
  16471. snprintf(hex, sizeof(hex), "%02X", data[i]);
  16472. result += hex;
  16473. }
  16474. return result;
  16475. }
  16476. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16477. if (!cert) return false;
  16478. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16479. int der_len = 0;
  16480. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  16481. if (!der_data || der_len <= 0) return false;
  16482. der.assign(der_data, der_data + der_len);
  16483. return true;
  16484. }
  16485. inline const char *get_sni(const_session_t session) {
  16486. if (!session) return nullptr;
  16487. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  16488. // For server: return SNI received from client during handshake
  16489. if (!wsession->sni_hostname.empty()) {
  16490. return wsession->sni_hostname.c_str();
  16491. }
  16492. // For client: return the hostname set via set_sni
  16493. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  16494. return nullptr;
  16495. }
  16496. inline uint64_t peek_error() {
  16497. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16498. }
  16499. inline uint64_t get_error() {
  16500. uint64_t err = impl::wolfssl_last_error();
  16501. impl::wolfssl_last_error() = 0;
  16502. return err;
  16503. }
  16504. inline std::string error_string(uint64_t code) {
  16505. char buf[256];
  16506. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  16507. return std::string(buf);
  16508. }
  16509. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16510. if (!pem || len == 0) { return nullptr; }
  16511. // Validate by attempting to load into a temporary ctx
  16512. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  16513. if (!tmp_ctx) { return nullptr; }
  16514. int ret = wolfSSL_CTX_load_verify_buffer(
  16515. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  16516. static_cast<long>(len), SSL_FILETYPE_PEM);
  16517. wolfSSL_CTX_free(tmp_ctx);
  16518. if (ret != SSL_SUCCESS) { return nullptr; }
  16519. return static_cast<ca_store_t>(
  16520. new impl::WolfSSLCAStore{std::string(pem, len)});
  16521. }
  16522. inline void free_ca_store(ca_store_t store) {
  16523. delete static_cast<impl::WolfSSLCAStore *>(store);
  16524. }
  16525. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16526. if (!ctx || !store) { return false; }
  16527. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16528. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  16529. int ret = wolfSSL_CTX_load_verify_buffer(
  16530. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  16531. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  16532. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  16533. return ret == SSL_SUCCESS;
  16534. }
  16535. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16536. certs.clear();
  16537. if (!ctx) { return 0; }
  16538. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16539. if (wctx->ca_pem_data_.empty()) { return 0; }
  16540. const std::string &pem = wctx->ca_pem_data_;
  16541. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  16542. const std::string end_marker = "-----END CERTIFICATE-----";
  16543. size_t pos = 0;
  16544. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  16545. size_t end_pos = pem.find(end_marker, pos);
  16546. if (end_pos == std::string::npos) { break; }
  16547. end_pos += end_marker.size();
  16548. std::string cert_pem = pem.substr(pos, end_pos - pos);
  16549. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  16550. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  16551. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  16552. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  16553. pos = end_pos;
  16554. }
  16555. return certs.size();
  16556. }
  16557. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16558. std::vector<std::string> names;
  16559. if (!ctx) { return names; }
  16560. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16561. if (wctx->ca_pem_data_.empty()) { return names; }
  16562. const std::string &pem = wctx->ca_pem_data_;
  16563. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  16564. const std::string end_marker = "-----END CERTIFICATE-----";
  16565. size_t pos = 0;
  16566. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  16567. size_t end_pos = pem.find(end_marker, pos);
  16568. if (end_pos == std::string::npos) { break; }
  16569. end_pos += end_marker.size();
  16570. std::string cert_pem = pem.substr(pos, end_pos - pos);
  16571. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  16572. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  16573. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  16574. if (x509) {
  16575. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16576. if (subject) {
  16577. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  16578. if (name_str) {
  16579. names.push_back(name_str);
  16580. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16581. }
  16582. }
  16583. wolfSSL_X509_free(x509);
  16584. }
  16585. pos = end_pos;
  16586. }
  16587. return names;
  16588. }
  16589. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16590. const char *key_pem, const char *password) {
  16591. if (!ctx || !cert_pem || !key_pem) { return false; }
  16592. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16593. // Load new certificate
  16594. int ret = wolfSSL_CTX_use_certificate_buffer(
  16595. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  16596. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  16597. if (ret != SSL_SUCCESS) {
  16598. impl::wolfssl_last_error() =
  16599. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16600. return false;
  16601. }
  16602. // Set password if provided
  16603. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16604. // Load new private key
  16605. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16606. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  16607. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  16608. if (ret != SSL_SUCCESS) {
  16609. impl::wolfssl_last_error() =
  16610. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16611. return false;
  16612. }
  16613. return true;
  16614. }
  16615. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16616. if (!ctx || !ca_pem) { return false; }
  16617. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16618. int ret = wolfSSL_CTX_load_verify_buffer(
  16619. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  16620. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  16621. if (ret != SSL_SUCCESS) {
  16622. impl::wolfssl_last_error() =
  16623. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16624. return false;
  16625. }
  16626. return true;
  16627. }
  16628. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16629. if (!ctx) { return false; }
  16630. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16631. impl::get_verify_callback() = std::move(callback);
  16632. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  16633. if (wctx->has_verify_callback) {
  16634. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16635. impl::wolfssl_verify_callback);
  16636. } else {
  16637. wolfSSL_CTX_set_verify(
  16638. wctx->ctx,
  16639. wctx->verify_client
  16640. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  16641. : SSL_VERIFY_NONE,
  16642. nullptr);
  16643. }
  16644. return true;
  16645. }
  16646. inline long get_verify_error(const_session_t session) {
  16647. if (!session) { return -1; }
  16648. auto *wsession =
  16649. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16650. return wolfSSL_get_verify_result(wsession->ssl);
  16651. }
  16652. inline std::string verify_error_string(long error_code) {
  16653. if (error_code == 0) { return ""; }
  16654. const char *str =
  16655. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  16656. return str ? std::string(str) : std::string();
  16657. }
  16658. } // namespace tls
  16659. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  16660. // WebSocket implementation
  16661. namespace ws {
  16662. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  16663. bool fin) {
  16664. std::lock_guard<std::mutex> lock(write_mutex_);
  16665. if (closed_) { return false; }
  16666. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  16667. }
  16668. inline ReadResult WebSocket::read(std::string &msg) {
  16669. while (!closed_) {
  16670. Opcode opcode;
  16671. std::string payload;
  16672. bool fin;
  16673. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  16674. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  16675. closed_ = true;
  16676. return Fail;
  16677. }
  16678. switch (opcode) {
  16679. case Opcode::Ping: {
  16680. std::lock_guard<std::mutex> lock(write_mutex_);
  16681. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  16682. payload.size(), true, !is_server_);
  16683. continue;
  16684. }
  16685. case Opcode::Pong: {
  16686. std::lock_guard<std::mutex> lock(ping_mutex_);
  16687. unacked_pings_ = 0;
  16688. continue;
  16689. }
  16690. case Opcode::Close: {
  16691. if (!closed_.exchange(true)) {
  16692. // Echo close frame back
  16693. std::lock_guard<std::mutex> lock(write_mutex_);
  16694. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  16695. payload.size(), true, !is_server_);
  16696. }
  16697. return Fail;
  16698. }
  16699. case Opcode::Text:
  16700. case Opcode::Binary: {
  16701. auto result = opcode == Opcode::Text ? Text : Binary;
  16702. msg = std::move(payload);
  16703. // Handle fragmentation
  16704. if (!fin) {
  16705. while (true) {
  16706. Opcode cont_opcode;
  16707. std::string cont_payload;
  16708. bool cont_fin;
  16709. if (!impl::read_websocket_frame(
  16710. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  16711. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  16712. closed_ = true;
  16713. return Fail;
  16714. }
  16715. if (cont_opcode == Opcode::Ping) {
  16716. std::lock_guard<std::mutex> lock(write_mutex_);
  16717. detail::write_websocket_frame(
  16718. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  16719. true, !is_server_);
  16720. continue;
  16721. }
  16722. if (cont_opcode == Opcode::Pong) {
  16723. std::lock_guard<std::mutex> lock(ping_mutex_);
  16724. unacked_pings_ = 0;
  16725. continue;
  16726. }
  16727. if (cont_opcode == Opcode::Close) {
  16728. if (!closed_.exchange(true)) {
  16729. std::lock_guard<std::mutex> lock(write_mutex_);
  16730. detail::write_websocket_frame(
  16731. strm_, Opcode::Close, cont_payload.data(),
  16732. cont_payload.size(), true, !is_server_);
  16733. }
  16734. return Fail;
  16735. }
  16736. // RFC 6455: continuation frames must use opcode 0x0
  16737. if (cont_opcode != Opcode::Continuation) {
  16738. closed_ = true;
  16739. return Fail;
  16740. }
  16741. msg += cont_payload;
  16742. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  16743. closed_ = true;
  16744. return Fail;
  16745. }
  16746. if (cont_fin) { break; }
  16747. }
  16748. }
  16749. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  16750. if (result == Text && !impl::is_valid_utf8(msg)) {
  16751. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  16752. return Fail;
  16753. }
  16754. return result;
  16755. }
  16756. default: closed_ = true; return Fail;
  16757. }
  16758. }
  16759. return Fail;
  16760. }
  16761. inline bool WebSocket::send(const std::string &data) {
  16762. return send_frame(Opcode::Text, data.data(), data.size());
  16763. }
  16764. inline bool WebSocket::send(const char *data, size_t len) {
  16765. return send_frame(Opcode::Binary, data, len);
  16766. }
  16767. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  16768. if (closed_.exchange(true)) { return; }
  16769. ping_cv_.notify_all();
  16770. std::string payload;
  16771. auto code = static_cast<uint16_t>(status);
  16772. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  16773. payload.push_back(static_cast<char>(code & 0xFF));
  16774. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  16775. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  16776. payload += reason.substr(0, 123);
  16777. {
  16778. std::lock_guard<std::mutex> lock(write_mutex_);
  16779. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  16780. payload.size(), true, !is_server_);
  16781. }
  16782. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  16783. // Close response before closing the TCP connection. Use a short timeout to
  16784. // avoid hanging if the peer doesn't respond.
  16785. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  16786. Opcode op;
  16787. std::string resp;
  16788. bool fin;
  16789. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  16790. if (op == Opcode::Close) { break; }
  16791. }
  16792. }
  16793. inline WebSocket::~WebSocket() {
  16794. {
  16795. std::lock_guard<std::mutex> lock(ping_mutex_);
  16796. closed_ = true;
  16797. }
  16798. ping_cv_.notify_all();
  16799. if (ping_thread_.joinable()) { ping_thread_.join(); }
  16800. }
  16801. inline void WebSocket::start_heartbeat() {
  16802. if (ping_interval_sec_ == 0) { return; }
  16803. ping_thread_ = std::thread([this]() {
  16804. std::unique_lock<std::mutex> lock(ping_mutex_);
  16805. while (!closed_) {
  16806. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  16807. if (closed_) { break; }
  16808. // If the peer has failed to respond to the previous pings, give up.
  16809. // RFC 6455 does not define a pong-timeout mechanism; this is an
  16810. // opt-in liveness check controlled by max_missed_pongs_.
  16811. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  16812. lock.unlock();
  16813. close(CloseStatus::GoingAway, "pong timeout");
  16814. return;
  16815. }
  16816. lock.unlock();
  16817. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  16818. lock.lock();
  16819. closed_ = true;
  16820. break;
  16821. }
  16822. lock.lock();
  16823. unacked_pings_++;
  16824. }
  16825. });
  16826. }
  16827. inline const Request &WebSocket::request() const { return req_; }
  16828. inline bool WebSocket::is_open() const { return !closed_; }
  16829. // WebSocketClient implementation
  16830. inline WebSocketClient::WebSocketClient(
  16831. const std::string &scheme_host_port_path, const Headers &headers)
  16832. : headers_(headers) {
  16833. detail::UrlComponents uc;
  16834. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  16835. !uc.host.empty() && !uc.path.empty()) {
  16836. auto &scheme = uc.scheme;
  16837. #ifdef CPPHTTPLIB_SSL_ENABLED
  16838. if (scheme != "ws" && scheme != "wss") {
  16839. #else
  16840. if (scheme != "ws") {
  16841. #endif
  16842. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  16843. std::string msg = "'" + scheme + "' scheme is not supported.";
  16844. throw std::invalid_argument(msg);
  16845. #endif
  16846. return;
  16847. }
  16848. auto is_ssl = scheme == "wss";
  16849. host_ = std::move(uc.host);
  16850. port_ = is_ssl ? 443 : 80;
  16851. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  16852. path_ = std::move(uc.path);
  16853. #ifdef CPPHTTPLIB_SSL_ENABLED
  16854. is_ssl_ = is_ssl;
  16855. #else
  16856. if (is_ssl) { return; }
  16857. #endif
  16858. is_valid_ = true;
  16859. }
  16860. }
  16861. inline WebSocketClient::~WebSocketClient() { shutdown_and_close(); }
  16862. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  16863. inline void WebSocketClient::shutdown_and_close() {
  16864. #ifdef CPPHTTPLIB_SSL_ENABLED
  16865. if (is_ssl_) {
  16866. if (tls_session_) {
  16867. tls::shutdown(tls_session_, true);
  16868. tls::free_session(tls_session_);
  16869. tls_session_ = nullptr;
  16870. }
  16871. if (tls_ctx_) {
  16872. tls::free_context(tls_ctx_);
  16873. tls_ctx_ = nullptr;
  16874. }
  16875. }
  16876. #endif
  16877. if (ws_ && ws_->is_open()) { ws_->close(); }
  16878. ws_.reset();
  16879. if (sock_ != INVALID_SOCKET) {
  16880. detail::shutdown_socket(sock_);
  16881. detail::close_socket(sock_);
  16882. sock_ = INVALID_SOCKET;
  16883. }
  16884. }
  16885. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  16886. #ifdef CPPHTTPLIB_SSL_ENABLED
  16887. if (is_ssl_) {
  16888. if (!detail::setup_client_tls_session(
  16889. host_, tls_ctx_, tls_session_, sock_,
  16890. server_certificate_verification_, ca_cert_file_path_,
  16891. ca_cert_store_, read_timeout_sec_, read_timeout_usec_)) {
  16892. return false;
  16893. }
  16894. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  16895. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  16896. write_timeout_sec_, write_timeout_usec_));
  16897. return true;
  16898. }
  16899. #endif
  16900. strm = std::unique_ptr<Stream>(
  16901. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  16902. write_timeout_sec_, write_timeout_usec_));
  16903. return true;
  16904. }
  16905. inline bool WebSocketClient::connect() {
  16906. if (!is_valid_) { return false; }
  16907. shutdown_and_close();
  16908. Error error;
  16909. sock_ = detail::create_client_socket(
  16910. host_, std::string(), port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  16911. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  16912. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  16913. write_timeout_usec_, interface_, error);
  16914. if (sock_ == INVALID_SOCKET) { return false; }
  16915. std::unique_ptr<Stream> strm;
  16916. if (!create_stream(strm)) {
  16917. shutdown_and_close();
  16918. return false;
  16919. }
  16920. std::string selected_subprotocol;
  16921. if (!detail::perform_websocket_handshake(*strm, host_, port_, path_, headers_,
  16922. selected_subprotocol)) {
  16923. shutdown_and_close();
  16924. return false;
  16925. }
  16926. subprotocol_ = std::move(selected_subprotocol);
  16927. Request req;
  16928. req.method = "GET";
  16929. req.path = path_;
  16930. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  16931. websocket_ping_interval_sec_,
  16932. websocket_max_missed_pongs_));
  16933. return true;
  16934. }
  16935. inline ReadResult WebSocketClient::read(std::string &msg) {
  16936. if (!ws_) { return Fail; }
  16937. return ws_->read(msg);
  16938. }
  16939. inline bool WebSocketClient::send(const std::string &data) {
  16940. if (!ws_) { return false; }
  16941. return ws_->send(data);
  16942. }
  16943. inline bool WebSocketClient::send(const char *data, size_t len) {
  16944. if (!ws_) { return false; }
  16945. return ws_->send(data, len);
  16946. }
  16947. inline void WebSocketClient::close(CloseStatus status,
  16948. const std::string &reason) {
  16949. if (ws_) { ws_->close(status, reason); }
  16950. }
  16951. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  16952. inline const std::string &WebSocketClient::subprotocol() const {
  16953. return subprotocol_;
  16954. }
  16955. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  16956. read_timeout_sec_ = sec;
  16957. read_timeout_usec_ = usec;
  16958. }
  16959. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  16960. write_timeout_sec_ = sec;
  16961. write_timeout_usec_ = usec;
  16962. }
  16963. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  16964. websocket_ping_interval_sec_ = sec;
  16965. }
  16966. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  16967. websocket_max_missed_pongs_ = count;
  16968. }
  16969. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  16970. inline void WebSocketClient::set_address_family(int family) {
  16971. address_family_ = family;
  16972. }
  16973. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  16974. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  16975. socket_options_ = std::move(socket_options);
  16976. }
  16977. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  16978. connection_timeout_sec_ = sec;
  16979. connection_timeout_usec_ = usec;
  16980. }
  16981. inline void WebSocketClient::set_interface(const std::string &intf) {
  16982. interface_ = intf;
  16983. }
  16984. #ifdef CPPHTTPLIB_SSL_ENABLED
  16985. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  16986. ca_cert_file_path_ = path;
  16987. }
  16988. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  16989. ca_cert_store_ = store;
  16990. }
  16991. inline void
  16992. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  16993. server_certificate_verification_ = enabled;
  16994. }
  16995. #endif // CPPHTTPLIB_SSL_ENABLED
  16996. } // namespace ws
  16997. // ----------------------------------------------------------------------------
  16998. } // namespace httplib
  16999. #endif // CPPHTTPLIB_HTTPLIB_H