httplib.h 572 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258
  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.30.1"
  10. #define CPPHTTPLIB_VERSION_NUM "0x001E01"
  11. /*
  12. * Platform compatibility check
  13. */
  14. #if defined(_WIN32) && !defined(_WIN64)
  15. #if defined(_MSC_VER)
  16. #pragma message( \
  17. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler.")
  18. #else
  19. #warning \
  20. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler."
  21. #endif
  22. #elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ < 8
  23. #warning \
  24. "cpp-httplib doesn't support 32-bit platforms. Please use a 64-bit compiler."
  25. #elif defined(__SIZEOF_SIZE_T__) && __SIZEOF_SIZE_T__ < 8
  26. #warning \
  27. "cpp-httplib doesn't support platforms where size_t is less than 64 bits."
  28. #endif
  29. #ifdef _WIN32
  30. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  31. #error \
  32. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  33. #endif
  34. #endif
  35. /*
  36. * Configuration
  37. */
  38. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  39. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  40. #endif
  41. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  42. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  43. #endif
  44. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  45. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  46. #endif
  47. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  60. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  61. #endif
  62. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  63. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  64. #endif
  65. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  66. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  67. #endif
  68. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  69. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  70. #endif
  71. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  72. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  73. #endif
  74. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  75. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  78. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  79. #endif
  80. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  81. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  82. #endif
  83. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  84. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  85. #endif
  86. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  87. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  88. #endif
  89. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  90. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  91. #endif
  92. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  93. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  94. #endif
  95. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  96. #ifdef _WIN32
  97. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  98. #else
  99. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  100. #endif
  101. #endif
  102. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  103. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  106. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  107. #endif
  108. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  109. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  110. #endif
  111. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  112. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  113. #endif
  114. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  115. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  116. #endif
  117. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  118. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  119. #endif
  120. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  121. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  122. #endif
  123. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  124. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  125. #endif
  126. #ifndef CPPHTTPLIB_TCP_NODELAY
  127. #define CPPHTTPLIB_TCP_NODELAY false
  128. #endif
  129. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  130. #define CPPHTTPLIB_IPV6_V6ONLY false
  131. #endif
  132. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  133. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  134. #endif
  135. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  136. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  137. #endif
  138. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  139. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  140. #endif
  141. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  142. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  143. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  144. ? std::thread::hardware_concurrency() - 1 \
  145. : 0))
  146. #endif
  147. #ifndef CPPHTTPLIB_RECV_FLAGS
  148. #define CPPHTTPLIB_RECV_FLAGS 0
  149. #endif
  150. #ifndef CPPHTTPLIB_SEND_FLAGS
  151. #define CPPHTTPLIB_SEND_FLAGS 0
  152. #endif
  153. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  154. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  155. #endif
  156. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  157. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  158. #endif
  159. /*
  160. * Headers
  161. */
  162. #ifdef _WIN32
  163. #ifndef _CRT_SECURE_NO_WARNINGS
  164. #define _CRT_SECURE_NO_WARNINGS
  165. #endif //_CRT_SECURE_NO_WARNINGS
  166. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  167. #define _CRT_NONSTDC_NO_DEPRECATE
  168. #endif //_CRT_NONSTDC_NO_DEPRECATE
  169. #if defined(_MSC_VER)
  170. #if _MSC_VER < 1900
  171. #error Sorry, Visual Studio versions prior to 2015 are not supported
  172. #endif
  173. #pragma comment(lib, "ws2_32.lib")
  174. #ifndef _SSIZE_T_DEFINED
  175. using ssize_t = __int64;
  176. #define _SSIZE_T_DEFINED
  177. #endif
  178. #endif // _MSC_VER
  179. #ifndef S_ISREG
  180. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  181. #endif // S_ISREG
  182. #ifndef S_ISDIR
  183. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  184. #endif // S_ISDIR
  185. #ifndef NOMINMAX
  186. #define NOMINMAX
  187. #endif // NOMINMAX
  188. #include <io.h>
  189. #include <winsock2.h>
  190. #include <ws2tcpip.h>
  191. #if defined(__has_include)
  192. #if __has_include(<afunix.h>)
  193. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  194. #include <afunix.h>
  195. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  196. #endif
  197. #endif
  198. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  199. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  200. #endif
  201. using nfds_t = unsigned long;
  202. using socket_t = SOCKET;
  203. using socklen_t = int;
  204. #else // not _WIN32
  205. #include <arpa/inet.h>
  206. #if !defined(_AIX) && !defined(__MVS__)
  207. #include <ifaddrs.h>
  208. #endif
  209. #ifdef __MVS__
  210. #include <strings.h>
  211. #ifndef NI_MAXHOST
  212. #define NI_MAXHOST 1025
  213. #endif
  214. #endif
  215. #include <net/if.h>
  216. #include <netdb.h>
  217. #include <netinet/in.h>
  218. #ifdef __linux__
  219. #include <resolv.h>
  220. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  221. #endif
  222. #include <csignal>
  223. #include <netinet/tcp.h>
  224. #include <poll.h>
  225. #include <pthread.h>
  226. #include <sys/mman.h>
  227. #include <sys/socket.h>
  228. #include <sys/un.h>
  229. #include <unistd.h>
  230. using socket_t = int;
  231. #ifndef INVALID_SOCKET
  232. #define INVALID_SOCKET (-1)
  233. #endif
  234. #endif //_WIN32
  235. #if defined(__APPLE__)
  236. #include <TargetConditionals.h>
  237. #endif
  238. #include <algorithm>
  239. #include <array>
  240. #include <atomic>
  241. #include <cassert>
  242. #include <cctype>
  243. #include <chrono>
  244. #include <climits>
  245. #include <condition_variable>
  246. #include <cstring>
  247. #include <errno.h>
  248. #include <exception>
  249. #include <fcntl.h>
  250. #include <functional>
  251. #include <iomanip>
  252. #include <iostream>
  253. #include <list>
  254. #include <map>
  255. #include <memory>
  256. #include <mutex>
  257. #include <random>
  258. #include <regex>
  259. #include <set>
  260. #include <sstream>
  261. #include <string>
  262. #include <sys/stat.h>
  263. #include <thread>
  264. #include <unordered_map>
  265. #include <unordered_set>
  266. #include <utility>
  267. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  268. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  269. #if TARGET_OS_MAC
  270. #include <CFNetwork/CFHost.h>
  271. #include <CoreFoundation/CoreFoundation.h>
  272. #endif
  273. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO or
  274. // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  275. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  276. #ifdef _WIN32
  277. #include <wincrypt.h>
  278. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  279. // used
  280. #undef X509_NAME
  281. #undef X509_CERT_PAIR
  282. #undef X509_EXTENSIONS
  283. #undef PKCS7_SIGNER_INFO
  284. #ifdef _MSC_VER
  285. #pragma comment(lib, "crypt32.lib")
  286. #endif
  287. #endif // _WIN32
  288. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  289. #if TARGET_OS_MAC
  290. #include <Security/Security.h>
  291. #endif
  292. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  293. #include <openssl/err.h>
  294. #include <openssl/evp.h>
  295. #include <openssl/ssl.h>
  296. #include <openssl/x509v3.h>
  297. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  298. #include <openssl/applink.c>
  299. #endif
  300. #include <iostream>
  301. #include <sstream>
  302. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  303. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  304. #error Please use OpenSSL or a current version of BoringSSL
  305. #endif
  306. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  307. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  308. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  309. #endif
  310. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  311. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  312. #include <mbedtls/ctr_drbg.h>
  313. #include <mbedtls/entropy.h>
  314. #include <mbedtls/error.h>
  315. #include <mbedtls/md5.h>
  316. #include <mbedtls/net_sockets.h>
  317. #include <mbedtls/oid.h>
  318. #include <mbedtls/pk.h>
  319. #include <mbedtls/sha1.h>
  320. #include <mbedtls/sha256.h>
  321. #include <mbedtls/sha512.h>
  322. #include <mbedtls/ssl.h>
  323. #include <mbedtls/x509_crt.h>
  324. #ifdef _WIN32
  325. #include <wincrypt.h>
  326. #ifdef _MSC_VER
  327. #pragma comment(lib, "crypt32.lib")
  328. #endif
  329. #endif // _WIN32
  330. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  331. #if TARGET_OS_MAC
  332. #include <Security/Security.h>
  333. #endif
  334. #endif // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  335. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  336. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  337. // This simplifies conditional compilation when adding new backends (e.g.,
  338. // wolfSSL)
  339. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  340. #define CPPHTTPLIB_SSL_ENABLED
  341. #endif
  342. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  343. #include <zlib.h>
  344. #endif
  345. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  346. #include <brotli/decode.h>
  347. #include <brotli/encode.h>
  348. #endif
  349. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  350. #include <zstd.h>
  351. #endif
  352. /*
  353. * Declaration
  354. */
  355. namespace httplib {
  356. namespace detail {
  357. /*
  358. * Backport std::make_unique from C++14.
  359. *
  360. * NOTE: This code came up with the following stackoverflow post:
  361. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  362. *
  363. */
  364. template <class T, class... Args>
  365. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  366. make_unique(Args &&...args) {
  367. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  368. }
  369. template <class T>
  370. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  371. make_unique(std::size_t n) {
  372. typedef typename std::remove_extent<T>::type RT;
  373. return std::unique_ptr<T>(new RT[n]);
  374. }
  375. namespace case_ignore {
  376. inline unsigned char to_lower(int c) {
  377. const static unsigned char table[256] = {
  378. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  379. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  380. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  381. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  382. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  383. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  384. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  385. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  386. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  387. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  388. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  389. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  390. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  391. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  392. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  393. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  394. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  395. 255,
  396. };
  397. return table[(unsigned char)(char)c];
  398. }
  399. inline bool equal(const std::string &a, const std::string &b) {
  400. return a.size() == b.size() &&
  401. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  402. return to_lower(ca) == to_lower(cb);
  403. });
  404. }
  405. struct equal_to {
  406. bool operator()(const std::string &a, const std::string &b) const {
  407. return equal(a, b);
  408. }
  409. };
  410. struct hash {
  411. size_t operator()(const std::string &key) const {
  412. return hash_core(key.data(), key.size(), 0);
  413. }
  414. size_t hash_core(const char *s, size_t l, size_t h) const {
  415. return (l == 0) ? h
  416. : hash_core(s + 1, l - 1,
  417. // Unsets the 6 high bits of h, therefore no
  418. // overflow happens
  419. (((std::numeric_limits<size_t>::max)() >> 6) &
  420. h * 33) ^
  421. static_cast<unsigned char>(to_lower(*s)));
  422. }
  423. };
  424. template <typename T>
  425. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  426. detail::case_ignore::equal_to>;
  427. } // namespace case_ignore
  428. // This is based on
  429. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  430. struct scope_exit {
  431. explicit scope_exit(std::function<void(void)> &&f)
  432. : exit_function(std::move(f)), execute_on_destruction{true} {}
  433. scope_exit(scope_exit &&rhs) noexcept
  434. : exit_function(std::move(rhs.exit_function)),
  435. execute_on_destruction{rhs.execute_on_destruction} {
  436. rhs.release();
  437. }
  438. ~scope_exit() {
  439. if (execute_on_destruction) { this->exit_function(); }
  440. }
  441. void release() { this->execute_on_destruction = false; }
  442. private:
  443. scope_exit(const scope_exit &) = delete;
  444. void operator=(const scope_exit &) = delete;
  445. scope_exit &operator=(scope_exit &&) = delete;
  446. std::function<void(void)> exit_function;
  447. bool execute_on_destruction;
  448. };
  449. } // namespace detail
  450. enum SSLVerifierResponse {
  451. // no decision has been made, use the built-in certificate verifier
  452. NoDecisionMade,
  453. // connection certificate is verified and accepted
  454. CertificateAccepted,
  455. // connection certificate was processed but is rejected
  456. CertificateRejected
  457. };
  458. enum StatusCode {
  459. // Information responses
  460. Continue_100 = 100,
  461. SwitchingProtocol_101 = 101,
  462. Processing_102 = 102,
  463. EarlyHints_103 = 103,
  464. // Successful responses
  465. OK_200 = 200,
  466. Created_201 = 201,
  467. Accepted_202 = 202,
  468. NonAuthoritativeInformation_203 = 203,
  469. NoContent_204 = 204,
  470. ResetContent_205 = 205,
  471. PartialContent_206 = 206,
  472. MultiStatus_207 = 207,
  473. AlreadyReported_208 = 208,
  474. IMUsed_226 = 226,
  475. // Redirection messages
  476. MultipleChoices_300 = 300,
  477. MovedPermanently_301 = 301,
  478. Found_302 = 302,
  479. SeeOther_303 = 303,
  480. NotModified_304 = 304,
  481. UseProxy_305 = 305,
  482. unused_306 = 306,
  483. TemporaryRedirect_307 = 307,
  484. PermanentRedirect_308 = 308,
  485. // Client error responses
  486. BadRequest_400 = 400,
  487. Unauthorized_401 = 401,
  488. PaymentRequired_402 = 402,
  489. Forbidden_403 = 403,
  490. NotFound_404 = 404,
  491. MethodNotAllowed_405 = 405,
  492. NotAcceptable_406 = 406,
  493. ProxyAuthenticationRequired_407 = 407,
  494. RequestTimeout_408 = 408,
  495. Conflict_409 = 409,
  496. Gone_410 = 410,
  497. LengthRequired_411 = 411,
  498. PreconditionFailed_412 = 412,
  499. PayloadTooLarge_413 = 413,
  500. UriTooLong_414 = 414,
  501. UnsupportedMediaType_415 = 415,
  502. RangeNotSatisfiable_416 = 416,
  503. ExpectationFailed_417 = 417,
  504. ImATeapot_418 = 418,
  505. MisdirectedRequest_421 = 421,
  506. UnprocessableContent_422 = 422,
  507. Locked_423 = 423,
  508. FailedDependency_424 = 424,
  509. TooEarly_425 = 425,
  510. UpgradeRequired_426 = 426,
  511. PreconditionRequired_428 = 428,
  512. TooManyRequests_429 = 429,
  513. RequestHeaderFieldsTooLarge_431 = 431,
  514. UnavailableForLegalReasons_451 = 451,
  515. // Server error responses
  516. InternalServerError_500 = 500,
  517. NotImplemented_501 = 501,
  518. BadGateway_502 = 502,
  519. ServiceUnavailable_503 = 503,
  520. GatewayTimeout_504 = 504,
  521. HttpVersionNotSupported_505 = 505,
  522. VariantAlsoNegotiates_506 = 506,
  523. InsufficientStorage_507 = 507,
  524. LoopDetected_508 = 508,
  525. NotExtended_510 = 510,
  526. NetworkAuthenticationRequired_511 = 511,
  527. };
  528. using Headers =
  529. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  530. detail::case_ignore::equal_to>;
  531. using Params = std::multimap<std::string, std::string>;
  532. using Match = std::smatch;
  533. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  534. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  535. struct Response;
  536. using ResponseHandler = std::function<bool(const Response &response)>;
  537. struct FormData {
  538. std::string name;
  539. std::string content;
  540. std::string filename;
  541. std::string content_type;
  542. Headers headers;
  543. };
  544. struct FormField {
  545. std::string name;
  546. std::string content;
  547. Headers headers;
  548. };
  549. using FormFields = std::multimap<std::string, FormField>;
  550. using FormFiles = std::multimap<std::string, FormData>;
  551. struct MultipartFormData {
  552. FormFields fields; // Text fields from multipart
  553. FormFiles files; // Files from multipart
  554. // Text field access
  555. std::string get_field(const std::string &key, size_t id = 0) const;
  556. std::vector<std::string> get_fields(const std::string &key) const;
  557. bool has_field(const std::string &key) const;
  558. size_t get_field_count(const std::string &key) const;
  559. // File access
  560. FormData get_file(const std::string &key, size_t id = 0) const;
  561. std::vector<FormData> get_files(const std::string &key) const;
  562. bool has_file(const std::string &key) const;
  563. size_t get_file_count(const std::string &key) const;
  564. };
  565. struct UploadFormData {
  566. std::string name;
  567. std::string content;
  568. std::string filename;
  569. std::string content_type;
  570. };
  571. using UploadFormDataItems = std::vector<UploadFormData>;
  572. class DataSink {
  573. public:
  574. DataSink() : os(&sb_), sb_(*this) {}
  575. DataSink(const DataSink &) = delete;
  576. DataSink &operator=(const DataSink &) = delete;
  577. DataSink(DataSink &&) = delete;
  578. DataSink &operator=(DataSink &&) = delete;
  579. std::function<bool(const char *data, size_t data_len)> write;
  580. std::function<bool()> is_writable;
  581. std::function<void()> done;
  582. std::function<void(const Headers &trailer)> done_with_trailer;
  583. std::ostream os;
  584. private:
  585. class data_sink_streambuf final : public std::streambuf {
  586. public:
  587. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  588. protected:
  589. std::streamsize xsputn(const char *s, std::streamsize n) override {
  590. sink_.write(s, static_cast<size_t>(n));
  591. return n;
  592. }
  593. private:
  594. DataSink &sink_;
  595. };
  596. data_sink_streambuf sb_;
  597. };
  598. using ContentProvider =
  599. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  600. using ContentProviderWithoutLength =
  601. std::function<bool(size_t offset, DataSink &sink)>;
  602. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  603. struct FormDataProvider {
  604. std::string name;
  605. ContentProviderWithoutLength provider;
  606. std::string filename;
  607. std::string content_type;
  608. };
  609. using FormDataProviderItems = std::vector<FormDataProvider>;
  610. using ContentReceiverWithProgress = std::function<bool(
  611. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  612. using ContentReceiver =
  613. std::function<bool(const char *data, size_t data_length)>;
  614. using FormDataHeader = std::function<bool(const FormData &file)>;
  615. class ContentReader {
  616. public:
  617. using Reader = std::function<bool(ContentReceiver receiver)>;
  618. using FormDataReader =
  619. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  620. ContentReader(Reader reader, FormDataReader multipart_reader)
  621. : reader_(std::move(reader)),
  622. formdata_reader_(std::move(multipart_reader)) {}
  623. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  624. return formdata_reader_(std::move(header), std::move(receiver));
  625. }
  626. bool operator()(ContentReceiver receiver) const {
  627. return reader_(std::move(receiver));
  628. }
  629. Reader reader_;
  630. FormDataReader formdata_reader_;
  631. };
  632. using Range = std::pair<ssize_t, ssize_t>;
  633. using Ranges = std::vector<Range>;
  634. struct Request {
  635. std::string method;
  636. std::string path;
  637. std::string matched_route;
  638. Params params;
  639. Headers headers;
  640. Headers trailers;
  641. std::string body;
  642. std::string remote_addr;
  643. int remote_port = -1;
  644. std::string local_addr;
  645. int local_port = -1;
  646. // for server
  647. std::string version;
  648. std::string target;
  649. MultipartFormData form;
  650. Ranges ranges;
  651. Match matches;
  652. std::unordered_map<std::string, std::string> path_params;
  653. std::function<bool()> is_connection_closed = []() { return true; };
  654. // for client
  655. std::vector<std::string> accept_content_types;
  656. ResponseHandler response_handler;
  657. ContentReceiverWithProgress content_receiver;
  658. DownloadProgress download_progress;
  659. UploadProgress upload_progress;
  660. #ifdef CPPHTTPLIB_SSL_ENABLED
  661. const void *ssl = nullptr; // tls_session_t (void*) - TLS session handle
  662. #endif
  663. bool has_header(const std::string &key) const;
  664. std::string get_header_value(const std::string &key, const char *def = "",
  665. size_t id = 0) const;
  666. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  667. size_t id = 0) const;
  668. size_t get_header_value_count(const std::string &key) const;
  669. void set_header(const std::string &key, const std::string &val);
  670. bool has_trailer(const std::string &key) const;
  671. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  672. size_t get_trailer_value_count(const std::string &key) const;
  673. bool has_param(const std::string &key) const;
  674. std::string get_param_value(const std::string &key, size_t id = 0) const;
  675. size_t get_param_value_count(const std::string &key) const;
  676. bool is_multipart_form_data() const;
  677. // private members...
  678. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  679. size_t content_length_ = 0;
  680. ContentProvider content_provider_;
  681. bool is_chunked_content_provider_ = false;
  682. size_t authorization_count_ = 0;
  683. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  684. (std::chrono::steady_clock::time_point::min)();
  685. };
  686. struct Response {
  687. std::string version;
  688. int status = -1;
  689. std::string reason;
  690. Headers headers;
  691. Headers trailers;
  692. std::string body;
  693. std::string location; // Redirect location
  694. bool has_header(const std::string &key) const;
  695. std::string get_header_value(const std::string &key, const char *def = "",
  696. size_t id = 0) const;
  697. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  698. size_t id = 0) const;
  699. size_t get_header_value_count(const std::string &key) const;
  700. void set_header(const std::string &key, const std::string &val);
  701. bool has_trailer(const std::string &key) const;
  702. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  703. size_t get_trailer_value_count(const std::string &key) const;
  704. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  705. void set_content(const char *s, size_t n, const std::string &content_type);
  706. void set_content(const std::string &s, const std::string &content_type);
  707. void set_content(std::string &&s, const std::string &content_type);
  708. void set_content_provider(
  709. size_t length, const std::string &content_type, ContentProvider provider,
  710. ContentProviderResourceReleaser resource_releaser = nullptr);
  711. void set_content_provider(
  712. const std::string &content_type, ContentProviderWithoutLength provider,
  713. ContentProviderResourceReleaser resource_releaser = nullptr);
  714. void set_chunked_content_provider(
  715. const std::string &content_type, ContentProviderWithoutLength provider,
  716. ContentProviderResourceReleaser resource_releaser = nullptr);
  717. void set_file_content(const std::string &path,
  718. const std::string &content_type);
  719. void set_file_content(const std::string &path);
  720. Response() = default;
  721. Response(const Response &) = default;
  722. Response &operator=(const Response &) = default;
  723. Response(Response &&) = default;
  724. Response &operator=(Response &&) = default;
  725. ~Response() {
  726. if (content_provider_resource_releaser_) {
  727. content_provider_resource_releaser_(content_provider_success_);
  728. }
  729. }
  730. // private members...
  731. size_t content_length_ = 0;
  732. ContentProvider content_provider_;
  733. ContentProviderResourceReleaser content_provider_resource_releaser_;
  734. bool is_chunked_content_provider_ = false;
  735. bool content_provider_success_ = false;
  736. std::string file_content_path_;
  737. std::string file_content_content_type_;
  738. };
  739. enum class Error {
  740. Success = 0,
  741. Unknown,
  742. Connection,
  743. BindIPAddress,
  744. Read,
  745. Write,
  746. ExceedRedirectCount,
  747. Canceled,
  748. SSLConnection,
  749. SSLLoadingCerts,
  750. SSLServerVerification,
  751. SSLServerHostnameVerification,
  752. UnsupportedMultipartBoundaryChars,
  753. Compression,
  754. ConnectionTimeout,
  755. ProxyConnection,
  756. ConnectionClosed,
  757. Timeout,
  758. ResourceExhaustion,
  759. TooManyFormDataFiles,
  760. ExceedMaxPayloadSize,
  761. ExceedUriMaxLength,
  762. ExceedMaxSocketDescriptorCount,
  763. InvalidRequestLine,
  764. InvalidHTTPMethod,
  765. InvalidHTTPVersion,
  766. InvalidHeaders,
  767. MultipartParsing,
  768. OpenFile,
  769. Listen,
  770. GetSockName,
  771. UnsupportedAddressFamily,
  772. HTTPParsing,
  773. InvalidRangeHeader,
  774. // For internal use only
  775. SSLPeerCouldBeClosed_,
  776. };
  777. std::string to_string(Error error);
  778. std::ostream &operator<<(std::ostream &os, const Error &obj);
  779. class Stream {
  780. public:
  781. virtual ~Stream() = default;
  782. virtual bool is_readable() const = 0;
  783. virtual bool wait_readable() const = 0;
  784. virtual bool wait_writable() const = 0;
  785. virtual ssize_t read(char *ptr, size_t size) = 0;
  786. virtual ssize_t write(const char *ptr, size_t size) = 0;
  787. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  788. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  789. virtual socket_t socket() const = 0;
  790. virtual time_t duration() const = 0;
  791. ssize_t write(const char *ptr);
  792. ssize_t write(const std::string &s);
  793. Error get_error() const { return error_; }
  794. protected:
  795. Error error_ = Error::Success;
  796. };
  797. class TaskQueue {
  798. public:
  799. TaskQueue() = default;
  800. virtual ~TaskQueue() = default;
  801. virtual bool enqueue(std::function<void()> fn) = 0;
  802. virtual void shutdown() = 0;
  803. virtual void on_idle() {}
  804. };
  805. class ThreadPool final : public TaskQueue {
  806. public:
  807. explicit ThreadPool(size_t n, size_t mqr = 0)
  808. : shutdown_(false), max_queued_requests_(mqr) {
  809. threads_.reserve(n);
  810. while (n) {
  811. threads_.emplace_back(worker(*this));
  812. n--;
  813. }
  814. }
  815. ThreadPool(const ThreadPool &) = delete;
  816. ~ThreadPool() override = default;
  817. bool enqueue(std::function<void()> fn) override {
  818. {
  819. std::unique_lock<std::mutex> lock(mutex_);
  820. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  821. return false;
  822. }
  823. jobs_.push_back(std::move(fn));
  824. }
  825. cond_.notify_one();
  826. return true;
  827. }
  828. void shutdown() override {
  829. // Stop all worker threads...
  830. {
  831. std::unique_lock<std::mutex> lock(mutex_);
  832. shutdown_ = true;
  833. }
  834. cond_.notify_all();
  835. // Join...
  836. for (auto &t : threads_) {
  837. t.join();
  838. }
  839. }
  840. private:
  841. struct worker {
  842. explicit worker(ThreadPool &pool) : pool_(pool) {}
  843. void operator()() {
  844. for (;;) {
  845. std::function<void()> fn;
  846. {
  847. std::unique_lock<std::mutex> lock(pool_.mutex_);
  848. pool_.cond_.wait(
  849. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  850. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  851. fn = pool_.jobs_.front();
  852. pool_.jobs_.pop_front();
  853. }
  854. assert(true == static_cast<bool>(fn));
  855. fn();
  856. }
  857. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  858. !defined(LIBRESSL_VERSION_NUMBER)
  859. OPENSSL_thread_stop();
  860. #endif
  861. }
  862. ThreadPool &pool_;
  863. };
  864. friend struct worker;
  865. std::vector<std::thread> threads_;
  866. std::list<std::function<void()>> jobs_;
  867. bool shutdown_;
  868. size_t max_queued_requests_ = 0;
  869. std::condition_variable cond_;
  870. std::mutex mutex_;
  871. };
  872. using Logger = std::function<void(const Request &, const Response &)>;
  873. // Forward declaration for Error type
  874. enum class Error;
  875. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  876. using SocketOptions = std::function<void(socket_t sock)>;
  877. void default_socket_options(socket_t sock);
  878. const char *status_message(int status);
  879. std::string to_string(Error error);
  880. std::ostream &operator<<(std::ostream &os, const Error &obj);
  881. std::string get_bearer_token_auth(const Request &req);
  882. namespace detail {
  883. class MatcherBase {
  884. public:
  885. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  886. virtual ~MatcherBase() = default;
  887. const std::string &pattern() const { return pattern_; }
  888. // Match request path and populate its matches and
  889. virtual bool match(Request &request) const = 0;
  890. private:
  891. std::string pattern_;
  892. };
  893. /**
  894. * Captures parameters in request path and stores them in Request::path_params
  895. *
  896. * Capture name is a substring of a pattern from : to /.
  897. * The rest of the pattern is matched against the request path directly
  898. * Parameters are captured starting from the next character after
  899. * the end of the last matched static pattern fragment until the next /.
  900. *
  901. * Example pattern:
  902. * "/path/fragments/:capture/more/fragments/:second_capture"
  903. * Static fragments:
  904. * "/path/fragments/", "more/fragments/"
  905. *
  906. * Given the following request path:
  907. * "/path/fragments/:1/more/fragments/:2"
  908. * the resulting capture will be
  909. * {{"capture", "1"}, {"second_capture", "2"}}
  910. */
  911. class PathParamsMatcher final : public MatcherBase {
  912. public:
  913. PathParamsMatcher(const std::string &pattern);
  914. bool match(Request &request) const override;
  915. private:
  916. // Treat segment separators as the end of path parameter capture
  917. // Does not need to handle query parameters as they are parsed before path
  918. // matching
  919. static constexpr char separator = '/';
  920. // Contains static path fragments to match against, excluding the '/' after
  921. // path params
  922. // Fragments are separated by path params
  923. std::vector<std::string> static_fragments_;
  924. // Stores the names of the path parameters to be used as keys in the
  925. // Request::path_params map
  926. std::vector<std::string> param_names_;
  927. };
  928. /**
  929. * Performs std::regex_match on request path
  930. * and stores the result in Request::matches
  931. *
  932. * Note that regex match is performed directly on the whole request.
  933. * This means that wildcard patterns may match multiple path segments with /:
  934. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  935. */
  936. class RegexMatcher final : public MatcherBase {
  937. public:
  938. RegexMatcher(const std::string &pattern)
  939. : MatcherBase(pattern), regex_(pattern) {}
  940. bool match(Request &request) const override;
  941. private:
  942. std::regex regex_;
  943. };
  944. int close_socket(socket_t sock);
  945. ssize_t write_headers(Stream &strm, const Headers &headers);
  946. } // namespace detail
  947. class Server {
  948. public:
  949. using Handler = std::function<void(const Request &, Response &)>;
  950. using ExceptionHandler =
  951. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  952. enum class HandlerResponse {
  953. Handled,
  954. Unhandled,
  955. };
  956. using HandlerWithResponse =
  957. std::function<HandlerResponse(const Request &, Response &)>;
  958. using HandlerWithContentReader = std::function<void(
  959. const Request &, Response &, const ContentReader &content_reader)>;
  960. using Expect100ContinueHandler =
  961. std::function<int(const Request &, Response &)>;
  962. Server();
  963. virtual ~Server();
  964. virtual bool is_valid() const;
  965. Server &Get(const std::string &pattern, Handler handler);
  966. Server &Post(const std::string &pattern, Handler handler);
  967. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  968. Server &Put(const std::string &pattern, Handler handler);
  969. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  970. Server &Patch(const std::string &pattern, Handler handler);
  971. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  972. Server &Delete(const std::string &pattern, Handler handler);
  973. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  974. Server &Options(const std::string &pattern, Handler handler);
  975. bool set_base_dir(const std::string &dir,
  976. const std::string &mount_point = std::string());
  977. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  978. Headers headers = Headers());
  979. bool remove_mount_point(const std::string &mount_point);
  980. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  981. const std::string &mime);
  982. Server &set_default_file_mimetype(const std::string &mime);
  983. Server &set_file_request_handler(Handler handler);
  984. template <class ErrorHandlerFunc>
  985. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  986. return set_error_handler_core(
  987. std::forward<ErrorHandlerFunc>(handler),
  988. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  989. }
  990. Server &set_exception_handler(ExceptionHandler handler);
  991. Server &set_pre_routing_handler(HandlerWithResponse handler);
  992. Server &set_post_routing_handler(Handler handler);
  993. Server &set_pre_request_handler(HandlerWithResponse handler);
  994. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  995. Server &set_logger(Logger logger);
  996. Server &set_pre_compression_logger(Logger logger);
  997. Server &set_error_logger(ErrorLogger error_logger);
  998. Server &set_address_family(int family);
  999. Server &set_tcp_nodelay(bool on);
  1000. Server &set_ipv6_v6only(bool on);
  1001. Server &set_socket_options(SocketOptions socket_options);
  1002. Server &set_default_headers(Headers headers);
  1003. Server &
  1004. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1005. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1006. Server &set_keep_alive_max_count(size_t count);
  1007. Server &set_keep_alive_timeout(time_t sec);
  1008. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1009. template <class Rep, class Period>
  1010. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1011. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1012. template <class Rep, class Period>
  1013. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1014. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1015. template <class Rep, class Period>
  1016. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1017. Server &set_payload_max_length(size_t length);
  1018. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1019. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1020. bool listen_after_bind();
  1021. bool listen(const std::string &host, int port, int socket_flags = 0);
  1022. bool is_running() const;
  1023. void wait_until_ready() const;
  1024. void stop();
  1025. void decommission();
  1026. std::function<TaskQueue *(void)> new_task_queue;
  1027. protected:
  1028. bool process_request(Stream &strm, const std::string &remote_addr,
  1029. int remote_port, const std::string &local_addr,
  1030. int local_port, bool close_connection,
  1031. bool &connection_closed,
  1032. const std::function<void(Request &)> &setup_request);
  1033. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1034. std::vector<std::string> trusted_proxies_;
  1035. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1036. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1037. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1038. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1039. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1040. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1041. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1042. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1043. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1044. private:
  1045. using Handlers =
  1046. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1047. using HandlersForContentReader =
  1048. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1049. HandlerWithContentReader>>;
  1050. static std::unique_ptr<detail::MatcherBase>
  1051. make_matcher(const std::string &pattern);
  1052. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1053. Server &set_error_handler_core(Handler handler, std::false_type);
  1054. socket_t create_server_socket(const std::string &host, int port,
  1055. int socket_flags,
  1056. SocketOptions socket_options) const;
  1057. int bind_internal(const std::string &host, int port, int socket_flags);
  1058. bool listen_internal();
  1059. bool routing(Request &req, Response &res, Stream &strm);
  1060. bool handle_file_request(Request &req, Response &res);
  1061. bool check_if_not_modified(const Request &req, Response &res,
  1062. const std::string &etag, time_t mtime) const;
  1063. bool check_if_range(Request &req, const std::string &etag,
  1064. time_t mtime) const;
  1065. bool dispatch_request(Request &req, Response &res,
  1066. const Handlers &handlers) const;
  1067. bool dispatch_request_for_content_reader(
  1068. Request &req, Response &res, ContentReader content_reader,
  1069. const HandlersForContentReader &handlers) const;
  1070. bool parse_request_line(const char *s, Request &req) const;
  1071. void apply_ranges(const Request &req, Response &res,
  1072. std::string &content_type, std::string &boundary) const;
  1073. bool write_response(Stream &strm, bool close_connection, Request &req,
  1074. Response &res);
  1075. bool write_response_with_content(Stream &strm, bool close_connection,
  1076. const Request &req, Response &res);
  1077. bool write_response_core(Stream &strm, bool close_connection,
  1078. const Request &req, Response &res,
  1079. bool need_apply_ranges);
  1080. bool write_content_with_provider(Stream &strm, const Request &req,
  1081. Response &res, const std::string &boundary,
  1082. const std::string &content_type);
  1083. bool read_content(Stream &strm, Request &req, Response &res);
  1084. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1085. Response &res,
  1086. ContentReceiver receiver,
  1087. FormDataHeader multipart_header,
  1088. ContentReceiver multipart_receiver);
  1089. bool read_content_core(Stream &strm, Request &req, Response &res,
  1090. ContentReceiver receiver,
  1091. FormDataHeader multipart_header,
  1092. ContentReceiver multipart_receiver) const;
  1093. virtual bool process_and_close_socket(socket_t sock);
  1094. void output_log(const Request &req, const Response &res) const;
  1095. void output_pre_compression_log(const Request &req,
  1096. const Response &res) const;
  1097. void output_error_log(const Error &err, const Request *req) const;
  1098. std::atomic<bool> is_running_{false};
  1099. std::atomic<bool> is_decommissioned{false};
  1100. struct MountPointEntry {
  1101. std::string mount_point;
  1102. std::string base_dir;
  1103. Headers headers;
  1104. };
  1105. std::vector<MountPointEntry> base_dirs_;
  1106. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1107. std::string default_file_mimetype_ = "application/octet-stream";
  1108. Handler file_request_handler_;
  1109. Handlers get_handlers_;
  1110. Handlers post_handlers_;
  1111. HandlersForContentReader post_handlers_for_content_reader_;
  1112. Handlers put_handlers_;
  1113. HandlersForContentReader put_handlers_for_content_reader_;
  1114. Handlers patch_handlers_;
  1115. HandlersForContentReader patch_handlers_for_content_reader_;
  1116. Handlers delete_handlers_;
  1117. HandlersForContentReader delete_handlers_for_content_reader_;
  1118. Handlers options_handlers_;
  1119. HandlerWithResponse error_handler_;
  1120. ExceptionHandler exception_handler_;
  1121. HandlerWithResponse pre_routing_handler_;
  1122. Handler post_routing_handler_;
  1123. HandlerWithResponse pre_request_handler_;
  1124. Expect100ContinueHandler expect_100_continue_handler_;
  1125. mutable std::mutex logger_mutex_;
  1126. Logger logger_;
  1127. Logger pre_compression_logger_;
  1128. ErrorLogger error_logger_;
  1129. int address_family_ = AF_UNSPEC;
  1130. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1131. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1132. SocketOptions socket_options_ = default_socket_options;
  1133. Headers default_headers_;
  1134. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1135. detail::write_headers;
  1136. };
  1137. class Result {
  1138. public:
  1139. Result() = default;
  1140. Result(std::unique_ptr<Response> &&res, Error err,
  1141. Headers &&request_headers = Headers{})
  1142. : res_(std::move(res)), err_(err),
  1143. request_headers_(std::move(request_headers)) {}
  1144. #ifdef CPPHTTPLIB_SSL_ENABLED
  1145. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1146. int ssl_error)
  1147. : res_(std::move(res)), err_(err),
  1148. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1149. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1150. int ssl_error, unsigned long ssl_backend_error)
  1151. : res_(std::move(res)), err_(err),
  1152. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1153. ssl_backend_error_(ssl_backend_error) {}
  1154. #endif
  1155. // Response
  1156. operator bool() const { return res_ != nullptr; }
  1157. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1158. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1159. const Response &value() const { return *res_; }
  1160. Response &value() { return *res_; }
  1161. const Response &operator*() const { return *res_; }
  1162. Response &operator*() { return *res_; }
  1163. const Response *operator->() const { return res_.get(); }
  1164. Response *operator->() { return res_.get(); }
  1165. // Error
  1166. Error error() const { return err_; }
  1167. #ifdef CPPHTTPLIB_SSL_ENABLED
  1168. // SSL Error (backend-specific error code from handshake)
  1169. int ssl_error() const { return ssl_error_; }
  1170. // Backend-specific error code (OpenSSL: ERR_get_error(), Mbed TLS: mbedtls
  1171. // error code)
  1172. unsigned long ssl_backend_error() const { return ssl_backend_error_; }
  1173. #endif
  1174. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1175. // OpenSSL Error (alias for ssl_backend_error for backward compatibility)
  1176. unsigned long ssl_openssl_error() const { return ssl_backend_error_; }
  1177. #endif
  1178. // Request Headers
  1179. bool has_request_header(const std::string &key) const;
  1180. std::string get_request_header_value(const std::string &key,
  1181. const char *def = "",
  1182. size_t id = 0) const;
  1183. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1184. size_t id = 0) const;
  1185. size_t get_request_header_value_count(const std::string &key) const;
  1186. private:
  1187. std::unique_ptr<Response> res_;
  1188. Error err_ = Error::Unknown;
  1189. Headers request_headers_;
  1190. #ifdef CPPHTTPLIB_SSL_ENABLED
  1191. int ssl_error_ = 0;
  1192. unsigned long ssl_backend_error_ = 0;
  1193. #endif
  1194. };
  1195. struct ClientConnection {
  1196. socket_t sock = INVALID_SOCKET;
  1197. #ifdef CPPHTTPLIB_SSL_ENABLED
  1198. // Use void* directly since tls::tls_session_t is not yet defined here
  1199. void *session = nullptr;
  1200. #endif
  1201. bool is_open() const { return sock != INVALID_SOCKET; }
  1202. ClientConnection() = default;
  1203. // Destructor defined after tls namespace is available (see implementation
  1204. // section)
  1205. ~ClientConnection();
  1206. ClientConnection(const ClientConnection &) = delete;
  1207. ClientConnection &operator=(const ClientConnection &) = delete;
  1208. ClientConnection(ClientConnection &&other) noexcept
  1209. : sock(other.sock)
  1210. #ifdef CPPHTTPLIB_SSL_ENABLED
  1211. ,
  1212. session(other.session)
  1213. #endif
  1214. {
  1215. other.sock = INVALID_SOCKET;
  1216. #ifdef CPPHTTPLIB_SSL_ENABLED
  1217. other.session = nullptr;
  1218. #endif
  1219. }
  1220. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1221. if (this != &other) {
  1222. sock = other.sock;
  1223. #ifdef CPPHTTPLIB_SSL_ENABLED
  1224. session = other.session;
  1225. #endif
  1226. other.sock = INVALID_SOCKET;
  1227. #ifdef CPPHTTPLIB_SSL_ENABLED
  1228. other.session = nullptr;
  1229. #endif
  1230. }
  1231. return *this;
  1232. }
  1233. };
  1234. namespace detail {
  1235. struct ChunkedDecoder;
  1236. struct BodyReader {
  1237. Stream *stream = nullptr;
  1238. size_t content_length = 0;
  1239. size_t bytes_read = 0;
  1240. bool chunked = false;
  1241. bool eof = false;
  1242. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1243. Error last_error = Error::Success;
  1244. ssize_t read(char *buf, size_t len);
  1245. bool has_error() const { return last_error != Error::Success; }
  1246. };
  1247. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1248. size_t len) {
  1249. (void)stream;
  1250. return br.read(buf, len);
  1251. }
  1252. class decompressor;
  1253. } // namespace detail
  1254. class ClientImpl {
  1255. public:
  1256. explicit ClientImpl(const std::string &host);
  1257. explicit ClientImpl(const std::string &host, int port);
  1258. explicit ClientImpl(const std::string &host, int port,
  1259. const std::string &client_cert_path,
  1260. const std::string &client_key_path);
  1261. virtual ~ClientImpl();
  1262. virtual bool is_valid() const;
  1263. struct StreamHandle {
  1264. std::unique_ptr<Response> response;
  1265. Error error = Error::Success;
  1266. StreamHandle() = default;
  1267. StreamHandle(const StreamHandle &) = delete;
  1268. StreamHandle &operator=(const StreamHandle &) = delete;
  1269. StreamHandle(StreamHandle &&) = default;
  1270. StreamHandle &operator=(StreamHandle &&) = default;
  1271. ~StreamHandle() = default;
  1272. bool is_valid() const {
  1273. return response != nullptr && error == Error::Success;
  1274. }
  1275. ssize_t read(char *buf, size_t len);
  1276. void parse_trailers_if_needed();
  1277. Error get_read_error() const { return body_reader_.last_error; }
  1278. bool has_read_error() const { return body_reader_.has_error(); }
  1279. bool trailers_parsed_ = false;
  1280. private:
  1281. friend class ClientImpl;
  1282. ssize_t read_with_decompression(char *buf, size_t len);
  1283. std::unique_ptr<ClientConnection> connection_;
  1284. std::unique_ptr<Stream> socket_stream_;
  1285. Stream *stream_ = nullptr;
  1286. detail::BodyReader body_reader_;
  1287. std::unique_ptr<detail::decompressor> decompressor_;
  1288. std::string decompress_buffer_;
  1289. size_t decompress_offset_ = 0;
  1290. };
  1291. // clang-format off
  1292. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1293. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1294. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1295. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1296. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1297. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1298. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1299. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1300. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1301. Result Head(const std::string &path);
  1302. Result Head(const std::string &path, const Headers &headers);
  1303. Result Post(const std::string &path);
  1304. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1305. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1306. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1307. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1308. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1309. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1310. Result Post(const std::string &path, const Params &params);
  1311. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1312. Result Post(const std::string &path, const Headers &headers);
  1313. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1314. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1315. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1316. 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);
  1317. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1318. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1319. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1320. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1321. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1322. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1323. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1324. Result Put(const std::string &path);
  1325. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1326. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1327. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1328. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1329. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1330. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1331. Result Put(const std::string &path, const Params &params);
  1332. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1333. Result Put(const std::string &path, const Headers &headers);
  1334. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1335. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1336. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1337. 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);
  1338. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1339. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1340. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1341. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1342. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1343. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1344. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1345. Result Patch(const std::string &path);
  1346. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1347. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1348. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1349. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1350. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1351. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1352. Result Patch(const std::string &path, const Params &params);
  1353. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1354. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1355. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1356. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1357. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1358. 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);
  1359. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1360. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1361. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1362. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1363. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1364. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1365. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1366. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1367. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1368. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1369. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1370. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1371. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1372. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1373. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1374. Result Options(const std::string &path);
  1375. Result Options(const std::string &path, const Headers &headers);
  1376. // clang-format on
  1377. // Streaming API: Open a stream for reading response body incrementally
  1378. // Socket ownership is transferred to StreamHandle for true streaming
  1379. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1380. StreamHandle open_stream(const std::string &method, const std::string &path,
  1381. const Params &params = {},
  1382. const Headers &headers = {},
  1383. const std::string &body = {},
  1384. const std::string &content_type = {});
  1385. bool send(Request &req, Response &res, Error &error);
  1386. Result send(const Request &req);
  1387. void stop();
  1388. std::string host() const;
  1389. int port() const;
  1390. size_t is_socket_open() const;
  1391. socket_t socket() const;
  1392. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1393. void set_default_headers(Headers headers);
  1394. void
  1395. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1396. void set_address_family(int family);
  1397. void set_tcp_nodelay(bool on);
  1398. void set_ipv6_v6only(bool on);
  1399. void set_socket_options(SocketOptions socket_options);
  1400. void set_connection_timeout(time_t sec, time_t usec = 0);
  1401. template <class Rep, class Period>
  1402. void
  1403. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1404. void set_read_timeout(time_t sec, time_t usec = 0);
  1405. template <class Rep, class Period>
  1406. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1407. void set_write_timeout(time_t sec, time_t usec = 0);
  1408. template <class Rep, class Period>
  1409. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1410. void set_max_timeout(time_t msec);
  1411. template <class Rep, class Period>
  1412. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1413. void set_basic_auth(const std::string &username, const std::string &password);
  1414. void set_bearer_token_auth(const std::string &token);
  1415. #ifdef CPPHTTPLIB_SSL_ENABLED
  1416. void set_digest_auth(const std::string &username,
  1417. const std::string &password);
  1418. #endif
  1419. void set_keep_alive(bool on);
  1420. void set_follow_location(bool on);
  1421. void set_path_encode(bool on);
  1422. void set_compress(bool on);
  1423. void set_decompress(bool on);
  1424. void set_interface(const std::string &intf);
  1425. void set_proxy(const std::string &host, int port);
  1426. void set_proxy_basic_auth(const std::string &username,
  1427. const std::string &password);
  1428. void set_proxy_bearer_token_auth(const std::string &token);
  1429. #ifdef CPPHTTPLIB_SSL_ENABLED
  1430. void set_proxy_digest_auth(const std::string &username,
  1431. const std::string &password);
  1432. #endif
  1433. #ifdef CPPHTTPLIB_SSL_ENABLED
  1434. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1435. const std::string &ca_cert_dir_path = std::string());
  1436. void enable_server_certificate_verification(bool enabled);
  1437. void enable_server_hostname_verification(bool enabled);
  1438. #endif
  1439. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1440. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1441. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1442. #endif
  1443. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1444. void set_server_certificate_verifier(
  1445. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1446. #endif
  1447. void set_logger(Logger logger);
  1448. void set_error_logger(ErrorLogger error_logger);
  1449. protected:
  1450. struct Socket {
  1451. socket_t sock = INVALID_SOCKET;
  1452. #ifdef CPPHTTPLIB_SSL_ENABLED
  1453. // Use void* directly since tls::tls_session_t is not yet defined here
  1454. void *ssl = nullptr;
  1455. #endif
  1456. // For Mbed TLS compatibility: start_time for request timeout tracking
  1457. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1458. bool is_open() const { return sock != INVALID_SOCKET; }
  1459. };
  1460. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1461. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1462. // All of:
  1463. // shutdown_ssl
  1464. // shutdown_socket
  1465. // close_socket
  1466. // should ONLY be called when socket_mutex_ is locked.
  1467. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1468. // with a DIFFERENT thread sending requests using that socket.
  1469. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1470. void shutdown_socket(Socket &socket) const;
  1471. void close_socket(Socket &socket);
  1472. bool process_request(Stream &strm, Request &req, Response &res,
  1473. bool close_connection, Error &error);
  1474. bool write_content_with_provider(Stream &strm, const Request &req,
  1475. Error &error) const;
  1476. void copy_settings(const ClientImpl &rhs);
  1477. void output_log(const Request &req, const Response &res) const;
  1478. void output_error_log(const Error &err, const Request *req) const;
  1479. // Socket endpoint information
  1480. const std::string host_;
  1481. const int port_;
  1482. // Current open socket
  1483. Socket socket_;
  1484. mutable std::mutex socket_mutex_;
  1485. std::recursive_mutex request_mutex_;
  1486. // These are all protected under socket_mutex
  1487. size_t socket_requests_in_flight_ = 0;
  1488. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1489. bool socket_should_be_closed_when_request_is_done_ = false;
  1490. // Hostname-IP map
  1491. std::map<std::string, std::string> addr_map_;
  1492. // Default headers
  1493. Headers default_headers_;
  1494. // Header writer
  1495. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1496. detail::write_headers;
  1497. // Settings
  1498. std::string client_cert_path_;
  1499. std::string client_key_path_;
  1500. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1501. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1502. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1503. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1504. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1505. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1506. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1507. std::string basic_auth_username_;
  1508. std::string basic_auth_password_;
  1509. std::string bearer_token_auth_token_;
  1510. #ifdef CPPHTTPLIB_SSL_ENABLED
  1511. std::string digest_auth_username_;
  1512. std::string digest_auth_password_;
  1513. #endif
  1514. bool keep_alive_ = false;
  1515. bool follow_location_ = false;
  1516. bool path_encode_ = true;
  1517. int address_family_ = AF_UNSPEC;
  1518. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1519. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1520. SocketOptions socket_options_ = nullptr;
  1521. bool compress_ = false;
  1522. bool decompress_ = true;
  1523. std::string interface_;
  1524. std::string proxy_host_;
  1525. int proxy_port_ = -1;
  1526. std::string proxy_basic_auth_username_;
  1527. std::string proxy_basic_auth_password_;
  1528. std::string proxy_bearer_token_auth_token_;
  1529. #ifdef CPPHTTPLIB_SSL_ENABLED
  1530. std::string proxy_digest_auth_username_;
  1531. std::string proxy_digest_auth_password_;
  1532. #endif
  1533. #ifdef CPPHTTPLIB_SSL_ENABLED
  1534. std::string ca_cert_file_path_;
  1535. std::string ca_cert_dir_path_;
  1536. #endif
  1537. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1538. X509_STORE *ca_cert_store_ = nullptr;
  1539. #endif
  1540. #ifdef CPPHTTPLIB_SSL_ENABLED
  1541. bool server_certificate_verification_ = true;
  1542. bool server_hostname_verification_ = true;
  1543. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  1544. #endif
  1545. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1546. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1547. #endif
  1548. mutable std::mutex logger_mutex_;
  1549. Logger logger_;
  1550. ErrorLogger error_logger_;
  1551. #ifdef CPPHTTPLIB_SSL_ENABLED
  1552. int last_ssl_error_ = 0;
  1553. unsigned long last_backend_error_ = 0;
  1554. #endif
  1555. private:
  1556. bool send_(Request &req, Response &res, Error &error);
  1557. Result send_(Request &&req);
  1558. socket_t create_client_socket(Error &error) const;
  1559. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1560. bool skip_100_continue = true) const;
  1561. bool write_request(Stream &strm, Request &req, bool close_connection,
  1562. Error &error, bool skip_body = false);
  1563. bool write_request_body(Stream &strm, Request &req, Error &error);
  1564. void prepare_default_headers(Request &r, bool for_stream,
  1565. const std::string &ct);
  1566. bool redirect(Request &req, Response &res, Error &error);
  1567. bool create_redirect_client(const std::string &scheme,
  1568. const std::string &host, int port, Request &req,
  1569. Response &res, const std::string &path,
  1570. const std::string &location, Error &error);
  1571. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1572. bool handle_request(Stream &strm, Request &req, Response &res,
  1573. bool close_connection, Error &error);
  1574. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1575. Request &req, const char *body, size_t content_length,
  1576. ContentProvider content_provider,
  1577. ContentProviderWithoutLength content_provider_without_length,
  1578. const std::string &content_type, ContentReceiver content_receiver,
  1579. Error &error);
  1580. Result send_with_content_provider_and_receiver(
  1581. const std::string &method, const std::string &path,
  1582. const Headers &headers, const char *body, size_t content_length,
  1583. ContentProvider content_provider,
  1584. ContentProviderWithoutLength content_provider_without_length,
  1585. const std::string &content_type, ContentReceiver content_receiver,
  1586. UploadProgress progress);
  1587. ContentProviderWithoutLength get_multipart_content_provider(
  1588. const std::string &boundary, const UploadFormDataItems &items,
  1589. const FormDataProviderItems &provider_items) const;
  1590. virtual bool
  1591. process_socket(const Socket &socket,
  1592. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1593. std::function<bool(Stream &strm)> callback);
  1594. virtual bool is_ssl() const;
  1595. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1596. };
  1597. class Client {
  1598. public:
  1599. // Universal interface
  1600. explicit Client(const std::string &scheme_host_port);
  1601. explicit Client(const std::string &scheme_host_port,
  1602. const std::string &client_cert_path,
  1603. const std::string &client_key_path);
  1604. // HTTP only interface
  1605. explicit Client(const std::string &host, int port);
  1606. explicit Client(const std::string &host, int port,
  1607. const std::string &client_cert_path,
  1608. const std::string &client_key_path);
  1609. Client(Client &&) = default;
  1610. Client &operator=(Client &&) = default;
  1611. ~Client();
  1612. bool is_valid() const;
  1613. // clang-format off
  1614. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1615. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1616. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1617. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1618. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1619. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1620. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1621. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1622. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1623. Result Head(const std::string &path);
  1624. Result Head(const std::string &path, const Headers &headers);
  1625. Result Post(const std::string &path);
  1626. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1627. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1628. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1629. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1630. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1631. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1632. Result Post(const std::string &path, const Params &params);
  1633. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1634. Result Post(const std::string &path, const Headers &headers);
  1635. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1636. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1637. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1638. 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);
  1639. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1640. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1641. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1642. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1643. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1644. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1645. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1646. Result Put(const std::string &path);
  1647. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1648. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1649. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1650. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1651. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1652. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1653. Result Put(const std::string &path, const Params &params);
  1654. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1655. Result Put(const std::string &path, const Headers &headers);
  1656. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1657. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1658. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1659. 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);
  1660. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1661. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1662. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1663. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1664. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1665. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1666. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1667. Result Patch(const std::string &path);
  1668. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1669. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1670. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1671. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1672. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1673. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1674. Result Patch(const std::string &path, const Params &params);
  1675. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1676. Result Patch(const std::string &path, const Headers &headers);
  1677. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1678. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1679. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1680. 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);
  1681. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1682. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1683. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1684. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1685. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1686. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1687. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1688. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1689. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1690. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1691. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1692. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1693. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1694. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1695. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1696. Result Options(const std::string &path);
  1697. Result Options(const std::string &path, const Headers &headers);
  1698. // clang-format on
  1699. // Streaming API: Open a stream for reading response body incrementally
  1700. // Socket ownership is transferred to StreamHandle for true streaming
  1701. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1702. ClientImpl::StreamHandle open_stream(const std::string &method,
  1703. const std::string &path,
  1704. const Params &params = {},
  1705. const Headers &headers = {},
  1706. const std::string &body = {},
  1707. const std::string &content_type = {});
  1708. bool send(Request &req, Response &res, Error &error);
  1709. Result send(const Request &req);
  1710. void stop();
  1711. std::string host() const;
  1712. int port() const;
  1713. size_t is_socket_open() const;
  1714. socket_t socket() const;
  1715. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1716. void set_default_headers(Headers headers);
  1717. void
  1718. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1719. void set_address_family(int family);
  1720. void set_tcp_nodelay(bool on);
  1721. void set_socket_options(SocketOptions socket_options);
  1722. void set_connection_timeout(time_t sec, time_t usec = 0);
  1723. template <class Rep, class Period>
  1724. void
  1725. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1726. void set_read_timeout(time_t sec, time_t usec = 0);
  1727. template <class Rep, class Period>
  1728. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1729. void set_write_timeout(time_t sec, time_t usec = 0);
  1730. template <class Rep, class Period>
  1731. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1732. void set_max_timeout(time_t msec);
  1733. template <class Rep, class Period>
  1734. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1735. void set_basic_auth(const std::string &username, const std::string &password);
  1736. void set_bearer_token_auth(const std::string &token);
  1737. #ifdef CPPHTTPLIB_SSL_ENABLED
  1738. void set_digest_auth(const std::string &username,
  1739. const std::string &password);
  1740. #endif
  1741. void set_keep_alive(bool on);
  1742. void set_follow_location(bool on);
  1743. void set_path_encode(bool on);
  1744. void set_url_encode(bool on);
  1745. void set_compress(bool on);
  1746. void set_decompress(bool on);
  1747. void set_interface(const std::string &intf);
  1748. void set_proxy(const std::string &host, int port);
  1749. void set_proxy_basic_auth(const std::string &username,
  1750. const std::string &password);
  1751. void set_proxy_bearer_token_auth(const std::string &token);
  1752. #ifdef CPPHTTPLIB_SSL_ENABLED
  1753. void set_proxy_digest_auth(const std::string &username,
  1754. const std::string &password);
  1755. #endif
  1756. #ifdef CPPHTTPLIB_SSL_ENABLED
  1757. void enable_server_certificate_verification(bool enabled);
  1758. void enable_server_hostname_verification(bool enabled);
  1759. #endif
  1760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1761. void set_server_certificate_verifier(
  1762. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1763. #endif
  1764. void set_logger(Logger logger);
  1765. void set_error_logger(ErrorLogger error_logger);
  1766. // SSL
  1767. #ifdef CPPHTTPLIB_SSL_ENABLED
  1768. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1769. const std::string &ca_cert_dir_path = std::string());
  1770. #endif
  1771. #ifdef CPPHTTPLIB_SSL_ENABLED
  1772. // Use void* directly since tls::tls_ca_store_t is not yet defined here
  1773. void set_ca_cert_store(void *ca_cert_store);
  1774. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1775. // Custom certificate verification callback (works with all TLS backends)
  1776. // Callback receives session and peer certificate, returns true to accept
  1777. using TlsVerifyCallback = std::function<bool(void *session, void *peer_cert)>;
  1778. void set_server_certificate_verifier(TlsVerifyCallback verifier);
  1779. #endif
  1780. // Backend-agnostic TLS context accessor
  1781. void *tls_context() const;
  1782. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1783. long get_openssl_verify_result() const;
  1784. SSL_CTX *ssl_context() const;
  1785. #endif
  1786. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  1787. mbedtls_ssl_config *ssl_config() const;
  1788. #endif
  1789. private:
  1790. std::unique_ptr<ClientImpl> cli_;
  1791. #ifdef CPPHTTPLIB_SSL_ENABLED
  1792. bool is_ssl_ = false;
  1793. #endif
  1794. };
  1795. #ifdef CPPHTTPLIB_SSL_ENABLED
  1796. class SSLServer : public Server {
  1797. public:
  1798. SSLServer(const char *cert_path, const char *private_key_path,
  1799. const char *client_ca_cert_file_path = nullptr,
  1800. const char *client_ca_cert_dir_path = nullptr,
  1801. const char *private_key_password = nullptr);
  1802. // PEM memory-based constructor (works with all TLS backends)
  1803. struct PemMemory {
  1804. const char *cert_pem;
  1805. size_t cert_pem_len;
  1806. const char *key_pem;
  1807. size_t key_pem_len;
  1808. const char *client_ca_pem;
  1809. size_t client_ca_pem_len;
  1810. const char *private_key_password;
  1811. };
  1812. explicit SSLServer(const PemMemory &pem);
  1813. // Backend-agnostic callback constructor
  1814. // The callback receives the opaque tls_ctx_t handle (void*) which can be
  1815. // cast to the appropriate backend type (SSL_CTX* for OpenSSL, MbedTlsContext*
  1816. // for mbedTLS)
  1817. explicit SSLServer(const std::function<bool(void *ctx)> &setup_callback);
  1818. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1819. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1820. X509_STORE *client_ca_cert_store = nullptr);
  1821. // OpenSSL-specific callback constructor for full API access
  1822. SSLServer(
  1823. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1824. #endif
  1825. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  1826. // mbedTLS-specific callback constructor for full API access
  1827. // Provides direct access to mbedtls_ssl_config for advanced configuration
  1828. SSLServer(
  1829. const std::function<bool(mbedtls_ssl_config &conf)> &setup_callback);
  1830. #endif
  1831. ~SSLServer() override;
  1832. bool is_valid() const override;
  1833. // Update certificates from PEM strings (works with all TLS backends)
  1834. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  1835. const char *password = nullptr);
  1836. bool update_client_ca_pem(const char *ca_pem);
  1837. // Backend-agnostic TLS context accessor
  1838. void *tls_context() const { return ctx_; }
  1839. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1840. SSL_CTX *ssl_context() const;
  1841. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1842. X509_STORE *client_ca_cert_store = nullptr);
  1843. #endif
  1844. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  1845. mbedtls_ssl_config *ssl_config() const;
  1846. #endif
  1847. int ssl_last_error() const { return last_ssl_error_; }
  1848. private:
  1849. bool process_and_close_socket(socket_t sock) override;
  1850. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1851. STACK_OF(X509_NAME) * extract_ca_names_from_x509_store(X509_STORE *store);
  1852. #endif
  1853. // Use void* for tls_ctx_t to support all backends
  1854. void *ctx_ = nullptr;
  1855. std::mutex ctx_mutex_;
  1856. int last_ssl_error_ = 0;
  1857. };
  1858. class SSLClient final : public ClientImpl {
  1859. public:
  1860. explicit SSLClient(const std::string &host);
  1861. explicit SSLClient(const std::string &host, int port);
  1862. explicit SSLClient(const std::string &host, int port,
  1863. const std::string &client_cert_path,
  1864. const std::string &client_key_path,
  1865. const std::string &private_key_password = std::string());
  1866. // PEM memory-based constructor (works with all TLS backends)
  1867. struct PemMemory {
  1868. const char *cert_pem;
  1869. size_t cert_pem_len;
  1870. const char *key_pem;
  1871. size_t key_pem_len;
  1872. const char *private_key_password;
  1873. };
  1874. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  1875. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1876. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1877. EVP_PKEY *client_key,
  1878. const std::string &private_key_password = std::string());
  1879. #endif
  1880. ~SSLClient() override;
  1881. bool is_valid() const override;
  1882. // Use void* directly since tls::tls_ca_store_t is not yet defined here
  1883. void set_ca_cert_store(void *ca_cert_store);
  1884. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1885. // Custom certificate verification callback (works with all TLS backends)
  1886. // Callback receives session and peer certificate, returns true to accept
  1887. using TlsVerifyCallback = std::function<bool(void *session, void *peer_cert)>;
  1888. void set_server_certificate_verifier(TlsVerifyCallback verifier);
  1889. // Backend-agnostic TLS context accessor
  1890. void *tls_context() const { return ctx_; }
  1891. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1892. long get_openssl_verify_result() const;
  1893. SSL_CTX *ssl_context() const;
  1894. #endif
  1895. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  1896. mbedtls_ssl_config *ssl_config() const;
  1897. #endif
  1898. private:
  1899. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1900. bool ensure_socket_connection(Socket &socket, Error &error) override;
  1901. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1902. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1903. bool
  1904. process_socket(const Socket &socket,
  1905. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1906. std::function<bool(Stream &strm)> callback) override;
  1907. bool is_ssl() const override;
  1908. bool connect_with_proxy(
  1909. Socket &sock,
  1910. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1911. Response &res, bool &success, Error &error);
  1912. bool initialize_ssl(Socket &socket, Error &error);
  1913. bool load_certs();
  1914. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1915. bool verify_host(X509 *server_cert) const;
  1916. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1917. bool verify_host_with_common_name(X509 *server_cert) const;
  1918. #endif
  1919. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1920. // Use void* directly since tls::tls_ctx_t is not yet defined here
  1921. void *ctx_;
  1922. std::mutex ctx_mutex_;
  1923. std::once_flag initialize_cert_;
  1924. std::vector<std::string> host_components_;
  1925. long verify_result_ = 0;
  1926. friend class ClientImpl;
  1927. };
  1928. #endif // CPPHTTPLIB_SSL_ENABLED
  1929. /*
  1930. * Implementation of template methods.
  1931. */
  1932. namespace detail {
  1933. template <typename T, typename U>
  1934. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1935. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1936. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1937. duration - std::chrono::seconds(sec))
  1938. .count();
  1939. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1940. }
  1941. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1942. return N - 1;
  1943. }
  1944. inline bool is_numeric(const std::string &str) {
  1945. return !str.empty() &&
  1946. std::all_of(str.cbegin(), str.cend(),
  1947. [](unsigned char c) { return std::isdigit(c); });
  1948. }
  1949. inline size_t get_header_value_u64(const Headers &headers,
  1950. const std::string &key, size_t def,
  1951. size_t id, bool &is_invalid_value) {
  1952. is_invalid_value = false;
  1953. auto rng = headers.equal_range(key);
  1954. auto it = rng.first;
  1955. std::advance(it, static_cast<ssize_t>(id));
  1956. if (it != rng.second) {
  1957. if (is_numeric(it->second)) {
  1958. return std::strtoull(it->second.data(), nullptr, 10);
  1959. } else {
  1960. is_invalid_value = true;
  1961. }
  1962. }
  1963. return def;
  1964. }
  1965. inline size_t get_header_value_u64(const Headers &headers,
  1966. const std::string &key, size_t def,
  1967. size_t id) {
  1968. auto dummy = false;
  1969. return get_header_value_u64(headers, key, def, id, dummy);
  1970. }
  1971. } // namespace detail
  1972. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  1973. size_t id) const {
  1974. return detail::get_header_value_u64(headers, key, def, id);
  1975. }
  1976. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  1977. size_t id) const {
  1978. return detail::get_header_value_u64(headers, key, def, id);
  1979. }
  1980. namespace detail {
  1981. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1982. const void *optval, socklen_t optlen) {
  1983. return setsockopt(sock, level, optname,
  1984. #ifdef _WIN32
  1985. reinterpret_cast<const char *>(optval),
  1986. #else
  1987. optval,
  1988. #endif
  1989. optlen) == 0;
  1990. }
  1991. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1992. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1993. }
  1994. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1995. time_t sec, time_t usec) {
  1996. #ifdef _WIN32
  1997. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1998. #else
  1999. timeval timeout;
  2000. timeout.tv_sec = static_cast<long>(sec);
  2001. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  2002. #endif
  2003. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  2004. }
  2005. } // namespace detail
  2006. inline void default_socket_options(socket_t sock) {
  2007. detail::set_socket_opt(sock, SOL_SOCKET,
  2008. #ifdef SO_REUSEPORT
  2009. SO_REUSEPORT,
  2010. #else
  2011. SO_REUSEADDR,
  2012. #endif
  2013. 1);
  2014. }
  2015. inline std::string get_bearer_token_auth(const Request &req) {
  2016. if (req.has_header("Authorization")) {
  2017. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  2018. return req.get_header_value("Authorization")
  2019. .substr(bearer_header_prefix_len);
  2020. }
  2021. return "";
  2022. }
  2023. template <class Rep, class Period>
  2024. inline Server &
  2025. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2026. detail::duration_to_sec_and_usec(
  2027. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2028. return *this;
  2029. }
  2030. template <class Rep, class Period>
  2031. inline Server &
  2032. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2033. detail::duration_to_sec_and_usec(
  2034. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2035. return *this;
  2036. }
  2037. template <class Rep, class Period>
  2038. inline Server &
  2039. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2040. detail::duration_to_sec_and_usec(
  2041. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2042. return *this;
  2043. }
  2044. inline size_t Result::get_request_header_value_u64(const std::string &key,
  2045. size_t def,
  2046. size_t id) const {
  2047. return detail::get_header_value_u64(request_headers_, key, def, id);
  2048. }
  2049. template <class Rep, class Period>
  2050. inline void ClientImpl::set_connection_timeout(
  2051. const std::chrono::duration<Rep, Period> &duration) {
  2052. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2053. set_connection_timeout(sec, usec);
  2054. });
  2055. }
  2056. template <class Rep, class Period>
  2057. inline void ClientImpl::set_read_timeout(
  2058. const std::chrono::duration<Rep, Period> &duration) {
  2059. detail::duration_to_sec_and_usec(
  2060. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2061. }
  2062. template <class Rep, class Period>
  2063. inline void ClientImpl::set_write_timeout(
  2064. const std::chrono::duration<Rep, Period> &duration) {
  2065. detail::duration_to_sec_and_usec(
  2066. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2067. }
  2068. template <class Rep, class Period>
  2069. inline void ClientImpl::set_max_timeout(
  2070. const std::chrono::duration<Rep, Period> &duration) {
  2071. auto msec =
  2072. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2073. set_max_timeout(msec);
  2074. }
  2075. template <class Rep, class Period>
  2076. inline void Client::set_connection_timeout(
  2077. const std::chrono::duration<Rep, Period> &duration) {
  2078. cli_->set_connection_timeout(duration);
  2079. }
  2080. template <class Rep, class Period>
  2081. inline void
  2082. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2083. cli_->set_read_timeout(duration);
  2084. }
  2085. template <class Rep, class Period>
  2086. inline void
  2087. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2088. cli_->set_write_timeout(duration);
  2089. }
  2090. inline void Client::set_max_timeout(time_t msec) {
  2091. cli_->set_max_timeout(msec);
  2092. }
  2093. template <class Rep, class Period>
  2094. inline void
  2095. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2096. cli_->set_max_timeout(duration);
  2097. }
  2098. /*
  2099. * Forward declarations and types that will be part of the .h file if split into
  2100. * .h + .cc.
  2101. */
  2102. std::string hosted_at(const std::string &hostname);
  2103. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2104. // JavaScript-style URL encoding/decoding functions
  2105. std::string encode_uri_component(const std::string &value);
  2106. std::string encode_uri(const std::string &value);
  2107. std::string decode_uri_component(const std::string &value);
  2108. std::string decode_uri(const std::string &value);
  2109. // RFC 3986 compliant URL component encoding/decoding functions
  2110. std::string encode_path_component(const std::string &component);
  2111. std::string decode_path_component(const std::string &component);
  2112. std::string encode_query_component(const std::string &component,
  2113. bool space_as_plus = true);
  2114. std::string decode_query_component(const std::string &component,
  2115. bool plus_as_space = true);
  2116. std::string append_query_params(const std::string &path, const Params &params);
  2117. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2118. std::pair<std::string, std::string>
  2119. make_basic_authentication_header(const std::string &username,
  2120. const std::string &password,
  2121. bool is_proxy = false);
  2122. namespace detail {
  2123. #if defined(_WIN32)
  2124. inline std::wstring u8string_to_wstring(const char *s) {
  2125. if (!s) { return std::wstring(); }
  2126. auto len = static_cast<int>(strlen(s));
  2127. if (!len) { return std::wstring(); }
  2128. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2129. if (!wlen) { return std::wstring(); }
  2130. std::wstring ws;
  2131. ws.resize(wlen);
  2132. wlen = ::MultiByteToWideChar(
  2133. CP_UTF8, 0, s, len,
  2134. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2135. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2136. return ws;
  2137. }
  2138. #endif
  2139. struct FileStat {
  2140. FileStat(const std::string &path);
  2141. bool is_file() const;
  2142. bool is_dir() const;
  2143. time_t mtime() const;
  2144. size_t size() const;
  2145. private:
  2146. #if defined(_WIN32)
  2147. struct _stat st_;
  2148. #else
  2149. struct stat st_;
  2150. #endif
  2151. int ret_ = -1;
  2152. };
  2153. std::string make_host_and_port_string(const std::string &host, int port,
  2154. bool is_ssl);
  2155. std::string trim_copy(const std::string &s);
  2156. void divide(
  2157. const char *data, std::size_t size, char d,
  2158. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2159. fn);
  2160. void divide(
  2161. const std::string &str, char d,
  2162. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2163. fn);
  2164. void split(const char *b, const char *e, char d,
  2165. std::function<void(const char *, const char *)> fn);
  2166. void split(const char *b, const char *e, char d, size_t m,
  2167. std::function<void(const char *, const char *)> fn);
  2168. bool process_client_socket(
  2169. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2170. time_t write_timeout_sec, time_t write_timeout_usec,
  2171. time_t max_timeout_msec,
  2172. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2173. std::function<bool(Stream &)> callback);
  2174. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2175. int port, int address_family, bool tcp_nodelay,
  2176. bool ipv6_v6only, SocketOptions socket_options,
  2177. time_t connection_timeout_sec,
  2178. time_t connection_timeout_usec,
  2179. time_t read_timeout_sec, time_t read_timeout_usec,
  2180. time_t write_timeout_sec,
  2181. time_t write_timeout_usec,
  2182. const std::string &intf, Error &error);
  2183. const char *get_header_value(const Headers &headers, const std::string &key,
  2184. const char *def, size_t id);
  2185. std::string params_to_query_str(const Params &params);
  2186. void parse_query_text(const char *data, std::size_t size, Params &params);
  2187. void parse_query_text(const std::string &s, Params &params);
  2188. bool parse_multipart_boundary(const std::string &content_type,
  2189. std::string &boundary);
  2190. bool parse_range_header(const std::string &s, Ranges &ranges);
  2191. bool parse_accept_header(const std::string &s,
  2192. std::vector<std::string> &content_types);
  2193. int close_socket(socket_t sock);
  2194. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2195. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2196. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2197. EncodingType encoding_type(const Request &req, const Response &res);
  2198. class BufferStream final : public Stream {
  2199. public:
  2200. BufferStream() = default;
  2201. ~BufferStream() override = default;
  2202. bool is_readable() const override;
  2203. bool wait_readable() const override;
  2204. bool wait_writable() const override;
  2205. ssize_t read(char *ptr, size_t size) override;
  2206. ssize_t write(const char *ptr, size_t size) override;
  2207. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2208. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2209. socket_t socket() const override;
  2210. time_t duration() const override;
  2211. const std::string &get_buffer() const;
  2212. private:
  2213. std::string buffer;
  2214. size_t position = 0;
  2215. };
  2216. class compressor {
  2217. public:
  2218. virtual ~compressor() = default;
  2219. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2220. virtual bool compress(const char *data, size_t data_length, bool last,
  2221. Callback callback) = 0;
  2222. };
  2223. class decompressor {
  2224. public:
  2225. virtual ~decompressor() = default;
  2226. virtual bool is_valid() const = 0;
  2227. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2228. virtual bool decompress(const char *data, size_t data_length,
  2229. Callback callback) = 0;
  2230. };
  2231. class nocompressor final : public compressor {
  2232. public:
  2233. ~nocompressor() override = default;
  2234. bool compress(const char *data, size_t data_length, bool /*last*/,
  2235. Callback callback) override;
  2236. };
  2237. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2238. class gzip_compressor final : public compressor {
  2239. public:
  2240. gzip_compressor();
  2241. ~gzip_compressor() override;
  2242. bool compress(const char *data, size_t data_length, bool last,
  2243. Callback callback) override;
  2244. private:
  2245. bool is_valid_ = false;
  2246. z_stream strm_;
  2247. };
  2248. class gzip_decompressor final : public decompressor {
  2249. public:
  2250. gzip_decompressor();
  2251. ~gzip_decompressor() override;
  2252. bool is_valid() const override;
  2253. bool decompress(const char *data, size_t data_length,
  2254. Callback callback) override;
  2255. private:
  2256. bool is_valid_ = false;
  2257. z_stream strm_;
  2258. };
  2259. #endif
  2260. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2261. class brotli_compressor final : public compressor {
  2262. public:
  2263. brotli_compressor();
  2264. ~brotli_compressor();
  2265. bool compress(const char *data, size_t data_length, bool last,
  2266. Callback callback) override;
  2267. private:
  2268. BrotliEncoderState *state_ = nullptr;
  2269. };
  2270. class brotli_decompressor final : public decompressor {
  2271. public:
  2272. brotli_decompressor();
  2273. ~brotli_decompressor();
  2274. bool is_valid() const override;
  2275. bool decompress(const char *data, size_t data_length,
  2276. Callback callback) override;
  2277. private:
  2278. BrotliDecoderResult decoder_r;
  2279. BrotliDecoderState *decoder_s = nullptr;
  2280. };
  2281. #endif
  2282. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2283. class zstd_compressor : public compressor {
  2284. public:
  2285. zstd_compressor();
  2286. ~zstd_compressor();
  2287. bool compress(const char *data, size_t data_length, bool last,
  2288. Callback callback) override;
  2289. private:
  2290. ZSTD_CCtx *ctx_ = nullptr;
  2291. };
  2292. class zstd_decompressor : public decompressor {
  2293. public:
  2294. zstd_decompressor();
  2295. ~zstd_decompressor();
  2296. bool is_valid() const override;
  2297. bool decompress(const char *data, size_t data_length,
  2298. Callback callback) override;
  2299. private:
  2300. ZSTD_DCtx *ctx_ = nullptr;
  2301. };
  2302. #endif
  2303. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2304. // to store data. The call can set memory on stack for performance.
  2305. class stream_line_reader {
  2306. public:
  2307. stream_line_reader(Stream &strm, char *fixed_buffer,
  2308. size_t fixed_buffer_size);
  2309. const char *ptr() const;
  2310. size_t size() const;
  2311. bool end_with_crlf() const;
  2312. bool getline();
  2313. private:
  2314. void append(char c);
  2315. Stream &strm_;
  2316. char *fixed_buffer_;
  2317. const size_t fixed_buffer_size_;
  2318. size_t fixed_buffer_used_size_ = 0;
  2319. std::string growable_buffer_;
  2320. };
  2321. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2322. const Headers &src_headers);
  2323. struct ChunkedDecoder {
  2324. Stream &strm;
  2325. size_t chunk_remaining = 0;
  2326. bool finished = false;
  2327. char line_buf[64];
  2328. size_t last_chunk_total = 0;
  2329. size_t last_chunk_offset = 0;
  2330. explicit ChunkedDecoder(Stream &s);
  2331. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2332. size_t &out_chunk_total);
  2333. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2334. };
  2335. class mmap {
  2336. public:
  2337. mmap(const char *path);
  2338. ~mmap();
  2339. bool open(const char *path);
  2340. void close();
  2341. bool is_open() const;
  2342. size_t size() const;
  2343. const char *data() const;
  2344. private:
  2345. #if defined(_WIN32)
  2346. HANDLE hFile_ = NULL;
  2347. HANDLE hMapping_ = NULL;
  2348. #else
  2349. int fd_ = -1;
  2350. #endif
  2351. size_t size_ = 0;
  2352. void *addr_ = nullptr;
  2353. bool is_open_empty_file = false;
  2354. };
  2355. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2356. namespace fields {
  2357. bool is_token_char(char c);
  2358. bool is_token(const std::string &s);
  2359. bool is_field_name(const std::string &s);
  2360. bool is_vchar(char c);
  2361. bool is_obs_text(char c);
  2362. bool is_field_vchar(char c);
  2363. bool is_field_content(const std::string &s);
  2364. bool is_field_value(const std::string &s);
  2365. } // namespace fields
  2366. // Crypto abstraction layer
  2367. #ifdef CPPHTTPLIB_SSL_ENABLED
  2368. namespace crypto {
  2369. // Hash algorithm enumeration
  2370. enum class HashAlgorithm { MD5, SHA1, SHA256, SHA384, SHA512 };
  2371. // Compute hash of data, returns hex-encoded string
  2372. std::string hash(HashAlgorithm algo, const void *data, size_t len);
  2373. std::string hash(HashAlgorithm algo, const std::string &data);
  2374. // Compute hash of data, returns raw bytes
  2375. bool hash_raw(HashAlgorithm algo, const void *data, size_t len,
  2376. std::vector<uint8_t> &digest);
  2377. // Get digest size in bytes for algorithm
  2378. size_t hash_size(HashAlgorithm algo);
  2379. } // namespace crypto
  2380. #endif // CPPHTTPLIB_SSL_ENABLED
  2381. // TLS abstraction layer
  2382. #ifdef CPPHTTPLIB_SSL_ENABLED
  2383. namespace tls {
  2384. // Error codes for TLS operations (backend-independent)
  2385. enum class ErrorCode : int {
  2386. Success = 0,
  2387. WantRead, // Non-blocking: need to wait for read
  2388. WantWrite, // Non-blocking: need to wait for write
  2389. PeerClosed, // Peer closed the connection
  2390. Fatal, // Unrecoverable error
  2391. SyscallError, // System call error (check sys_errno)
  2392. CertVerifyFailed, // Certificate verification failed
  2393. HostnameMismatch, // Hostname verification failed
  2394. };
  2395. // TLS error information
  2396. struct TlsError {
  2397. ErrorCode code = ErrorCode::Fatal;
  2398. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  2399. int sys_errno = 0; // errno when SyscallError
  2400. };
  2401. // Opaque handles (defined as void* for abstraction)
  2402. using tls_ctx_t = void *;
  2403. using tls_session_t = void *;
  2404. using tls_cert_t = void *;
  2405. using tls_ca_store_t = void *;
  2406. // Global initialization
  2407. bool tls_global_init();
  2408. void tls_global_cleanup();
  2409. // Client context
  2410. tls_ctx_t tls_create_client_context();
  2411. void tls_free_context(tls_ctx_t ctx);
  2412. bool tls_set_min_version(tls_ctx_t ctx, int version);
  2413. bool tls_load_ca_pem(tls_ctx_t ctx, const char *pem, size_t len);
  2414. bool tls_load_ca_file(tls_ctx_t ctx, const char *file_path);
  2415. bool tls_load_ca_dir(tls_ctx_t ctx, const char *dir_path);
  2416. bool tls_load_system_certs(tls_ctx_t ctx);
  2417. bool tls_set_client_cert_pem(tls_ctx_t ctx, const char *cert, const char *key,
  2418. const char *password);
  2419. bool tls_set_client_cert_file(tls_ctx_t ctx, const char *cert_path,
  2420. const char *key_path, const char *password);
  2421. // Server context
  2422. tls_ctx_t tls_create_server_context();
  2423. bool tls_set_server_cert_pem(tls_ctx_t ctx, const char *cert, const char *key,
  2424. const char *password);
  2425. bool tls_set_server_cert_file(tls_ctx_t ctx, const char *cert_path,
  2426. const char *key_path, const char *password);
  2427. bool tls_set_client_ca_file(tls_ctx_t ctx, const char *ca_file,
  2428. const char *ca_dir);
  2429. void tls_set_verify_client(tls_ctx_t ctx, bool require);
  2430. // Session management
  2431. tls_session_t tls_create_session(tls_ctx_t ctx, socket_t sock);
  2432. void tls_free_session(tls_session_t session);
  2433. bool tls_set_sni(tls_session_t session, const char *hostname);
  2434. bool tls_set_hostname(tls_session_t session, const char *hostname);
  2435. // Handshake (non-blocking capable)
  2436. TlsError tls_connect(tls_session_t session);
  2437. TlsError tls_accept(tls_session_t session);
  2438. // Handshake with timeout (blocking until timeout)
  2439. bool tls_connect_nonblocking(tls_session_t session, socket_t sock,
  2440. time_t timeout_sec, time_t timeout_usec,
  2441. TlsError *err);
  2442. bool tls_accept_nonblocking(tls_session_t session, socket_t sock,
  2443. time_t timeout_sec, time_t timeout_usec,
  2444. TlsError *err);
  2445. // I/O (non-blocking capable)
  2446. ssize_t tls_read(tls_session_t session, void *buf, size_t len, TlsError &err);
  2447. ssize_t tls_write(tls_session_t session, const void *buf, size_t len,
  2448. TlsError &err);
  2449. int tls_pending(tls_session_t session);
  2450. void tls_shutdown(tls_session_t session, bool graceful);
  2451. // Connection state
  2452. bool tls_is_peer_closed(tls_session_t session, socket_t sock);
  2453. // Certificate verification
  2454. tls_cert_t tls_get_peer_cert(tls_session_t session);
  2455. void tls_free_cert(tls_cert_t cert);
  2456. bool tls_verify_hostname(tls_cert_t cert, const char *hostname);
  2457. long tls_get_verify_result(tls_session_t session);
  2458. // Certificate introspection
  2459. std::string tls_get_cert_subject_cn(tls_cert_t cert);
  2460. std::string tls_get_cert_issuer_name(tls_cert_t cert);
  2461. // Subject Alternative Names (SAN) entry types
  2462. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  2463. // SAN entry structure
  2464. struct TlsSanEntry {
  2465. SanType type;
  2466. std::string value;
  2467. };
  2468. // Get Subject Alternative Names from certificate
  2469. bool tls_get_cert_sans(tls_cert_t cert, std::vector<TlsSanEntry> &sans);
  2470. // Get certificate validity period (Unix timestamps)
  2471. bool tls_get_cert_validity(tls_cert_t cert, time_t &not_before,
  2472. time_t &not_after);
  2473. // Get certificate serial number as hex string
  2474. std::string tls_get_cert_serial(tls_cert_t cert);
  2475. // SNI (Server Name Indication)
  2476. // Returns the SNI hostname from the TLS session, or empty string if not set
  2477. const char *tls_get_sni(tls_session_t session);
  2478. // CA store management
  2479. tls_ca_store_t tls_create_ca_store(const char *pem, size_t len);
  2480. void tls_free_ca_store(tls_ca_store_t store);
  2481. bool tls_set_ca_store(tls_ctx_t ctx, tls_ca_store_t store);
  2482. // Get list of CA certificates from store (returns count, fills certs vector)
  2483. // Caller must call tls_free_cert() on each certificate when done
  2484. size_t tls_get_ca_certs(tls_ctx_t ctx, std::vector<tls_cert_t> &certs);
  2485. // Get list of CA subject names from context (for client certificate request)
  2486. // Returns vector of subject name strings
  2487. std::vector<std::string> tls_get_ca_names(tls_ctx_t ctx);
  2488. // Dynamic certificate update (for servers)
  2489. bool tls_update_server_cert(tls_ctx_t ctx, const char *cert_pem,
  2490. const char *key_pem, const char *password);
  2491. bool tls_update_server_client_ca(tls_ctx_t ctx, const char *ca_pem);
  2492. // Custom certificate verification callback
  2493. // Returns true to accept the certificate, false to reject
  2494. using TlsVerifyCallback =
  2495. std::function<bool(tls_session_t session, tls_cert_t peer_cert)>;
  2496. bool tls_set_verify_callback(tls_ctx_t ctx, TlsVerifyCallback callback);
  2497. // Extended verification context for detailed callback
  2498. struct TlsVerifyContext {
  2499. tls_session_t session; // TLS session handle
  2500. tls_cert_t cert; // Current certificate being verified
  2501. int depth; // Certificate chain depth (0 = leaf)
  2502. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  2503. long error_code; // Backend-specific error code (0 = no error)
  2504. const char *error_string; // Human-readable error description
  2505. };
  2506. // Extended verification callback with full context
  2507. using TlsVerifyCallbackEx = std::function<bool(const TlsVerifyContext &ctx)>;
  2508. bool tls_set_verify_callback_ex(tls_ctx_t ctx, TlsVerifyCallbackEx callback);
  2509. // Get verification error code from session (after handshake)
  2510. long tls_get_verify_error(tls_session_t session);
  2511. // Convert verification error code to string
  2512. std::string tls_verify_error_string(long error_code);
  2513. // Error information
  2514. uint64_t tls_peek_error();
  2515. uint64_t tls_get_error();
  2516. std::string tls_error_string(uint64_t code);
  2517. } // namespace tls
  2518. #endif // CPPHTTPLIB_SSL_ENABLED
  2519. } // namespace detail
  2520. namespace stream {
  2521. class Result {
  2522. public:
  2523. Result() : chunk_size_(8192) {}
  2524. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192)
  2525. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  2526. Result(Result &&other) noexcept
  2527. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  2528. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  2529. finished_(other.finished_) {
  2530. other.current_size_ = 0;
  2531. other.finished_ = true;
  2532. }
  2533. Result &operator=(Result &&other) noexcept {
  2534. if (this != &other) {
  2535. handle_ = std::move(other.handle_);
  2536. buffer_ = std::move(other.buffer_);
  2537. current_size_ = other.current_size_;
  2538. chunk_size_ = other.chunk_size_;
  2539. finished_ = other.finished_;
  2540. other.current_size_ = 0;
  2541. other.finished_ = true;
  2542. }
  2543. return *this;
  2544. }
  2545. Result(const Result &) = delete;
  2546. Result &operator=(const Result &) = delete;
  2547. // Check if the result is valid (connection succeeded and response received)
  2548. bool is_valid() const { return handle_.is_valid(); }
  2549. explicit operator bool() const { return is_valid(); }
  2550. // Response status code
  2551. int status() const {
  2552. return handle_.response ? handle_.response->status : -1;
  2553. }
  2554. // Response headers
  2555. const Headers &headers() const {
  2556. static const Headers empty_headers;
  2557. return handle_.response ? handle_.response->headers : empty_headers;
  2558. }
  2559. std::string get_header_value(const std::string &key,
  2560. const char *def = "") const {
  2561. return handle_.response ? handle_.response->get_header_value(key, def)
  2562. : def;
  2563. }
  2564. bool has_header(const std::string &key) const {
  2565. return handle_.response ? handle_.response->has_header(key) : false;
  2566. }
  2567. // Error information
  2568. Error error() const { return handle_.error; }
  2569. Error read_error() const { return handle_.get_read_error(); }
  2570. bool has_read_error() const { return handle_.has_read_error(); }
  2571. // Streaming iteration API
  2572. // Call next() to read the next chunk, then access data via data()/size()
  2573. // Returns true if data was read, false when stream is exhausted
  2574. bool next() {
  2575. if (!handle_.is_valid() || finished_) { return false; }
  2576. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  2577. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  2578. if (n > 0) {
  2579. current_size_ = static_cast<size_t>(n);
  2580. return true;
  2581. }
  2582. current_size_ = 0;
  2583. finished_ = true;
  2584. return false;
  2585. }
  2586. // Pointer to current chunk data (valid after next() returns true)
  2587. const char *data() const { return buffer_.data(); }
  2588. // Size of current chunk (valid after next() returns true)
  2589. size_t size() const { return current_size_; }
  2590. // Convenience method: read all remaining data into a string
  2591. std::string read_all() {
  2592. std::string result;
  2593. while (next()) {
  2594. result.append(data(), size());
  2595. }
  2596. return result;
  2597. }
  2598. private:
  2599. ClientImpl::StreamHandle handle_;
  2600. std::string buffer_;
  2601. size_t current_size_ = 0;
  2602. size_t chunk_size_;
  2603. bool finished_ = false;
  2604. };
  2605. // GET
  2606. template <typename ClientType>
  2607. inline Result Get(ClientType &cli, const std::string &path,
  2608. size_t chunk_size = 8192) {
  2609. return Result{cli.open_stream("GET", path), chunk_size};
  2610. }
  2611. template <typename ClientType>
  2612. inline Result Get(ClientType &cli, const std::string &path,
  2613. const Headers &headers, size_t chunk_size = 8192) {
  2614. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2615. }
  2616. template <typename ClientType>
  2617. inline Result Get(ClientType &cli, const std::string &path,
  2618. const Params &params, size_t chunk_size = 8192) {
  2619. return Result{cli.open_stream("GET", path, params), chunk_size};
  2620. }
  2621. template <typename ClientType>
  2622. inline Result Get(ClientType &cli, const std::string &path,
  2623. const Params &params, const Headers &headers,
  2624. size_t chunk_size = 8192) {
  2625. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2626. }
  2627. // POST
  2628. template <typename ClientType>
  2629. inline Result Post(ClientType &cli, const std::string &path,
  2630. const std::string &body, const std::string &content_type,
  2631. size_t chunk_size = 8192) {
  2632. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2633. chunk_size};
  2634. }
  2635. template <typename ClientType>
  2636. inline Result Post(ClientType &cli, const std::string &path,
  2637. const Headers &headers, const std::string &body,
  2638. const std::string &content_type, size_t chunk_size = 8192) {
  2639. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2640. chunk_size};
  2641. }
  2642. template <typename ClientType>
  2643. inline Result Post(ClientType &cli, const std::string &path,
  2644. const Params &params, const std::string &body,
  2645. const std::string &content_type, size_t chunk_size = 8192) {
  2646. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2647. chunk_size};
  2648. }
  2649. template <typename ClientType>
  2650. inline Result Post(ClientType &cli, const std::string &path,
  2651. const Params &params, const Headers &headers,
  2652. const std::string &body, const std::string &content_type,
  2653. size_t chunk_size = 8192) {
  2654. return Result{
  2655. cli.open_stream("POST", path, params, headers, body, content_type),
  2656. chunk_size};
  2657. }
  2658. // PUT
  2659. template <typename ClientType>
  2660. inline Result Put(ClientType &cli, const std::string &path,
  2661. const std::string &body, const std::string &content_type,
  2662. size_t chunk_size = 8192) {
  2663. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2664. chunk_size};
  2665. }
  2666. template <typename ClientType>
  2667. inline Result Put(ClientType &cli, const std::string &path,
  2668. const Headers &headers, const std::string &body,
  2669. const std::string &content_type, size_t chunk_size = 8192) {
  2670. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2671. chunk_size};
  2672. }
  2673. template <typename ClientType>
  2674. inline Result Put(ClientType &cli, const std::string &path,
  2675. const Params &params, const std::string &body,
  2676. const std::string &content_type, size_t chunk_size = 8192) {
  2677. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2678. chunk_size};
  2679. }
  2680. template <typename ClientType>
  2681. inline Result Put(ClientType &cli, const std::string &path,
  2682. const Params &params, const Headers &headers,
  2683. const std::string &body, const std::string &content_type,
  2684. size_t chunk_size = 8192) {
  2685. return Result{
  2686. cli.open_stream("PUT", path, params, headers, body, content_type),
  2687. chunk_size};
  2688. }
  2689. // PATCH
  2690. template <typename ClientType>
  2691. inline Result Patch(ClientType &cli, const std::string &path,
  2692. const std::string &body, const std::string &content_type,
  2693. size_t chunk_size = 8192) {
  2694. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2695. chunk_size};
  2696. }
  2697. template <typename ClientType>
  2698. inline Result Patch(ClientType &cli, const std::string &path,
  2699. const Headers &headers, const std::string &body,
  2700. const std::string &content_type, size_t chunk_size = 8192) {
  2701. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2702. chunk_size};
  2703. }
  2704. template <typename ClientType>
  2705. inline Result Patch(ClientType &cli, const std::string &path,
  2706. const Params &params, const std::string &body,
  2707. const std::string &content_type, size_t chunk_size = 8192) {
  2708. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2709. chunk_size};
  2710. }
  2711. template <typename ClientType>
  2712. inline Result Patch(ClientType &cli, const std::string &path,
  2713. const Params &params, const Headers &headers,
  2714. const std::string &body, const std::string &content_type,
  2715. size_t chunk_size = 8192) {
  2716. return Result{
  2717. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2718. chunk_size};
  2719. }
  2720. // DELETE
  2721. template <typename ClientType>
  2722. inline Result Delete(ClientType &cli, const std::string &path,
  2723. size_t chunk_size = 8192) {
  2724. return Result{cli.open_stream("DELETE", path), chunk_size};
  2725. }
  2726. template <typename ClientType>
  2727. inline Result Delete(ClientType &cli, const std::string &path,
  2728. const Headers &headers, size_t chunk_size = 8192) {
  2729. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2730. }
  2731. template <typename ClientType>
  2732. inline Result Delete(ClientType &cli, const std::string &path,
  2733. const std::string &body, const std::string &content_type,
  2734. size_t chunk_size = 8192) {
  2735. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2736. chunk_size};
  2737. }
  2738. template <typename ClientType>
  2739. inline Result Delete(ClientType &cli, const std::string &path,
  2740. const Headers &headers, const std::string &body,
  2741. const std::string &content_type,
  2742. size_t chunk_size = 8192) {
  2743. return Result{
  2744. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2745. chunk_size};
  2746. }
  2747. template <typename ClientType>
  2748. inline Result Delete(ClientType &cli, const std::string &path,
  2749. const Params &params, size_t chunk_size = 8192) {
  2750. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2751. }
  2752. template <typename ClientType>
  2753. inline Result Delete(ClientType &cli, const std::string &path,
  2754. const Params &params, const Headers &headers,
  2755. size_t chunk_size = 8192) {
  2756. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2757. }
  2758. template <typename ClientType>
  2759. inline Result Delete(ClientType &cli, const std::string &path,
  2760. const Params &params, const std::string &body,
  2761. const std::string &content_type,
  2762. size_t chunk_size = 8192) {
  2763. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2764. chunk_size};
  2765. }
  2766. template <typename ClientType>
  2767. inline Result Delete(ClientType &cli, const std::string &path,
  2768. const Params &params, const Headers &headers,
  2769. const std::string &body, const std::string &content_type,
  2770. size_t chunk_size = 8192) {
  2771. return Result{
  2772. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2773. chunk_size};
  2774. }
  2775. // HEAD
  2776. template <typename ClientType>
  2777. inline Result Head(ClientType &cli, const std::string &path,
  2778. size_t chunk_size = 8192) {
  2779. return Result{cli.open_stream("HEAD", path), chunk_size};
  2780. }
  2781. template <typename ClientType>
  2782. inline Result Head(ClientType &cli, const std::string &path,
  2783. const Headers &headers, size_t chunk_size = 8192) {
  2784. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2785. }
  2786. template <typename ClientType>
  2787. inline Result Head(ClientType &cli, const std::string &path,
  2788. const Params &params, size_t chunk_size = 8192) {
  2789. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2790. }
  2791. template <typename ClientType>
  2792. inline Result Head(ClientType &cli, const std::string &path,
  2793. const Params &params, const Headers &headers,
  2794. size_t chunk_size = 8192) {
  2795. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2796. }
  2797. // OPTIONS
  2798. template <typename ClientType>
  2799. inline Result Options(ClientType &cli, const std::string &path,
  2800. size_t chunk_size = 8192) {
  2801. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2802. }
  2803. template <typename ClientType>
  2804. inline Result Options(ClientType &cli, const std::string &path,
  2805. const Headers &headers, size_t chunk_size = 8192) {
  2806. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2807. }
  2808. template <typename ClientType>
  2809. inline Result Options(ClientType &cli, const std::string &path,
  2810. const Params &params, size_t chunk_size = 8192) {
  2811. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2812. }
  2813. template <typename ClientType>
  2814. inline Result Options(ClientType &cli, const std::string &path,
  2815. const Params &params, const Headers &headers,
  2816. size_t chunk_size = 8192) {
  2817. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2818. }
  2819. } // namespace stream
  2820. namespace sse {
  2821. struct SSEMessage {
  2822. std::string event; // Event type (default: "message")
  2823. std::string data; // Event payload
  2824. std::string id; // Event ID for Last-Event-ID header
  2825. SSEMessage() : event("message") {}
  2826. void clear() {
  2827. event = "message";
  2828. data.clear();
  2829. id.clear();
  2830. }
  2831. };
  2832. class SSEClient {
  2833. public:
  2834. using MessageHandler = std::function<void(const SSEMessage &)>;
  2835. using ErrorHandler = std::function<void(Error)>;
  2836. using OpenHandler = std::function<void()>;
  2837. SSEClient(Client &client, const std::string &path)
  2838. : client_(client), path_(path) {}
  2839. SSEClient(Client &client, const std::string &path, const Headers &headers)
  2840. : client_(client), path_(path), headers_(headers) {}
  2841. ~SSEClient() { stop(); }
  2842. SSEClient(const SSEClient &) = delete;
  2843. SSEClient &operator=(const SSEClient &) = delete;
  2844. // Event handlers
  2845. SSEClient &on_message(MessageHandler handler) {
  2846. on_message_ = std::move(handler);
  2847. return *this;
  2848. }
  2849. SSEClient &on_event(const std::string &type, MessageHandler handler) {
  2850. event_handlers_[type] = std::move(handler);
  2851. return *this;
  2852. }
  2853. SSEClient &on_open(OpenHandler handler) {
  2854. on_open_ = std::move(handler);
  2855. return *this;
  2856. }
  2857. SSEClient &on_error(ErrorHandler handler) {
  2858. on_error_ = std::move(handler);
  2859. return *this;
  2860. }
  2861. SSEClient &set_reconnect_interval(int ms) {
  2862. reconnect_interval_ms_ = ms;
  2863. return *this;
  2864. }
  2865. SSEClient &set_max_reconnect_attempts(int n) {
  2866. max_reconnect_attempts_ = n;
  2867. return *this;
  2868. }
  2869. // State accessors
  2870. bool is_connected() const { return connected_.load(); }
  2871. const std::string &last_event_id() const { return last_event_id_; }
  2872. // Blocking start - runs event loop with auto-reconnect
  2873. void start() {
  2874. running_.store(true);
  2875. run_event_loop();
  2876. }
  2877. // Non-blocking start - runs in background thread
  2878. void start_async() {
  2879. running_.store(true);
  2880. async_thread_ = std::thread([this]() { run_event_loop(); });
  2881. }
  2882. // Stop the client (thread-safe)
  2883. void stop() {
  2884. running_.store(false);
  2885. client_.stop(); // Cancel any pending operations
  2886. if (async_thread_.joinable()) { async_thread_.join(); }
  2887. }
  2888. private:
  2889. // Parse a single SSE field line
  2890. // Returns true if this line ends an event (blank line)
  2891. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms) {
  2892. // Blank line signals end of event
  2893. if (line.empty() || line == "\r") { return true; }
  2894. // Lines starting with ':' are comments (ignored)
  2895. if (!line.empty() && line[0] == ':') { return false; }
  2896. // Find the colon separator
  2897. auto colon_pos = line.find(':');
  2898. if (colon_pos == std::string::npos) {
  2899. // Line with no colon is treated as field name with empty value
  2900. return false;
  2901. }
  2902. auto field = line.substr(0, colon_pos);
  2903. std::string value;
  2904. // Value starts after colon, skip optional single space
  2905. if (colon_pos + 1 < line.size()) {
  2906. auto value_start = colon_pos + 1;
  2907. if (line[value_start] == ' ') { value_start++; }
  2908. value = line.substr(value_start);
  2909. // Remove trailing \r if present
  2910. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  2911. }
  2912. // Handle known fields
  2913. if (field == "event") {
  2914. msg.event = value;
  2915. } else if (field == "data") {
  2916. // Multiple data lines are concatenated with newlines
  2917. if (!msg.data.empty()) { msg.data += "\n"; }
  2918. msg.data += value;
  2919. } else if (field == "id") {
  2920. // Empty id is valid (clears the last event ID)
  2921. msg.id = value;
  2922. } else if (field == "retry") {
  2923. // Parse retry interval in milliseconds
  2924. try {
  2925. retry_ms = std::stoi(value);
  2926. } catch (...) {
  2927. // Invalid retry value, ignore
  2928. }
  2929. }
  2930. // Unknown fields are ignored per SSE spec
  2931. return false;
  2932. }
  2933. // Main event loop with auto-reconnect
  2934. void run_event_loop() {
  2935. auto reconnect_count = 0;
  2936. while (running_.load()) {
  2937. // Build headers, including Last-Event-ID if we have one
  2938. auto request_headers = headers_;
  2939. if (!last_event_id_.empty()) {
  2940. request_headers.emplace("Last-Event-ID", last_event_id_);
  2941. }
  2942. // Open streaming connection
  2943. auto result = stream::Get(client_, path_, request_headers);
  2944. // Connection error handling
  2945. if (!result) {
  2946. connected_.store(false);
  2947. if (on_error_) { on_error_(result.error()); }
  2948. if (!should_reconnect(reconnect_count)) { break; }
  2949. wait_for_reconnect();
  2950. reconnect_count++;
  2951. continue;
  2952. }
  2953. if (result.status() != 200) {
  2954. connected_.store(false);
  2955. // For certain errors, don't reconnect
  2956. if (result.status() == 204 || // No Content - server wants us to stop
  2957. result.status() == 404 || // Not Found
  2958. result.status() == 401 || // Unauthorized
  2959. result.status() == 403) { // Forbidden
  2960. if (on_error_) { on_error_(Error::Connection); }
  2961. break;
  2962. }
  2963. if (on_error_) { on_error_(Error::Connection); }
  2964. if (!should_reconnect(reconnect_count)) { break; }
  2965. wait_for_reconnect();
  2966. reconnect_count++;
  2967. continue;
  2968. }
  2969. // Connection successful
  2970. connected_.store(true);
  2971. reconnect_count = 0;
  2972. if (on_open_) { on_open_(); }
  2973. // Event receiving loop
  2974. std::string buffer;
  2975. SSEMessage current_msg;
  2976. while (running_.load() && result.next()) {
  2977. buffer.append(result.data(), result.size());
  2978. // Process complete lines in the buffer
  2979. size_t line_start = 0;
  2980. size_t newline_pos;
  2981. while ((newline_pos = buffer.find('\n', line_start)) !=
  2982. std::string::npos) {
  2983. auto line = buffer.substr(line_start, newline_pos - line_start);
  2984. line_start = newline_pos + 1;
  2985. // Parse the line and check if event is complete
  2986. auto event_complete =
  2987. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  2988. if (event_complete && !current_msg.data.empty()) {
  2989. // Update last_event_id for reconnection
  2990. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  2991. // Dispatch event to appropriate handler
  2992. dispatch_event(current_msg);
  2993. current_msg.clear();
  2994. }
  2995. }
  2996. // Keep unprocessed data in buffer
  2997. buffer.erase(0, line_start);
  2998. }
  2999. // Connection ended
  3000. connected_.store(false);
  3001. if (!running_.load()) { break; }
  3002. // Check for read errors
  3003. if (result.has_read_error()) {
  3004. if (on_error_) { on_error_(result.read_error()); }
  3005. }
  3006. if (!should_reconnect(reconnect_count)) { break; }
  3007. wait_for_reconnect();
  3008. reconnect_count++;
  3009. }
  3010. connected_.store(false);
  3011. }
  3012. // Dispatch event to appropriate handler
  3013. void dispatch_event(const SSEMessage &msg) {
  3014. // Check for specific event type handler first
  3015. auto it = event_handlers_.find(msg.event);
  3016. if (it != event_handlers_.end()) {
  3017. it->second(msg);
  3018. return;
  3019. }
  3020. // Fall back to generic message handler
  3021. if (on_message_) { on_message_(msg); }
  3022. }
  3023. // Check if we should attempt to reconnect
  3024. bool should_reconnect(int count) const {
  3025. if (!running_.load()) { return false; }
  3026. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3027. return count < max_reconnect_attempts_;
  3028. }
  3029. // Wait for reconnect interval
  3030. void wait_for_reconnect() {
  3031. // Use small increments to check running_ flag frequently
  3032. auto waited = 0;
  3033. while (running_.load() && waited < reconnect_interval_ms_) {
  3034. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3035. waited += 100;
  3036. }
  3037. }
  3038. // Client and path
  3039. Client &client_;
  3040. std::string path_;
  3041. Headers headers_;
  3042. // Callbacks
  3043. MessageHandler on_message_;
  3044. std::map<std::string, MessageHandler> event_handlers_;
  3045. OpenHandler on_open_;
  3046. ErrorHandler on_error_;
  3047. // Configuration
  3048. int reconnect_interval_ms_ = 3000;
  3049. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3050. // State
  3051. std::atomic<bool> running_{false};
  3052. std::atomic<bool> connected_{false};
  3053. std::string last_event_id_;
  3054. // Async support
  3055. std::thread async_thread_;
  3056. };
  3057. } // namespace sse
  3058. // ----------------------------------------------------------------------------
  3059. /*
  3060. * Implementation that will be part of the .cc file if split into .h + .cc.
  3061. */
  3062. namespace detail {
  3063. inline bool is_hex(char c, int &v) {
  3064. if (isdigit(c)) {
  3065. v = c - '0';
  3066. return true;
  3067. } else if ('A' <= c && c <= 'F') {
  3068. v = c - 'A' + 10;
  3069. return true;
  3070. } else if ('a' <= c && c <= 'f') {
  3071. v = c - 'a' + 10;
  3072. return true;
  3073. }
  3074. return false;
  3075. }
  3076. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3077. int &val) {
  3078. if (i >= s.size()) { return false; }
  3079. val = 0;
  3080. for (; cnt; i++, cnt--) {
  3081. if (!s[i]) { return false; }
  3082. auto v = 0;
  3083. if (is_hex(s[i], v)) {
  3084. val = val * 16 + v;
  3085. } else {
  3086. return false;
  3087. }
  3088. }
  3089. return true;
  3090. }
  3091. inline std::string from_i_to_hex(size_t n) {
  3092. static const auto charset = "0123456789abcdef";
  3093. std::string ret;
  3094. do {
  3095. ret = charset[n & 15] + ret;
  3096. n >>= 4;
  3097. } while (n > 0);
  3098. return ret;
  3099. }
  3100. inline std::string compute_etag(const FileStat &fs) {
  3101. if (!fs.is_file()) { return std::string(); }
  3102. // If mtime cannot be determined (negative value indicates an error
  3103. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3104. // value like 0 could collide with a real file that legitimately has
  3105. // mtime == 0 (epoch) and lead to misleading validators.
  3106. auto mtime_raw = fs.mtime();
  3107. if (mtime_raw < 0) { return std::string(); }
  3108. auto mtime = static_cast<size_t>(mtime_raw);
  3109. auto size = fs.size();
  3110. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3111. from_i_to_hex(size) + "\"";
  3112. }
  3113. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3114. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3115. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3116. inline std::string file_mtime_to_http_date(time_t mtime) {
  3117. if (mtime < 0) { return std::string(); }
  3118. struct tm tm_buf;
  3119. #ifdef _WIN32
  3120. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3121. #else
  3122. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3123. #endif
  3124. char buf[64];
  3125. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3126. return std::string();
  3127. }
  3128. return std::string(buf);
  3129. }
  3130. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3131. inline time_t parse_http_date(const std::string &date_str) {
  3132. struct tm tm_buf;
  3133. // Create a classic locale object once for all parsing attempts
  3134. const std::locale classic_locale = std::locale::classic();
  3135. // Try to parse using std::get_time (C++11, cross-platform)
  3136. auto try_parse = [&](const char *fmt) -> bool {
  3137. std::istringstream ss(date_str);
  3138. ss.imbue(classic_locale);
  3139. memset(&tm_buf, 0, sizeof(tm_buf));
  3140. ss >> std::get_time(&tm_buf, fmt);
  3141. return !ss.fail();
  3142. };
  3143. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3144. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3145. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3146. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3147. // asctime format: "Sun Nov 6 08:49:37 1994"
  3148. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3149. return static_cast<time_t>(-1);
  3150. }
  3151. }
  3152. }
  3153. #ifdef _WIN32
  3154. return _mkgmtime(&tm_buf);
  3155. #else
  3156. return timegm(&tm_buf);
  3157. #endif
  3158. }
  3159. inline bool is_weak_etag(const std::string &s) {
  3160. // Check if the string is a weak ETag (starts with 'W/"')
  3161. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3162. }
  3163. inline bool is_strong_etag(const std::string &s) {
  3164. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3165. // chars)
  3166. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3167. }
  3168. inline size_t to_utf8(int code, char *buff) {
  3169. if (code < 0x0080) {
  3170. buff[0] = static_cast<char>(code & 0x7F);
  3171. return 1;
  3172. } else if (code < 0x0800) {
  3173. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3174. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3175. return 2;
  3176. } else if (code < 0xD800) {
  3177. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3178. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3179. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3180. return 3;
  3181. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3182. return 0;
  3183. } else if (code < 0x10000) {
  3184. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3185. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3186. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3187. return 3;
  3188. } else if (code < 0x110000) {
  3189. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3190. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3191. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3192. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3193. return 4;
  3194. }
  3195. // NOTREACHED
  3196. return 0;
  3197. }
  3198. // NOTE: This code came up with the following stackoverflow post:
  3199. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3200. inline std::string base64_encode(const std::string &in) {
  3201. static const auto lookup =
  3202. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3203. std::string out;
  3204. out.reserve(in.size());
  3205. auto val = 0;
  3206. auto valb = -6;
  3207. for (auto c : in) {
  3208. val = (val << 8) + static_cast<uint8_t>(c);
  3209. valb += 8;
  3210. while (valb >= 0) {
  3211. out.push_back(lookup[(val >> valb) & 0x3F]);
  3212. valb -= 6;
  3213. }
  3214. }
  3215. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3216. while (out.size() % 4) {
  3217. out.push_back('=');
  3218. }
  3219. return out;
  3220. }
  3221. inline bool is_valid_path(const std::string &path) {
  3222. size_t level = 0;
  3223. size_t i = 0;
  3224. // Skip slash
  3225. while (i < path.size() && path[i] == '/') {
  3226. i++;
  3227. }
  3228. while (i < path.size()) {
  3229. // Read component
  3230. auto beg = i;
  3231. while (i < path.size() && path[i] != '/') {
  3232. if (path[i] == '\0') {
  3233. return false;
  3234. } else if (path[i] == '\\') {
  3235. return false;
  3236. }
  3237. i++;
  3238. }
  3239. auto len = i - beg;
  3240. assert(len > 0);
  3241. if (!path.compare(beg, len, ".")) {
  3242. ;
  3243. } else if (!path.compare(beg, len, "..")) {
  3244. if (level == 0) { return false; }
  3245. level--;
  3246. } else {
  3247. level++;
  3248. }
  3249. // Skip slash
  3250. while (i < path.size() && path[i] == '/') {
  3251. i++;
  3252. }
  3253. }
  3254. return true;
  3255. }
  3256. inline FileStat::FileStat(const std::string &path) {
  3257. #if defined(_WIN32)
  3258. auto wpath = u8string_to_wstring(path.c_str());
  3259. ret_ = _wstat(wpath.c_str(), &st_);
  3260. #else
  3261. ret_ = stat(path.c_str(), &st_);
  3262. #endif
  3263. }
  3264. inline bool FileStat::is_file() const {
  3265. return ret_ >= 0 && S_ISREG(st_.st_mode);
  3266. }
  3267. inline bool FileStat::is_dir() const {
  3268. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  3269. }
  3270. inline time_t FileStat::mtime() const {
  3271. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  3272. : static_cast<time_t>(-1);
  3273. }
  3274. inline size_t FileStat::size() const {
  3275. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  3276. }
  3277. inline std::string encode_path(const std::string &s) {
  3278. std::string result;
  3279. result.reserve(s.size());
  3280. for (size_t i = 0; s[i]; i++) {
  3281. switch (s[i]) {
  3282. case ' ': result += "%20"; break;
  3283. case '+': result += "%2B"; break;
  3284. case '\r': result += "%0D"; break;
  3285. case '\n': result += "%0A"; break;
  3286. case '\'': result += "%27"; break;
  3287. case ',': result += "%2C"; break;
  3288. // case ':': result += "%3A"; break; // ok? probably...
  3289. case ';': result += "%3B"; break;
  3290. default:
  3291. auto c = static_cast<uint8_t>(s[i]);
  3292. if (c >= 0x80) {
  3293. result += '%';
  3294. char hex[4];
  3295. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  3296. assert(len == 2);
  3297. result.append(hex, static_cast<size_t>(len));
  3298. } else {
  3299. result += s[i];
  3300. }
  3301. break;
  3302. }
  3303. }
  3304. return result;
  3305. }
  3306. inline std::string file_extension(const std::string &path) {
  3307. std::smatch m;
  3308. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  3309. if (std::regex_search(path, m, re)) { return m[1].str(); }
  3310. return std::string();
  3311. }
  3312. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  3313. template <typename T>
  3314. inline bool parse_header(const char *beg, const char *end, T fn);
  3315. template <typename T>
  3316. inline bool parse_header(const char *beg, const char *end, T fn) {
  3317. // Skip trailing spaces and tabs.
  3318. while (beg < end && is_space_or_tab(end[-1])) {
  3319. end--;
  3320. }
  3321. auto p = beg;
  3322. while (p < end && *p != ':') {
  3323. p++;
  3324. }
  3325. auto name = std::string(beg, p);
  3326. if (!detail::fields::is_field_name(name)) { return false; }
  3327. if (p == end) { return false; }
  3328. auto key_end = p;
  3329. if (*p++ != ':') { return false; }
  3330. while (p < end && is_space_or_tab(*p)) {
  3331. p++;
  3332. }
  3333. if (p <= end) {
  3334. auto key_len = key_end - beg;
  3335. if (!key_len) { return false; }
  3336. auto key = std::string(beg, key_end);
  3337. auto val = std::string(p, end);
  3338. if (!detail::fields::is_field_value(val)) { return false; }
  3339. if (case_ignore::equal(key, "Location") ||
  3340. case_ignore::equal(key, "Referer")) {
  3341. fn(key, val);
  3342. } else {
  3343. fn(key, decode_path_component(val));
  3344. }
  3345. return true;
  3346. }
  3347. return false;
  3348. }
  3349. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3350. const Headers &src_headers) {
  3351. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3352. // transfer coding is complete when a chunk with a chunk-size of zero is
  3353. // received, possibly followed by a trailer section, and finally terminated by
  3354. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3355. //
  3356. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3357. // doesn't care for the existence of the final CRLF. In other words, it seems
  3358. // to be ok whether the final CRLF exists or not in the chunked data.
  3359. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3360. //
  3361. // According to the reference code in RFC 9112, cpp-httplib now allows
  3362. // chunked transfer coding data without the final CRLF.
  3363. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3364. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3365. "transfer-encoding",
  3366. "content-length",
  3367. "host",
  3368. "authorization",
  3369. "www-authenticate",
  3370. "proxy-authenticate",
  3371. "proxy-authorization",
  3372. "cookie",
  3373. "set-cookie",
  3374. "cache-control",
  3375. "expect",
  3376. "max-forwards",
  3377. "pragma",
  3378. "range",
  3379. "te",
  3380. "age",
  3381. "expires",
  3382. "date",
  3383. "location",
  3384. "retry-after",
  3385. "vary",
  3386. "warning",
  3387. "content-encoding",
  3388. "content-type",
  3389. "content-range",
  3390. "trailer"};
  3391. case_ignore::unordered_set<std::string> declared_trailers;
  3392. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  3393. if (trailer_header && std::strlen(trailer_header)) {
  3394. auto len = std::strlen(trailer_header);
  3395. split(trailer_header, trailer_header + len, ',',
  3396. [&](const char *b, const char *e) {
  3397. const char *kbeg = b;
  3398. const char *kend = e;
  3399. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  3400. ++kbeg;
  3401. }
  3402. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  3403. --kend;
  3404. }
  3405. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  3406. if (!key.empty() &&
  3407. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  3408. declared_trailers.insert(key);
  3409. }
  3410. });
  3411. }
  3412. size_t trailer_header_count = 0;
  3413. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3414. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3415. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3416. constexpr auto line_terminator_len = 2;
  3417. auto line_beg = line_reader.ptr();
  3418. auto line_end =
  3419. line_reader.ptr() + line_reader.size() - line_terminator_len;
  3420. if (!parse_header(line_beg, line_end,
  3421. [&](const std::string &key, const std::string &val) {
  3422. if (declared_trailers.find(key) !=
  3423. declared_trailers.end()) {
  3424. dest.emplace(key, val);
  3425. trailer_header_count++;
  3426. }
  3427. })) {
  3428. return false;
  3429. }
  3430. if (!line_reader.getline()) { return false; }
  3431. }
  3432. return true;
  3433. }
  3434. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  3435. size_t right) {
  3436. while (b + left < e && is_space_or_tab(b[left])) {
  3437. left++;
  3438. }
  3439. while (right > 0 && is_space_or_tab(b[right - 1])) {
  3440. right--;
  3441. }
  3442. return std::make_pair(left, right);
  3443. }
  3444. inline std::string trim_copy(const std::string &s) {
  3445. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  3446. return s.substr(r.first, r.second - r.first);
  3447. }
  3448. inline std::string trim_double_quotes_copy(const std::string &s) {
  3449. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  3450. return s.substr(1, s.size() - 2);
  3451. }
  3452. return s;
  3453. }
  3454. inline void
  3455. divide(const char *data, std::size_t size, char d,
  3456. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3457. fn) {
  3458. const auto it = std::find(data, data + size, d);
  3459. const auto found = static_cast<std::size_t>(it != data + size);
  3460. const auto lhs_data = data;
  3461. const auto lhs_size = static_cast<std::size_t>(it - data);
  3462. const auto rhs_data = it + found;
  3463. const auto rhs_size = size - lhs_size - found;
  3464. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  3465. }
  3466. inline void
  3467. divide(const std::string &str, char d,
  3468. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3469. fn) {
  3470. divide(str.data(), str.size(), d, std::move(fn));
  3471. }
  3472. inline void split(const char *b, const char *e, char d,
  3473. std::function<void(const char *, const char *)> fn) {
  3474. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  3475. }
  3476. inline void split(const char *b, const char *e, char d, size_t m,
  3477. std::function<void(const char *, const char *)> fn) {
  3478. size_t i = 0;
  3479. size_t beg = 0;
  3480. size_t count = 1;
  3481. while (e ? (b + i < e) : (b[i] != '\0')) {
  3482. if (b[i] == d && count < m) {
  3483. auto r = trim(b, e, beg, i);
  3484. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3485. beg = i + 1;
  3486. count++;
  3487. }
  3488. i++;
  3489. }
  3490. if (i) {
  3491. auto r = trim(b, e, beg, i);
  3492. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3493. }
  3494. }
  3495. inline bool split_find(const char *b, const char *e, char d, size_t m,
  3496. std::function<bool(const char *, const char *)> fn) {
  3497. size_t i = 0;
  3498. size_t beg = 0;
  3499. size_t count = 1;
  3500. while (e ? (b + i < e) : (b[i] != '\0')) {
  3501. if (b[i] == d && count < m) {
  3502. auto r = trim(b, e, beg, i);
  3503. if (r.first < r.second) {
  3504. auto found = fn(&b[r.first], &b[r.second]);
  3505. if (found) { return true; }
  3506. }
  3507. beg = i + 1;
  3508. count++;
  3509. }
  3510. i++;
  3511. }
  3512. if (i) {
  3513. auto r = trim(b, e, beg, i);
  3514. if (r.first < r.second) {
  3515. auto found = fn(&b[r.first], &b[r.second]);
  3516. if (found) { return true; }
  3517. }
  3518. }
  3519. return false;
  3520. }
  3521. inline bool split_find(const char *b, const char *e, char d,
  3522. std::function<bool(const char *, const char *)> fn) {
  3523. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  3524. std::move(fn));
  3525. }
  3526. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  3527. size_t fixed_buffer_size)
  3528. : strm_(strm), fixed_buffer_(fixed_buffer),
  3529. fixed_buffer_size_(fixed_buffer_size) {}
  3530. inline const char *stream_line_reader::ptr() const {
  3531. if (growable_buffer_.empty()) {
  3532. return fixed_buffer_;
  3533. } else {
  3534. return growable_buffer_.data();
  3535. }
  3536. }
  3537. inline size_t stream_line_reader::size() const {
  3538. if (growable_buffer_.empty()) {
  3539. return fixed_buffer_used_size_;
  3540. } else {
  3541. return growable_buffer_.size();
  3542. }
  3543. }
  3544. inline bool stream_line_reader::end_with_crlf() const {
  3545. auto end = ptr() + size();
  3546. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  3547. }
  3548. inline bool stream_line_reader::getline() {
  3549. fixed_buffer_used_size_ = 0;
  3550. growable_buffer_.clear();
  3551. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3552. char prev_byte = 0;
  3553. #endif
  3554. for (size_t i = 0;; i++) {
  3555. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  3556. // Treat exceptionally long lines as an error to
  3557. // prevent infinite loops/memory exhaustion
  3558. return false;
  3559. }
  3560. char byte;
  3561. auto n = strm_.read(&byte, 1);
  3562. if (n < 0) {
  3563. return false;
  3564. } else if (n == 0) {
  3565. if (i == 0) {
  3566. return false;
  3567. } else {
  3568. break;
  3569. }
  3570. }
  3571. append(byte);
  3572. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3573. if (byte == '\n') { break; }
  3574. #else
  3575. if (prev_byte == '\r' && byte == '\n') { break; }
  3576. prev_byte = byte;
  3577. #endif
  3578. }
  3579. return true;
  3580. }
  3581. inline void stream_line_reader::append(char c) {
  3582. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  3583. fixed_buffer_[fixed_buffer_used_size_++] = c;
  3584. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  3585. } else {
  3586. if (growable_buffer_.empty()) {
  3587. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  3588. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  3589. }
  3590. growable_buffer_ += c;
  3591. }
  3592. }
  3593. inline mmap::mmap(const char *path) { open(path); }
  3594. inline mmap::~mmap() { close(); }
  3595. inline bool mmap::open(const char *path) {
  3596. close();
  3597. #if defined(_WIN32)
  3598. auto wpath = u8string_to_wstring(path);
  3599. if (wpath.empty()) { return false; }
  3600. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  3601. OPEN_EXISTING, NULL);
  3602. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  3603. LARGE_INTEGER size{};
  3604. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  3605. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  3606. // See:
  3607. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  3608. if (static_cast<ULONGLONG>(size.QuadPart) >
  3609. (std::numeric_limits<decltype(size_)>::max)()) {
  3610. // `size_t` might be 32-bits, on 32-bits Windows.
  3611. return false;
  3612. }
  3613. size_ = static_cast<size_t>(size.QuadPart);
  3614. hMapping_ =
  3615. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  3616. // Special treatment for an empty file...
  3617. if (hMapping_ == NULL && size_ == 0) {
  3618. close();
  3619. is_open_empty_file = true;
  3620. return true;
  3621. }
  3622. if (hMapping_ == NULL) {
  3623. close();
  3624. return false;
  3625. }
  3626. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  3627. if (addr_ == nullptr) {
  3628. close();
  3629. return false;
  3630. }
  3631. #else
  3632. fd_ = ::open(path, O_RDONLY);
  3633. if (fd_ == -1) { return false; }
  3634. struct stat sb;
  3635. if (fstat(fd_, &sb) == -1) {
  3636. close();
  3637. return false;
  3638. }
  3639. size_ = static_cast<size_t>(sb.st_size);
  3640. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  3641. // Special treatment for an empty file...
  3642. if (addr_ == MAP_FAILED && size_ == 0) {
  3643. close();
  3644. is_open_empty_file = true;
  3645. return false;
  3646. }
  3647. #endif
  3648. return true;
  3649. }
  3650. inline bool mmap::is_open() const {
  3651. return is_open_empty_file ? true : addr_ != nullptr;
  3652. }
  3653. inline size_t mmap::size() const { return size_; }
  3654. inline const char *mmap::data() const {
  3655. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  3656. }
  3657. inline void mmap::close() {
  3658. #if defined(_WIN32)
  3659. if (addr_) {
  3660. ::UnmapViewOfFile(addr_);
  3661. addr_ = nullptr;
  3662. }
  3663. if (hMapping_) {
  3664. ::CloseHandle(hMapping_);
  3665. hMapping_ = NULL;
  3666. }
  3667. if (hFile_ != INVALID_HANDLE_VALUE) {
  3668. ::CloseHandle(hFile_);
  3669. hFile_ = INVALID_HANDLE_VALUE;
  3670. }
  3671. is_open_empty_file = false;
  3672. #else
  3673. if (addr_ != nullptr) {
  3674. munmap(addr_, size_);
  3675. addr_ = nullptr;
  3676. }
  3677. if (fd_ != -1) {
  3678. ::close(fd_);
  3679. fd_ = -1;
  3680. }
  3681. #endif
  3682. size_ = 0;
  3683. }
  3684. inline int close_socket(socket_t sock) {
  3685. #ifdef _WIN32
  3686. return closesocket(sock);
  3687. #else
  3688. return close(sock);
  3689. #endif
  3690. }
  3691. template <typename T> inline ssize_t handle_EINTR(T fn) {
  3692. ssize_t res = 0;
  3693. while (true) {
  3694. res = fn();
  3695. if (res < 0 && errno == EINTR) {
  3696. std::this_thread::sleep_for(std::chrono::microseconds{1});
  3697. continue;
  3698. }
  3699. break;
  3700. }
  3701. return res;
  3702. }
  3703. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  3704. return handle_EINTR([&]() {
  3705. return recv(sock,
  3706. #ifdef _WIN32
  3707. static_cast<char *>(ptr), static_cast<int>(size),
  3708. #else
  3709. ptr, size,
  3710. #endif
  3711. flags);
  3712. });
  3713. }
  3714. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  3715. int flags) {
  3716. return handle_EINTR([&]() {
  3717. return send(sock,
  3718. #ifdef _WIN32
  3719. static_cast<const char *>(ptr), static_cast<int>(size),
  3720. #else
  3721. ptr, size,
  3722. #endif
  3723. flags);
  3724. });
  3725. }
  3726. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  3727. #ifdef _WIN32
  3728. return ::WSAPoll(fds, nfds, timeout);
  3729. #else
  3730. return ::poll(fds, nfds, timeout);
  3731. #endif
  3732. }
  3733. template <bool Read>
  3734. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  3735. #ifdef __APPLE__
  3736. if (sock >= FD_SETSIZE) { return -1; }
  3737. fd_set fds, *rfds, *wfds;
  3738. FD_ZERO(&fds);
  3739. FD_SET(sock, &fds);
  3740. rfds = (Read ? &fds : nullptr);
  3741. wfds = (Read ? nullptr : &fds);
  3742. timeval tv;
  3743. tv.tv_sec = static_cast<long>(sec);
  3744. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3745. return handle_EINTR([&]() {
  3746. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  3747. });
  3748. #else
  3749. struct pollfd pfd;
  3750. pfd.fd = sock;
  3751. pfd.events = (Read ? POLLIN : POLLOUT);
  3752. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3753. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  3754. #endif
  3755. }
  3756. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  3757. return select_impl<true>(sock, sec, usec);
  3758. }
  3759. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  3760. return select_impl<false>(sock, sec, usec);
  3761. }
  3762. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  3763. time_t usec) {
  3764. #ifdef __APPLE__
  3765. if (sock >= FD_SETSIZE) { return Error::Connection; }
  3766. fd_set fdsr, fdsw;
  3767. FD_ZERO(&fdsr);
  3768. FD_ZERO(&fdsw);
  3769. FD_SET(sock, &fdsr);
  3770. FD_SET(sock, &fdsw);
  3771. timeval tv;
  3772. tv.tv_sec = static_cast<long>(sec);
  3773. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3774. auto ret = handle_EINTR([&]() {
  3775. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  3776. });
  3777. if (ret == 0) { return Error::ConnectionTimeout; }
  3778. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  3779. auto error = 0;
  3780. socklen_t len = sizeof(error);
  3781. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3782. reinterpret_cast<char *>(&error), &len);
  3783. auto successful = res >= 0 && !error;
  3784. return successful ? Error::Success : Error::Connection;
  3785. }
  3786. return Error::Connection;
  3787. #else
  3788. struct pollfd pfd_read;
  3789. pfd_read.fd = sock;
  3790. pfd_read.events = POLLIN | POLLOUT;
  3791. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3792. auto poll_res =
  3793. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  3794. if (poll_res == 0) { return Error::ConnectionTimeout; }
  3795. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  3796. auto error = 0;
  3797. socklen_t len = sizeof(error);
  3798. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3799. reinterpret_cast<char *>(&error), &len);
  3800. auto successful = res >= 0 && !error;
  3801. return successful ? Error::Success : Error::Connection;
  3802. }
  3803. return Error::Connection;
  3804. #endif
  3805. }
  3806. inline bool is_socket_alive(socket_t sock) {
  3807. const auto val = detail::select_read(sock, 0, 0);
  3808. if (val == 0) {
  3809. return true;
  3810. } else if (val < 0 && errno == EBADF) {
  3811. return false;
  3812. }
  3813. char buf[1];
  3814. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  3815. }
  3816. class SocketStream final : public Stream {
  3817. public:
  3818. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3819. time_t write_timeout_sec, time_t write_timeout_usec,
  3820. time_t max_timeout_msec = 0,
  3821. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3822. (std::chrono::steady_clock::time_point::min)());
  3823. ~SocketStream() override;
  3824. bool is_readable() const override;
  3825. bool wait_readable() const override;
  3826. bool wait_writable() const override;
  3827. ssize_t read(char *ptr, size_t size) override;
  3828. ssize_t write(const char *ptr, size_t size) override;
  3829. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3830. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3831. socket_t socket() const override;
  3832. time_t duration() const override;
  3833. private:
  3834. socket_t sock_;
  3835. time_t read_timeout_sec_;
  3836. time_t read_timeout_usec_;
  3837. time_t write_timeout_sec_;
  3838. time_t write_timeout_usec_;
  3839. time_t max_timeout_msec_;
  3840. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3841. std::vector<char> read_buff_;
  3842. size_t read_buff_off_ = 0;
  3843. size_t read_buff_content_size_ = 0;
  3844. static const size_t read_buff_size_ = 1024l * 4;
  3845. };
  3846. #ifdef CPPHTTPLIB_SSL_ENABLED
  3847. class SSLSocketStream final : public Stream {
  3848. public:
  3849. SSLSocketStream(
  3850. socket_t sock, tls::tls_session_t session, time_t read_timeout_sec,
  3851. time_t read_timeout_usec, time_t write_timeout_sec,
  3852. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  3853. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3854. (std::chrono::steady_clock::time_point::min)());
  3855. ~SSLSocketStream() override;
  3856. bool is_readable() const override;
  3857. bool wait_readable() const override;
  3858. bool wait_writable() const override;
  3859. ssize_t read(char *ptr, size_t size) override;
  3860. ssize_t write(const char *ptr, size_t size) override;
  3861. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3862. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3863. socket_t socket() const override;
  3864. time_t duration() const override;
  3865. private:
  3866. socket_t sock_;
  3867. tls::tls_session_t session_;
  3868. time_t read_timeout_sec_;
  3869. time_t read_timeout_usec_;
  3870. time_t write_timeout_sec_;
  3871. time_t write_timeout_usec_;
  3872. time_t max_timeout_msec_;
  3873. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3874. };
  3875. #endif
  3876. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3877. time_t keep_alive_timeout_sec) {
  3878. using namespace std::chrono;
  3879. const auto interval_usec =
  3880. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  3881. // Avoid expensive `steady_clock::now()` call for the first time
  3882. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  3883. const auto start = steady_clock::now() - microseconds{interval_usec};
  3884. const auto timeout = seconds{keep_alive_timeout_sec};
  3885. while (true) {
  3886. if (svr_sock == INVALID_SOCKET) {
  3887. break; // Server socket is closed
  3888. }
  3889. auto val = select_read(sock, 0, interval_usec);
  3890. if (val < 0) {
  3891. break; // Ssocket error
  3892. } else if (val == 0) {
  3893. if (steady_clock::now() - start > timeout) {
  3894. break; // Timeout
  3895. }
  3896. } else {
  3897. return true; // Ready for read
  3898. }
  3899. }
  3900. return false;
  3901. }
  3902. template <typename T>
  3903. inline bool
  3904. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3905. size_t keep_alive_max_count,
  3906. time_t keep_alive_timeout_sec, T callback) {
  3907. assert(keep_alive_max_count > 0);
  3908. auto ret = false;
  3909. auto count = keep_alive_max_count;
  3910. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  3911. auto close_connection = count == 1;
  3912. auto connection_closed = false;
  3913. ret = callback(close_connection, connection_closed);
  3914. if (!ret || connection_closed) { break; }
  3915. count--;
  3916. }
  3917. return ret;
  3918. }
  3919. template <typename T>
  3920. inline bool
  3921. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3922. size_t keep_alive_max_count,
  3923. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  3924. time_t read_timeout_usec, time_t write_timeout_sec,
  3925. time_t write_timeout_usec, T callback) {
  3926. return process_server_socket_core(
  3927. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  3928. [&](bool close_connection, bool &connection_closed) {
  3929. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3930. write_timeout_sec, write_timeout_usec);
  3931. return callback(strm, close_connection, connection_closed);
  3932. });
  3933. }
  3934. inline bool process_client_socket(
  3935. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3936. time_t write_timeout_sec, time_t write_timeout_usec,
  3937. time_t max_timeout_msec,
  3938. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3939. std::function<bool(Stream &)> callback) {
  3940. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3941. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  3942. start_time);
  3943. return callback(strm);
  3944. }
  3945. inline int shutdown_socket(socket_t sock) {
  3946. #ifdef _WIN32
  3947. return shutdown(sock, SD_BOTH);
  3948. #else
  3949. return shutdown(sock, SHUT_RDWR);
  3950. #endif
  3951. }
  3952. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  3953. if (s.size() > 1 && s[0] == '\0') {
  3954. auto ret = s;
  3955. ret[0] = '@';
  3956. return ret;
  3957. }
  3958. return s;
  3959. }
  3960. inline std::string
  3961. unescape_abstract_namespace_unix_domain(const std::string &s) {
  3962. if (s.size() > 1 && s[0] == '@') {
  3963. auto ret = s;
  3964. ret[0] = '\0';
  3965. return ret;
  3966. }
  3967. return s;
  3968. }
  3969. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  3970. const struct addrinfo *hints,
  3971. struct addrinfo **res, time_t timeout_sec) {
  3972. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  3973. if (timeout_sec <= 0) {
  3974. // No timeout specified, use standard getaddrinfo
  3975. return getaddrinfo(node, service, hints, res);
  3976. }
  3977. #ifdef _WIN32
  3978. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  3979. OVERLAPPED overlapped = {0};
  3980. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  3981. if (!event) { return EAI_FAIL; }
  3982. overlapped.hEvent = event;
  3983. PADDRINFOEXW result_addrinfo = nullptr;
  3984. HANDLE cancel_handle = nullptr;
  3985. ADDRINFOEXW hints_ex = {0};
  3986. if (hints) {
  3987. hints_ex.ai_flags = hints->ai_flags;
  3988. hints_ex.ai_family = hints->ai_family;
  3989. hints_ex.ai_socktype = hints->ai_socktype;
  3990. hints_ex.ai_protocol = hints->ai_protocol;
  3991. }
  3992. auto wnode = u8string_to_wstring(node);
  3993. auto wservice = u8string_to_wstring(service);
  3994. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  3995. hints ? &hints_ex : nullptr, &result_addrinfo,
  3996. nullptr, &overlapped, nullptr, &cancel_handle);
  3997. if (ret == WSA_IO_PENDING) {
  3998. auto wait_result =
  3999. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4000. if (wait_result == WAIT_TIMEOUT) {
  4001. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4002. ::CloseHandle(event);
  4003. return EAI_AGAIN;
  4004. }
  4005. DWORD bytes_returned;
  4006. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4007. &bytes_returned, FALSE)) {
  4008. ::CloseHandle(event);
  4009. return ::WSAGetLastError();
  4010. }
  4011. }
  4012. ::CloseHandle(event);
  4013. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4014. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4015. return 0;
  4016. }
  4017. return ret;
  4018. #elif TARGET_OS_MAC
  4019. if (!node) { return EAI_NONAME; }
  4020. // macOS implementation using CFHost API for asynchronous DNS resolution
  4021. CFStringRef hostname_ref = CFStringCreateWithCString(
  4022. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4023. if (!hostname_ref) { return EAI_MEMORY; }
  4024. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4025. CFRelease(hostname_ref);
  4026. if (!host_ref) { return EAI_MEMORY; }
  4027. // Set up context for callback
  4028. struct CFHostContext {
  4029. bool completed = false;
  4030. bool success = false;
  4031. CFArrayRef addresses = nullptr;
  4032. std::mutex mutex;
  4033. std::condition_variable cv;
  4034. } context;
  4035. CFHostClientContext client_context;
  4036. memset(&client_context, 0, sizeof(client_context));
  4037. client_context.info = &context;
  4038. // Set callback
  4039. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4040. const CFStreamError *error, void *info) {
  4041. auto ctx = static_cast<CFHostContext *>(info);
  4042. std::lock_guard<std::mutex> lock(ctx->mutex);
  4043. if (error && error->error != 0) {
  4044. ctx->success = false;
  4045. } else {
  4046. Boolean hasBeenResolved;
  4047. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4048. if (ctx->addresses && hasBeenResolved) {
  4049. CFRetain(ctx->addresses);
  4050. ctx->success = true;
  4051. } else {
  4052. ctx->success = false;
  4053. }
  4054. }
  4055. ctx->completed = true;
  4056. ctx->cv.notify_one();
  4057. };
  4058. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4059. CFRelease(host_ref);
  4060. return EAI_SYSTEM;
  4061. }
  4062. // Schedule on run loop
  4063. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4064. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4065. // Start resolution
  4066. CFStreamError stream_error;
  4067. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4068. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4069. CFRelease(host_ref);
  4070. return EAI_FAIL;
  4071. }
  4072. // Wait for completion with timeout
  4073. auto timeout_time =
  4074. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4075. bool timed_out = false;
  4076. {
  4077. std::unique_lock<std::mutex> lock(context.mutex);
  4078. while (!context.completed) {
  4079. auto now = std::chrono::steady_clock::now();
  4080. if (now >= timeout_time) {
  4081. timed_out = true;
  4082. break;
  4083. }
  4084. // Run the runloop for a short time
  4085. lock.unlock();
  4086. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4087. lock.lock();
  4088. }
  4089. }
  4090. // Clean up
  4091. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4092. CFHostSetClient(host_ref, nullptr, nullptr);
  4093. if (timed_out || !context.completed) {
  4094. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4095. CFRelease(host_ref);
  4096. return EAI_AGAIN;
  4097. }
  4098. if (!context.success || !context.addresses) {
  4099. CFRelease(host_ref);
  4100. return EAI_NODATA;
  4101. }
  4102. // Convert CFArray to addrinfo
  4103. CFIndex count = CFArrayGetCount(context.addresses);
  4104. if (count == 0) {
  4105. CFRelease(context.addresses);
  4106. CFRelease(host_ref);
  4107. return EAI_NODATA;
  4108. }
  4109. struct addrinfo *result_addrinfo = nullptr;
  4110. struct addrinfo **current = &result_addrinfo;
  4111. for (CFIndex i = 0; i < count; i++) {
  4112. CFDataRef addr_data =
  4113. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4114. if (!addr_data) continue;
  4115. const struct sockaddr *sockaddr_ptr =
  4116. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4117. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4118. // Allocate addrinfo structure
  4119. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4120. if (!*current) {
  4121. freeaddrinfo(result_addrinfo);
  4122. CFRelease(context.addresses);
  4123. CFRelease(host_ref);
  4124. return EAI_MEMORY;
  4125. }
  4126. memset(*current, 0, sizeof(struct addrinfo));
  4127. // Set up addrinfo fields
  4128. (*current)->ai_family = sockaddr_ptr->sa_family;
  4129. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4130. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4131. (*current)->ai_addrlen = sockaddr_len;
  4132. // Copy sockaddr
  4133. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4134. if (!(*current)->ai_addr) {
  4135. freeaddrinfo(result_addrinfo);
  4136. CFRelease(context.addresses);
  4137. CFRelease(host_ref);
  4138. return EAI_MEMORY;
  4139. }
  4140. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4141. // Set port if service is specified
  4142. if (service && strlen(service) > 0) {
  4143. int port = atoi(service);
  4144. if (port > 0) {
  4145. if (sockaddr_ptr->sa_family == AF_INET) {
  4146. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4147. ->sin_port = htons(static_cast<uint16_t>(port));
  4148. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4149. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4150. ->sin6_port = htons(static_cast<uint16_t>(port));
  4151. }
  4152. }
  4153. }
  4154. current = &((*current)->ai_next);
  4155. }
  4156. CFRelease(context.addresses);
  4157. CFRelease(host_ref);
  4158. *res = result_addrinfo;
  4159. return 0;
  4160. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  4161. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  4162. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  4163. struct gaicb request;
  4164. struct gaicb *requests[1] = {&request};
  4165. struct sigevent sevp;
  4166. struct timespec timeout;
  4167. // Initialize the request structure
  4168. memset(&request, 0, sizeof(request));
  4169. request.ar_name = node;
  4170. request.ar_service = service;
  4171. request.ar_request = hints;
  4172. // Set up timeout
  4173. timeout.tv_sec = timeout_sec;
  4174. timeout.tv_nsec = 0;
  4175. // Initialize sigevent structure (not used, but required)
  4176. memset(&sevp, 0, sizeof(sevp));
  4177. sevp.sigev_notify = SIGEV_NONE;
  4178. // Start asynchronous resolution
  4179. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  4180. if (start_result != 0) { return start_result; }
  4181. // Wait for completion with timeout
  4182. int wait_result =
  4183. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  4184. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  4185. // Completed successfully, get the result
  4186. int gai_result = gai_error(&request);
  4187. if (gai_result == 0) {
  4188. *res = request.ar_result;
  4189. return 0;
  4190. } else {
  4191. // Clean up on error
  4192. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  4193. return gai_result;
  4194. }
  4195. } else if (wait_result == EAI_AGAIN) {
  4196. // Timeout occurred, cancel the request
  4197. gai_cancel(&request);
  4198. return EAI_AGAIN;
  4199. } else {
  4200. // Other error occurred
  4201. gai_cancel(&request);
  4202. return wait_result;
  4203. }
  4204. #else
  4205. // Fallback implementation using thread-based timeout for other Unix systems
  4206. struct GetAddrInfoState {
  4207. ~GetAddrInfoState() {
  4208. if (info) { freeaddrinfo(info); }
  4209. }
  4210. std::mutex mutex;
  4211. std::condition_variable result_cv;
  4212. bool completed = false;
  4213. int result = EAI_SYSTEM;
  4214. std::string node;
  4215. std::string service;
  4216. struct addrinfo hints;
  4217. struct addrinfo *info = nullptr;
  4218. };
  4219. // Allocate on the heap, so the resolver thread can keep using the data.
  4220. auto state = std::make_shared<GetAddrInfoState>();
  4221. if (node) { state->node = node; }
  4222. state->service = service;
  4223. state->hints = *hints;
  4224. std::thread resolve_thread([state]() {
  4225. auto thread_result =
  4226. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4227. &state->info);
  4228. std::lock_guard<std::mutex> lock(state->mutex);
  4229. state->result = thread_result;
  4230. state->completed = true;
  4231. state->result_cv.notify_one();
  4232. });
  4233. // Wait for completion or timeout
  4234. std::unique_lock<std::mutex> lock(state->mutex);
  4235. auto finished =
  4236. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4237. [&] { return state->completed; });
  4238. if (finished) {
  4239. // Operation completed within timeout
  4240. resolve_thread.join();
  4241. *res = state->info;
  4242. state->info = nullptr; // Pass ownership to caller
  4243. return state->result;
  4244. } else {
  4245. // Timeout occurred
  4246. resolve_thread.detach(); // Let the thread finish in background
  4247. return EAI_AGAIN; // Return timeout error
  4248. }
  4249. #endif
  4250. #else
  4251. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4252. return getaddrinfo(node, service, hints, res);
  4253. #endif
  4254. }
  4255. template <typename BindOrConnect>
  4256. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4257. int address_family, int socket_flags, bool tcp_nodelay,
  4258. bool ipv6_v6only, SocketOptions socket_options,
  4259. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4260. // Get address info
  4261. const char *node = nullptr;
  4262. struct addrinfo hints;
  4263. struct addrinfo *result;
  4264. memset(&hints, 0, sizeof(struct addrinfo));
  4265. hints.ai_socktype = SOCK_STREAM;
  4266. hints.ai_protocol = IPPROTO_IP;
  4267. if (!ip.empty()) {
  4268. node = ip.c_str();
  4269. // Ask getaddrinfo to convert IP in c-string to address
  4270. hints.ai_family = AF_UNSPEC;
  4271. hints.ai_flags = AI_NUMERICHOST;
  4272. } else {
  4273. if (!host.empty()) { node = host.c_str(); }
  4274. hints.ai_family = address_family;
  4275. hints.ai_flags = socket_flags;
  4276. }
  4277. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  4278. if (hints.ai_family == AF_UNIX) {
  4279. const auto addrlen = host.length();
  4280. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  4281. #ifdef SOCK_CLOEXEC
  4282. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  4283. hints.ai_protocol);
  4284. #else
  4285. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4286. #endif
  4287. if (sock != INVALID_SOCKET) {
  4288. sockaddr_un addr{};
  4289. addr.sun_family = AF_UNIX;
  4290. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  4291. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  4292. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  4293. hints.ai_addrlen = static_cast<socklen_t>(
  4294. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  4295. #ifndef SOCK_CLOEXEC
  4296. #ifndef _WIN32
  4297. fcntl(sock, F_SETFD, FD_CLOEXEC);
  4298. #endif
  4299. #endif
  4300. if (socket_options) { socket_options(sock); }
  4301. #ifdef _WIN32
  4302. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  4303. // remove the option.
  4304. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  4305. #endif
  4306. bool dummy;
  4307. if (!bind_or_connect(sock, hints, dummy)) {
  4308. close_socket(sock);
  4309. sock = INVALID_SOCKET;
  4310. }
  4311. }
  4312. return sock;
  4313. }
  4314. #endif
  4315. auto service = std::to_string(port);
  4316. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  4317. timeout_sec)) {
  4318. #if defined __linux__ && !defined __ANDROID__
  4319. res_init();
  4320. #endif
  4321. return INVALID_SOCKET;
  4322. }
  4323. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4324. for (auto rp = result; rp; rp = rp->ai_next) {
  4325. // Create a socket
  4326. #ifdef _WIN32
  4327. auto sock =
  4328. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  4329. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  4330. /**
  4331. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  4332. * and above the socket creation fails on older Windows Systems.
  4333. *
  4334. * Let's try to create a socket the old way in this case.
  4335. *
  4336. * Reference:
  4337. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  4338. *
  4339. * WSA_FLAG_NO_HANDLE_INHERIT:
  4340. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  4341. * SP1, and later
  4342. *
  4343. */
  4344. if (sock == INVALID_SOCKET) {
  4345. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4346. }
  4347. #else
  4348. #ifdef SOCK_CLOEXEC
  4349. auto sock =
  4350. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  4351. #else
  4352. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4353. #endif
  4354. #endif
  4355. if (sock == INVALID_SOCKET) { continue; }
  4356. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  4357. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  4358. close_socket(sock);
  4359. continue;
  4360. }
  4361. #endif
  4362. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  4363. if (rp->ai_family == AF_INET6) {
  4364. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  4365. }
  4366. if (socket_options) { socket_options(sock); }
  4367. // bind or connect
  4368. auto quit = false;
  4369. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  4370. close_socket(sock);
  4371. if (quit) { break; }
  4372. }
  4373. return INVALID_SOCKET;
  4374. }
  4375. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  4376. #ifdef _WIN32
  4377. auto flags = nonblocking ? 1UL : 0UL;
  4378. ioctlsocket(sock, FIONBIO, &flags);
  4379. #else
  4380. auto flags = fcntl(sock, F_GETFL, 0);
  4381. fcntl(sock, F_SETFL,
  4382. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  4383. #endif
  4384. }
  4385. inline bool is_connection_error() {
  4386. #ifdef _WIN32
  4387. return WSAGetLastError() != WSAEWOULDBLOCK;
  4388. #else
  4389. return errno != EINPROGRESS;
  4390. #endif
  4391. }
  4392. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  4393. struct addrinfo hints;
  4394. struct addrinfo *result;
  4395. memset(&hints, 0, sizeof(struct addrinfo));
  4396. hints.ai_family = AF_UNSPEC;
  4397. hints.ai_socktype = SOCK_STREAM;
  4398. hints.ai_protocol = 0;
  4399. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  4400. return false;
  4401. }
  4402. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4403. auto ret = false;
  4404. for (auto rp = result; rp; rp = rp->ai_next) {
  4405. const auto &ai = *rp;
  4406. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4407. ret = true;
  4408. break;
  4409. }
  4410. }
  4411. return ret;
  4412. }
  4413. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  4414. #define USE_IF2IP
  4415. #endif
  4416. #ifdef USE_IF2IP
  4417. inline std::string if2ip(int address_family, const std::string &ifn) {
  4418. struct ifaddrs *ifap;
  4419. getifaddrs(&ifap);
  4420. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  4421. std::string addr_candidate;
  4422. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  4423. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  4424. (AF_UNSPEC == address_family ||
  4425. ifa->ifa_addr->sa_family == address_family)) {
  4426. if (ifa->ifa_addr->sa_family == AF_INET) {
  4427. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  4428. char buf[INET_ADDRSTRLEN];
  4429. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  4430. return std::string(buf, INET_ADDRSTRLEN);
  4431. }
  4432. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  4433. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  4434. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  4435. char buf[INET6_ADDRSTRLEN] = {};
  4436. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  4437. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  4438. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  4439. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  4440. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  4441. } else {
  4442. return std::string(buf, INET6_ADDRSTRLEN);
  4443. }
  4444. }
  4445. }
  4446. }
  4447. }
  4448. }
  4449. return addr_candidate;
  4450. }
  4451. #endif
  4452. inline socket_t create_client_socket(
  4453. const std::string &host, const std::string &ip, int port,
  4454. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  4455. SocketOptions socket_options, time_t connection_timeout_sec,
  4456. time_t connection_timeout_usec, time_t read_timeout_sec,
  4457. time_t read_timeout_usec, time_t write_timeout_sec,
  4458. time_t write_timeout_usec, const std::string &intf, Error &error) {
  4459. auto sock = create_socket(
  4460. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  4461. std::move(socket_options),
  4462. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  4463. if (!intf.empty()) {
  4464. #ifdef USE_IF2IP
  4465. auto ip_from_if = if2ip(address_family, intf);
  4466. if (ip_from_if.empty()) { ip_from_if = intf; }
  4467. if (!bind_ip_address(sock2, ip_from_if)) {
  4468. error = Error::BindIPAddress;
  4469. return false;
  4470. }
  4471. #endif
  4472. }
  4473. set_nonblocking(sock2, true);
  4474. auto ret =
  4475. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  4476. if (ret < 0) {
  4477. if (is_connection_error()) {
  4478. error = Error::Connection;
  4479. return false;
  4480. }
  4481. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  4482. connection_timeout_usec);
  4483. if (error != Error::Success) {
  4484. if (error == Error::ConnectionTimeout) { quit = true; }
  4485. return false;
  4486. }
  4487. }
  4488. set_nonblocking(sock2, false);
  4489. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  4490. read_timeout_usec);
  4491. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  4492. write_timeout_usec);
  4493. error = Error::Success;
  4494. return true;
  4495. },
  4496. connection_timeout_sec); // Pass DNS timeout
  4497. if (sock != INVALID_SOCKET) {
  4498. error = Error::Success;
  4499. } else {
  4500. if (error == Error::Success) { error = Error::Connection; }
  4501. }
  4502. return sock;
  4503. }
  4504. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  4505. socklen_t addr_len, std::string &ip, int &port) {
  4506. if (addr.ss_family == AF_INET) {
  4507. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  4508. } else if (addr.ss_family == AF_INET6) {
  4509. port =
  4510. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  4511. } else {
  4512. return false;
  4513. }
  4514. std::array<char, NI_MAXHOST> ipstr{};
  4515. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  4516. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  4517. 0, NI_NUMERICHOST)) {
  4518. return false;
  4519. }
  4520. ip = ipstr.data();
  4521. return true;
  4522. }
  4523. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4524. struct sockaddr_storage addr;
  4525. socklen_t addr_len = sizeof(addr);
  4526. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4527. &addr_len)) {
  4528. get_ip_and_port(addr, addr_len, ip, port);
  4529. }
  4530. }
  4531. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4532. struct sockaddr_storage addr;
  4533. socklen_t addr_len = sizeof(addr);
  4534. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4535. &addr_len)) {
  4536. #ifndef _WIN32
  4537. if (addr.ss_family == AF_UNIX) {
  4538. #if defined(__linux__)
  4539. struct ucred ucred;
  4540. socklen_t len = sizeof(ucred);
  4541. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  4542. port = ucred.pid;
  4543. }
  4544. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  4545. pid_t pid;
  4546. socklen_t len = sizeof(pid);
  4547. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  4548. port = pid;
  4549. }
  4550. #endif
  4551. return;
  4552. }
  4553. #endif
  4554. get_ip_and_port(addr, addr_len, ip, port);
  4555. }
  4556. }
  4557. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  4558. unsigned int h) {
  4559. return (l == 0)
  4560. ? h
  4561. : str2tag_core(
  4562. s + 1, l - 1,
  4563. // Unsets the 6 high bits of h, therefore no overflow happens
  4564. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  4565. h * 33) ^
  4566. static_cast<unsigned char>(*s));
  4567. }
  4568. inline unsigned int str2tag(const std::string &s) {
  4569. return str2tag_core(s.data(), s.size(), 0);
  4570. }
  4571. namespace udl {
  4572. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  4573. return str2tag_core(s, l, 0);
  4574. }
  4575. } // namespace udl
  4576. inline std::string
  4577. find_content_type(const std::string &path,
  4578. const std::map<std::string, std::string> &user_data,
  4579. const std::string &default_content_type) {
  4580. auto ext = file_extension(path);
  4581. auto it = user_data.find(ext);
  4582. if (it != user_data.end()) { return it->second; }
  4583. using udl::operator""_t;
  4584. switch (str2tag(ext)) {
  4585. default: return default_content_type;
  4586. case "css"_t: return "text/css";
  4587. case "csv"_t: return "text/csv";
  4588. case "htm"_t:
  4589. case "html"_t: return "text/html";
  4590. case "js"_t:
  4591. case "mjs"_t: return "text/javascript";
  4592. case "txt"_t: return "text/plain";
  4593. case "vtt"_t: return "text/vtt";
  4594. case "apng"_t: return "image/apng";
  4595. case "avif"_t: return "image/avif";
  4596. case "bmp"_t: return "image/bmp";
  4597. case "gif"_t: return "image/gif";
  4598. case "png"_t: return "image/png";
  4599. case "svg"_t: return "image/svg+xml";
  4600. case "webp"_t: return "image/webp";
  4601. case "ico"_t: return "image/x-icon";
  4602. case "tif"_t: return "image/tiff";
  4603. case "tiff"_t: return "image/tiff";
  4604. case "jpg"_t:
  4605. case "jpeg"_t: return "image/jpeg";
  4606. case "mp4"_t: return "video/mp4";
  4607. case "mpeg"_t: return "video/mpeg";
  4608. case "webm"_t: return "video/webm";
  4609. case "mp3"_t: return "audio/mp3";
  4610. case "mpga"_t: return "audio/mpeg";
  4611. case "weba"_t: return "audio/webm";
  4612. case "wav"_t: return "audio/wave";
  4613. case "otf"_t: return "font/otf";
  4614. case "ttf"_t: return "font/ttf";
  4615. case "woff"_t: return "font/woff";
  4616. case "woff2"_t: return "font/woff2";
  4617. case "7z"_t: return "application/x-7z-compressed";
  4618. case "atom"_t: return "application/atom+xml";
  4619. case "pdf"_t: return "application/pdf";
  4620. case "json"_t: return "application/json";
  4621. case "rss"_t: return "application/rss+xml";
  4622. case "tar"_t: return "application/x-tar";
  4623. case "xht"_t:
  4624. case "xhtml"_t: return "application/xhtml+xml";
  4625. case "xslt"_t: return "application/xslt+xml";
  4626. case "xml"_t: return "application/xml";
  4627. case "gz"_t: return "application/gzip";
  4628. case "zip"_t: return "application/zip";
  4629. case "wasm"_t: return "application/wasm";
  4630. }
  4631. }
  4632. inline bool can_compress_content_type(const std::string &content_type) {
  4633. using udl::operator""_t;
  4634. auto tag = str2tag(content_type);
  4635. switch (tag) {
  4636. case "image/svg+xml"_t:
  4637. case "application/javascript"_t:
  4638. case "application/json"_t:
  4639. case "application/xml"_t:
  4640. case "application/protobuf"_t:
  4641. case "application/xhtml+xml"_t: return true;
  4642. case "text/event-stream"_t: return false;
  4643. default: return !content_type.rfind("text/", 0);
  4644. }
  4645. }
  4646. inline EncodingType encoding_type(const Request &req, const Response &res) {
  4647. auto ret =
  4648. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  4649. if (!ret) { return EncodingType::None; }
  4650. const auto &s = req.get_header_value("Accept-Encoding");
  4651. (void)(s);
  4652. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4653. // TODO: 'Accept-Encoding' has br, not br;q=0
  4654. ret = s.find("br") != std::string::npos;
  4655. if (ret) { return EncodingType::Brotli; }
  4656. #endif
  4657. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4658. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  4659. ret = s.find("gzip") != std::string::npos;
  4660. if (ret) { return EncodingType::Gzip; }
  4661. #endif
  4662. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4663. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  4664. ret = s.find("zstd") != std::string::npos;
  4665. if (ret) { return EncodingType::Zstd; }
  4666. #endif
  4667. return EncodingType::None;
  4668. }
  4669. inline bool nocompressor::compress(const char *data, size_t data_length,
  4670. bool /*last*/, Callback callback) {
  4671. if (!data_length) { return true; }
  4672. return callback(data, data_length);
  4673. }
  4674. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4675. inline gzip_compressor::gzip_compressor() {
  4676. std::memset(&strm_, 0, sizeof(strm_));
  4677. strm_.zalloc = Z_NULL;
  4678. strm_.zfree = Z_NULL;
  4679. strm_.opaque = Z_NULL;
  4680. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  4681. Z_DEFAULT_STRATEGY) == Z_OK;
  4682. }
  4683. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  4684. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  4685. bool last, Callback callback) {
  4686. assert(is_valid_);
  4687. do {
  4688. constexpr size_t max_avail_in =
  4689. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4690. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4691. (std::min)(data_length, max_avail_in));
  4692. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4693. data_length -= strm_.avail_in;
  4694. data += strm_.avail_in;
  4695. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  4696. auto ret = Z_OK;
  4697. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4698. do {
  4699. strm_.avail_out = static_cast<uInt>(buff.size());
  4700. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4701. ret = deflate(&strm_, flush);
  4702. if (ret == Z_STREAM_ERROR) { return false; }
  4703. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4704. return false;
  4705. }
  4706. } while (strm_.avail_out == 0);
  4707. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  4708. (flush == Z_NO_FLUSH && ret == Z_OK));
  4709. assert(strm_.avail_in == 0);
  4710. } while (data_length > 0);
  4711. return true;
  4712. }
  4713. inline gzip_decompressor::gzip_decompressor() {
  4714. std::memset(&strm_, 0, sizeof(strm_));
  4715. strm_.zalloc = Z_NULL;
  4716. strm_.zfree = Z_NULL;
  4717. strm_.opaque = Z_NULL;
  4718. // 15 is the value of wbits, which should be at the maximum possible value
  4719. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  4720. // that the stream type should be automatically detected either gzip or
  4721. // deflate.
  4722. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  4723. }
  4724. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  4725. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  4726. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  4727. Callback callback) {
  4728. assert(is_valid_);
  4729. auto ret = Z_OK;
  4730. do {
  4731. constexpr size_t max_avail_in =
  4732. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4733. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4734. (std::min)(data_length, max_avail_in));
  4735. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4736. data_length -= strm_.avail_in;
  4737. data += strm_.avail_in;
  4738. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4739. while (strm_.avail_in > 0 && ret == Z_OK) {
  4740. strm_.avail_out = static_cast<uInt>(buff.size());
  4741. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4742. ret = inflate(&strm_, Z_NO_FLUSH);
  4743. assert(ret != Z_STREAM_ERROR);
  4744. switch (ret) {
  4745. case Z_NEED_DICT:
  4746. case Z_DATA_ERROR:
  4747. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  4748. }
  4749. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4750. return false;
  4751. }
  4752. }
  4753. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  4754. } while (data_length > 0);
  4755. return true;
  4756. }
  4757. #endif
  4758. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4759. inline brotli_compressor::brotli_compressor() {
  4760. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  4761. }
  4762. inline brotli_compressor::~brotli_compressor() {
  4763. BrotliEncoderDestroyInstance(state_);
  4764. }
  4765. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  4766. bool last, Callback callback) {
  4767. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4768. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  4769. auto available_in = data_length;
  4770. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4771. for (;;) {
  4772. if (last) {
  4773. if (BrotliEncoderIsFinished(state_)) { break; }
  4774. } else {
  4775. if (!available_in) { break; }
  4776. }
  4777. auto available_out = buff.size();
  4778. auto next_out = buff.data();
  4779. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  4780. &available_out, &next_out, nullptr)) {
  4781. return false;
  4782. }
  4783. auto output_bytes = buff.size() - available_out;
  4784. if (output_bytes) {
  4785. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  4786. }
  4787. }
  4788. return true;
  4789. }
  4790. inline brotli_decompressor::brotli_decompressor() {
  4791. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  4792. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  4793. : BROTLI_DECODER_RESULT_ERROR;
  4794. }
  4795. inline brotli_decompressor::~brotli_decompressor() {
  4796. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  4797. }
  4798. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  4799. inline bool brotli_decompressor::decompress(const char *data,
  4800. size_t data_length,
  4801. Callback callback) {
  4802. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4803. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  4804. return 0;
  4805. }
  4806. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4807. size_t avail_in = data_length;
  4808. size_t total_out;
  4809. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  4810. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4811. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  4812. char *next_out = buff.data();
  4813. size_t avail_out = buff.size();
  4814. decoder_r = BrotliDecoderDecompressStream(
  4815. decoder_s, &avail_in, &next_in, &avail_out,
  4816. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  4817. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  4818. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  4819. }
  4820. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4821. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  4822. }
  4823. #endif
  4824. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4825. inline zstd_compressor::zstd_compressor() {
  4826. ctx_ = ZSTD_createCCtx();
  4827. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  4828. }
  4829. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  4830. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  4831. bool last, Callback callback) {
  4832. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4833. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  4834. ZSTD_inBuffer input = {data, data_length, 0};
  4835. bool finished;
  4836. do {
  4837. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4838. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  4839. if (ZSTD_isError(remaining)) { return false; }
  4840. if (!callback(buff.data(), output.pos)) { return false; }
  4841. finished = last ? (remaining == 0) : (input.pos == input.size);
  4842. } while (!finished);
  4843. return true;
  4844. }
  4845. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  4846. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  4847. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  4848. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  4849. Callback callback) {
  4850. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4851. ZSTD_inBuffer input = {data, data_length, 0};
  4852. while (input.pos < input.size) {
  4853. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4854. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  4855. if (ZSTD_isError(remaining)) { return false; }
  4856. if (!callback(buff.data(), output.pos)) { return false; }
  4857. }
  4858. return true;
  4859. }
  4860. #endif
  4861. inline std::unique_ptr<decompressor>
  4862. create_decompressor(const std::string &encoding) {
  4863. std::unique_ptr<decompressor> decompressor;
  4864. if (encoding == "gzip" || encoding == "deflate") {
  4865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4866. decompressor = detail::make_unique<gzip_decompressor>();
  4867. #endif
  4868. } else if (encoding.find("br") != std::string::npos) {
  4869. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4870. decompressor = detail::make_unique<brotli_decompressor>();
  4871. #endif
  4872. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  4873. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4874. decompressor = detail::make_unique<zstd_decompressor>();
  4875. #endif
  4876. }
  4877. return decompressor;
  4878. }
  4879. inline bool is_prohibited_header_name(const std::string &name) {
  4880. using udl::operator""_t;
  4881. switch (str2tag(name)) {
  4882. case "REMOTE_ADDR"_t:
  4883. case "REMOTE_PORT"_t:
  4884. case "LOCAL_ADDR"_t:
  4885. case "LOCAL_PORT"_t: return true;
  4886. default: return false;
  4887. }
  4888. }
  4889. inline bool has_header(const Headers &headers, const std::string &key) {
  4890. if (is_prohibited_header_name(key)) { return false; }
  4891. return headers.find(key) != headers.end();
  4892. }
  4893. inline const char *get_header_value(const Headers &headers,
  4894. const std::string &key, const char *def,
  4895. size_t id) {
  4896. if (is_prohibited_header_name(key)) {
  4897. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4898. std::string msg = "Prohibited header name '" + key + "' is specified.";
  4899. throw std::invalid_argument(msg);
  4900. #else
  4901. return "";
  4902. #endif
  4903. }
  4904. auto rng = headers.equal_range(key);
  4905. auto it = rng.first;
  4906. std::advance(it, static_cast<ssize_t>(id));
  4907. if (it != rng.second) { return it->second.c_str(); }
  4908. return def;
  4909. }
  4910. inline bool read_headers(Stream &strm, Headers &headers) {
  4911. const auto bufsiz = 2048;
  4912. char buf[bufsiz];
  4913. stream_line_reader line_reader(strm, buf, bufsiz);
  4914. size_t header_count = 0;
  4915. for (;;) {
  4916. if (!line_reader.getline()) { return false; }
  4917. // Check if the line ends with CRLF.
  4918. auto line_terminator_len = 2;
  4919. if (line_reader.end_with_crlf()) {
  4920. // Blank line indicates end of headers.
  4921. if (line_reader.size() == 2) { break; }
  4922. } else {
  4923. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4924. // Blank line indicates end of headers.
  4925. if (line_reader.size() == 1) { break; }
  4926. line_terminator_len = 1;
  4927. #else
  4928. continue; // Skip invalid line.
  4929. #endif
  4930. }
  4931. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4932. // Check header count limit
  4933. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4934. // Exclude line terminator
  4935. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  4936. if (!parse_header(line_reader.ptr(), end,
  4937. [&](const std::string &key, const std::string &val) {
  4938. headers.emplace(key, val);
  4939. })) {
  4940. return false;
  4941. }
  4942. header_count++;
  4943. }
  4944. return true;
  4945. }
  4946. inline bool read_content_with_length(Stream &strm, size_t len,
  4947. DownloadProgress progress,
  4948. ContentReceiverWithProgress out) {
  4949. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4950. detail::BodyReader br;
  4951. br.stream = &strm;
  4952. br.content_length = len;
  4953. br.chunked = false;
  4954. br.bytes_read = 0;
  4955. br.last_error = Error::Success;
  4956. size_t r = 0;
  4957. while (r < len) {
  4958. auto read_len = static_cast<size_t>(len - r);
  4959. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  4960. auto n = detail::read_body_content(&strm, br, buf, to_read);
  4961. if (n <= 0) { return false; }
  4962. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  4963. r += static_cast<size_t>(n);
  4964. if (progress) {
  4965. if (!progress(r, len)) { return false; }
  4966. }
  4967. }
  4968. return true;
  4969. }
  4970. inline void skip_content_with_length(Stream &strm, size_t len) {
  4971. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4972. size_t r = 0;
  4973. while (r < len) {
  4974. auto read_len = static_cast<size_t>(len - r);
  4975. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  4976. if (n <= 0) { return; }
  4977. r += static_cast<size_t>(n);
  4978. }
  4979. }
  4980. enum class ReadContentResult {
  4981. Success, // Successfully read the content
  4982. PayloadTooLarge, // The content exceeds the specified payload limit
  4983. Error // An error occurred while reading the content
  4984. };
  4985. inline ReadContentResult
  4986. read_content_without_length(Stream &strm, size_t payload_max_length,
  4987. ContentReceiverWithProgress out) {
  4988. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4989. size_t r = 0;
  4990. for (;;) {
  4991. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  4992. if (n == 0) { return ReadContentResult::Success; }
  4993. if (n < 0) { return ReadContentResult::Error; }
  4994. // Check if adding this data would exceed the payload limit
  4995. if (r > payload_max_length ||
  4996. payload_max_length - r < static_cast<size_t>(n)) {
  4997. return ReadContentResult::PayloadTooLarge;
  4998. }
  4999. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  5000. return ReadContentResult::Error;
  5001. }
  5002. r += static_cast<size_t>(n);
  5003. }
  5004. return ReadContentResult::Success;
  5005. }
  5006. template <typename T>
  5007. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  5008. size_t payload_max_length,
  5009. ContentReceiverWithProgress out) {
  5010. detail::ChunkedDecoder dec(strm);
  5011. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5012. size_t total_len = 0;
  5013. for (;;) {
  5014. size_t chunk_offset = 0;
  5015. size_t chunk_total = 0;
  5016. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  5017. if (n < 0) { return ReadContentResult::Error; }
  5018. if (n == 0) {
  5019. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  5020. return ReadContentResult::Error;
  5021. }
  5022. return ReadContentResult::Success;
  5023. }
  5024. if (total_len > payload_max_length ||
  5025. payload_max_length - total_len < static_cast<size_t>(n)) {
  5026. return ReadContentResult::PayloadTooLarge;
  5027. }
  5028. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  5029. return ReadContentResult::Error;
  5030. }
  5031. total_len += static_cast<size_t>(n);
  5032. }
  5033. }
  5034. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  5035. return case_ignore::equal(
  5036. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  5037. }
  5038. template <typename T, typename U>
  5039. bool prepare_content_receiver(T &x, int &status,
  5040. ContentReceiverWithProgress receiver,
  5041. bool decompress, U callback) {
  5042. if (decompress) {
  5043. std::string encoding = x.get_header_value("Content-Encoding");
  5044. std::unique_ptr<decompressor> decompressor;
  5045. if (!encoding.empty()) {
  5046. decompressor = detail::create_decompressor(encoding);
  5047. if (!decompressor) {
  5048. // Unsupported encoding or no support compiled in
  5049. status = StatusCode::UnsupportedMediaType_415;
  5050. return false;
  5051. }
  5052. }
  5053. if (decompressor) {
  5054. if (decompressor->is_valid()) {
  5055. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  5056. size_t off, size_t len) {
  5057. return decompressor->decompress(buf, n,
  5058. [&](const char *buf2, size_t n2) {
  5059. return receiver(buf2, n2, off, len);
  5060. });
  5061. };
  5062. return callback(std::move(out));
  5063. } else {
  5064. status = StatusCode::InternalServerError_500;
  5065. return false;
  5066. }
  5067. }
  5068. }
  5069. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  5070. size_t len) {
  5071. return receiver(buf, n, off, len);
  5072. };
  5073. return callback(std::move(out));
  5074. }
  5075. template <typename T>
  5076. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  5077. DownloadProgress progress,
  5078. ContentReceiverWithProgress receiver, bool decompress) {
  5079. return prepare_content_receiver(
  5080. x, status, std::move(receiver), decompress,
  5081. [&](const ContentReceiverWithProgress &out) {
  5082. auto ret = true;
  5083. auto exceed_payload_max_length = false;
  5084. if (is_chunked_transfer_encoding(x.headers)) {
  5085. auto result = read_content_chunked(strm, x, payload_max_length, out);
  5086. if (result == ReadContentResult::Success) {
  5087. ret = true;
  5088. } else if (result == ReadContentResult::PayloadTooLarge) {
  5089. exceed_payload_max_length = true;
  5090. ret = false;
  5091. } else {
  5092. ret = false;
  5093. }
  5094. } else if (!has_header(x.headers, "Content-Length")) {
  5095. auto result =
  5096. read_content_without_length(strm, payload_max_length, out);
  5097. if (result == ReadContentResult::Success) {
  5098. ret = true;
  5099. } else if (result == ReadContentResult::PayloadTooLarge) {
  5100. exceed_payload_max_length = true;
  5101. ret = false;
  5102. } else {
  5103. ret = false;
  5104. }
  5105. } else {
  5106. auto is_invalid_value = false;
  5107. auto len = get_header_value_u64(x.headers, "Content-Length",
  5108. (std::numeric_limits<size_t>::max)(),
  5109. 0, is_invalid_value);
  5110. if (is_invalid_value) {
  5111. ret = false;
  5112. } else if (len > payload_max_length) {
  5113. exceed_payload_max_length = true;
  5114. skip_content_with_length(strm, len);
  5115. ret = false;
  5116. } else if (len > 0) {
  5117. ret = read_content_with_length(strm, len, std::move(progress), out);
  5118. }
  5119. }
  5120. if (!ret) {
  5121. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  5122. : StatusCode::BadRequest_400;
  5123. }
  5124. return ret;
  5125. });
  5126. }
  5127. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  5128. const std::string &path) {
  5129. std::string s = method;
  5130. s += ' ';
  5131. s += path;
  5132. s += " HTTP/1.1\r\n";
  5133. return strm.write(s.data(), s.size());
  5134. }
  5135. inline ssize_t write_response_line(Stream &strm, int status) {
  5136. std::string s = "HTTP/1.1 ";
  5137. s += std::to_string(status);
  5138. s += ' ';
  5139. s += httplib::status_message(status);
  5140. s += "\r\n";
  5141. return strm.write(s.data(), s.size());
  5142. }
  5143. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  5144. ssize_t write_len = 0;
  5145. for (const auto &x : headers) {
  5146. std::string s;
  5147. s = x.first;
  5148. s += ": ";
  5149. s += x.second;
  5150. s += "\r\n";
  5151. auto len = strm.write(s.data(), s.size());
  5152. if (len < 0) { return len; }
  5153. write_len += len;
  5154. }
  5155. auto len = strm.write("\r\n");
  5156. if (len < 0) { return len; }
  5157. write_len += len;
  5158. return write_len;
  5159. }
  5160. inline bool write_data(Stream &strm, const char *d, size_t l) {
  5161. size_t offset = 0;
  5162. while (offset < l) {
  5163. auto length = strm.write(d + offset, l - offset);
  5164. if (length < 0) { return false; }
  5165. offset += static_cast<size_t>(length);
  5166. }
  5167. return true;
  5168. }
  5169. template <typename T>
  5170. inline bool write_content_with_progress(Stream &strm,
  5171. const ContentProvider &content_provider,
  5172. size_t offset, size_t length,
  5173. T is_shutting_down,
  5174. const UploadProgress &upload_progress,
  5175. Error &error) {
  5176. size_t end_offset = offset + length;
  5177. size_t start_offset = offset;
  5178. auto ok = true;
  5179. DataSink data_sink;
  5180. data_sink.write = [&](const char *d, size_t l) -> bool {
  5181. if (ok) {
  5182. if (write_data(strm, d, l)) {
  5183. offset += l;
  5184. if (upload_progress && length > 0) {
  5185. size_t current_written = offset - start_offset;
  5186. if (!upload_progress(current_written, length)) {
  5187. ok = false;
  5188. return false;
  5189. }
  5190. }
  5191. } else {
  5192. ok = false;
  5193. }
  5194. }
  5195. return ok;
  5196. };
  5197. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5198. while (offset < end_offset && !is_shutting_down()) {
  5199. if (!strm.wait_writable()) {
  5200. error = Error::Write;
  5201. return false;
  5202. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  5203. error = Error::Canceled;
  5204. return false;
  5205. } else if (!ok) {
  5206. error = Error::Write;
  5207. return false;
  5208. }
  5209. }
  5210. error = Error::Success;
  5211. return true;
  5212. }
  5213. template <typename T>
  5214. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5215. size_t offset, size_t length, T is_shutting_down,
  5216. Error &error) {
  5217. return write_content_with_progress<T>(strm, content_provider, offset, length,
  5218. is_shutting_down, nullptr, error);
  5219. }
  5220. template <typename T>
  5221. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5222. size_t offset, size_t length,
  5223. const T &is_shutting_down) {
  5224. auto error = Error::Success;
  5225. return write_content(strm, content_provider, offset, length, is_shutting_down,
  5226. error);
  5227. }
  5228. template <typename T>
  5229. inline bool
  5230. write_content_without_length(Stream &strm,
  5231. const ContentProvider &content_provider,
  5232. const T &is_shutting_down) {
  5233. size_t offset = 0;
  5234. auto data_available = true;
  5235. auto ok = true;
  5236. DataSink data_sink;
  5237. data_sink.write = [&](const char *d, size_t l) -> bool {
  5238. if (ok) {
  5239. offset += l;
  5240. if (!write_data(strm, d, l)) { ok = false; }
  5241. }
  5242. return ok;
  5243. };
  5244. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5245. data_sink.done = [&](void) { data_available = false; };
  5246. while (data_available && !is_shutting_down()) {
  5247. if (!strm.wait_writable()) {
  5248. return false;
  5249. } else if (!content_provider(offset, 0, data_sink)) {
  5250. return false;
  5251. } else if (!ok) {
  5252. return false;
  5253. }
  5254. }
  5255. return true;
  5256. }
  5257. template <typename T, typename U>
  5258. inline bool
  5259. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  5260. const T &is_shutting_down, U &compressor, Error &error) {
  5261. size_t offset = 0;
  5262. auto data_available = true;
  5263. auto ok = true;
  5264. DataSink data_sink;
  5265. data_sink.write = [&](const char *d, size_t l) -> bool {
  5266. if (ok) {
  5267. data_available = l > 0;
  5268. offset += l;
  5269. std::string payload;
  5270. if (compressor.compress(d, l, false,
  5271. [&](const char *data, size_t data_len) {
  5272. payload.append(data, data_len);
  5273. return true;
  5274. })) {
  5275. if (!payload.empty()) {
  5276. // Emit chunked response header and footer for each chunk
  5277. auto chunk =
  5278. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5279. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  5280. }
  5281. } else {
  5282. ok = false;
  5283. }
  5284. }
  5285. return ok;
  5286. };
  5287. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5288. auto done_with_trailer = [&](const Headers *trailer) {
  5289. if (!ok) { return; }
  5290. data_available = false;
  5291. std::string payload;
  5292. if (!compressor.compress(nullptr, 0, true,
  5293. [&](const char *data, size_t data_len) {
  5294. payload.append(data, data_len);
  5295. return true;
  5296. })) {
  5297. ok = false;
  5298. return;
  5299. }
  5300. if (!payload.empty()) {
  5301. // Emit chunked response header and footer for each chunk
  5302. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5303. if (!write_data(strm, chunk.data(), chunk.size())) {
  5304. ok = false;
  5305. return;
  5306. }
  5307. }
  5308. constexpr const char done_marker[] = "0\r\n";
  5309. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  5310. // Trailer
  5311. if (trailer) {
  5312. for (const auto &kv : *trailer) {
  5313. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  5314. if (!write_data(strm, field_line.data(), field_line.size())) {
  5315. ok = false;
  5316. }
  5317. }
  5318. }
  5319. constexpr const char crlf[] = "\r\n";
  5320. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  5321. };
  5322. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  5323. data_sink.done_with_trailer = [&](const Headers &trailer) {
  5324. done_with_trailer(&trailer);
  5325. };
  5326. while (data_available && !is_shutting_down()) {
  5327. if (!strm.wait_writable()) {
  5328. error = Error::Write;
  5329. return false;
  5330. } else if (!content_provider(offset, 0, data_sink)) {
  5331. error = Error::Canceled;
  5332. return false;
  5333. } else if (!ok) {
  5334. error = Error::Write;
  5335. return false;
  5336. }
  5337. }
  5338. error = Error::Success;
  5339. return true;
  5340. }
  5341. template <typename T, typename U>
  5342. inline bool write_content_chunked(Stream &strm,
  5343. const ContentProvider &content_provider,
  5344. const T &is_shutting_down, U &compressor) {
  5345. auto error = Error::Success;
  5346. return write_content_chunked(strm, content_provider, is_shutting_down,
  5347. compressor, error);
  5348. }
  5349. template <typename T>
  5350. inline bool redirect(T &cli, Request &req, Response &res,
  5351. const std::string &path, const std::string &location,
  5352. Error &error) {
  5353. Request new_req = req;
  5354. new_req.path = path;
  5355. new_req.redirect_count_ -= 1;
  5356. if (res.status == StatusCode::SeeOther_303 &&
  5357. (req.method != "GET" && req.method != "HEAD")) {
  5358. new_req.method = "GET";
  5359. new_req.body.clear();
  5360. new_req.headers.clear();
  5361. }
  5362. Response new_res;
  5363. auto ret = cli.send(new_req, new_res, error);
  5364. if (ret) {
  5365. req = std::move(new_req);
  5366. res = std::move(new_res);
  5367. if (res.location.empty()) { res.location = location; }
  5368. }
  5369. return ret;
  5370. }
  5371. inline std::string params_to_query_str(const Params &params) {
  5372. std::string query;
  5373. for (auto it = params.begin(); it != params.end(); ++it) {
  5374. if (it != params.begin()) { query += '&'; }
  5375. query += encode_query_component(it->first);
  5376. query += '=';
  5377. query += encode_query_component(it->second);
  5378. }
  5379. return query;
  5380. }
  5381. inline void parse_query_text(const char *data, std::size_t size,
  5382. Params &params) {
  5383. std::set<std::string> cache;
  5384. split(data, data + size, '&', [&](const char *b, const char *e) {
  5385. std::string kv(b, e);
  5386. if (cache.find(kv) != cache.end()) { return; }
  5387. cache.insert(std::move(kv));
  5388. std::string key;
  5389. std::string val;
  5390. divide(b, static_cast<std::size_t>(e - b), '=',
  5391. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  5392. std::size_t rhs_size) {
  5393. key.assign(lhs_data, lhs_size);
  5394. val.assign(rhs_data, rhs_size);
  5395. });
  5396. if (!key.empty()) {
  5397. params.emplace(decode_query_component(key), decode_query_component(val));
  5398. }
  5399. });
  5400. }
  5401. inline void parse_query_text(const std::string &s, Params &params) {
  5402. parse_query_text(s.data(), s.size(), params);
  5403. }
  5404. // Normalize a query string by decoding and re-encoding each key/value pair
  5405. // while preserving the original parameter order. This avoids double-encoding
  5406. // and ensures consistent encoding without reordering (unlike Params which
  5407. // uses std::multimap and sorts keys).
  5408. inline std::string normalize_query_string(const std::string &query) {
  5409. std::string result;
  5410. split(query.data(), query.data() + query.size(), '&',
  5411. [&](const char *b, const char *e) {
  5412. std::string key;
  5413. std::string val;
  5414. divide(b, static_cast<std::size_t>(e - b), '=',
  5415. [&](const char *lhs_data, std::size_t lhs_size,
  5416. const char *rhs_data, std::size_t rhs_size) {
  5417. key.assign(lhs_data, lhs_size);
  5418. val.assign(rhs_data, rhs_size);
  5419. });
  5420. if (!key.empty()) {
  5421. auto dec_key = decode_query_component(key);
  5422. auto dec_val = decode_query_component(val);
  5423. if (!result.empty()) { result += '&'; }
  5424. result += encode_query_component(dec_key);
  5425. if (!val.empty() || std::find(b, e, '=') != e) {
  5426. result += '=';
  5427. result += encode_query_component(dec_val);
  5428. }
  5429. }
  5430. });
  5431. return result;
  5432. }
  5433. inline bool parse_multipart_boundary(const std::string &content_type,
  5434. std::string &boundary) {
  5435. auto boundary_keyword = "boundary=";
  5436. auto pos = content_type.find(boundary_keyword);
  5437. if (pos == std::string::npos) { return false; }
  5438. auto end = content_type.find(';', pos);
  5439. auto beg = pos + strlen(boundary_keyword);
  5440. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  5441. return !boundary.empty();
  5442. }
  5443. inline void parse_disposition_params(const std::string &s, Params &params) {
  5444. std::set<std::string> cache;
  5445. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  5446. std::string kv(b, e);
  5447. if (cache.find(kv) != cache.end()) { return; }
  5448. cache.insert(kv);
  5449. std::string key;
  5450. std::string val;
  5451. split(b, e, '=', [&](const char *b2, const char *e2) {
  5452. if (key.empty()) {
  5453. key.assign(b2, e2);
  5454. } else {
  5455. val.assign(b2, e2);
  5456. }
  5457. });
  5458. if (!key.empty()) {
  5459. params.emplace(trim_double_quotes_copy((key)),
  5460. trim_double_quotes_copy((val)));
  5461. }
  5462. });
  5463. }
  5464. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5465. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  5466. #else
  5467. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  5468. #endif
  5469. auto is_valid = [](const std::string &str) {
  5470. return std::all_of(str.cbegin(), str.cend(),
  5471. [](unsigned char c) { return std::isdigit(c); });
  5472. };
  5473. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  5474. const auto pos = static_cast<size_t>(6);
  5475. const auto len = static_cast<size_t>(s.size() - 6);
  5476. auto all_valid_ranges = true;
  5477. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  5478. if (!all_valid_ranges) { return; }
  5479. const auto it = std::find(b, e, '-');
  5480. if (it == e) {
  5481. all_valid_ranges = false;
  5482. return;
  5483. }
  5484. const auto lhs = std::string(b, it);
  5485. const auto rhs = std::string(it + 1, e);
  5486. if (!is_valid(lhs) || !is_valid(rhs)) {
  5487. all_valid_ranges = false;
  5488. return;
  5489. }
  5490. const auto first =
  5491. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  5492. const auto last =
  5493. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  5494. if ((first == -1 && last == -1) ||
  5495. (first != -1 && last != -1 && first > last)) {
  5496. all_valid_ranges = false;
  5497. return;
  5498. }
  5499. ranges.emplace_back(first, last);
  5500. });
  5501. return all_valid_ranges && !ranges.empty();
  5502. }
  5503. return false;
  5504. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5505. }
  5506. #else
  5507. } catch (...) { return false; }
  5508. #endif
  5509. inline bool parse_accept_header(const std::string &s,
  5510. std::vector<std::string> &content_types) {
  5511. content_types.clear();
  5512. // Empty string is considered valid (no preference)
  5513. if (s.empty()) { return true; }
  5514. // Check for invalid patterns: leading/trailing commas or consecutive commas
  5515. if (s.front() == ',' || s.back() == ',' ||
  5516. s.find(",,") != std::string::npos) {
  5517. return false;
  5518. }
  5519. struct AcceptEntry {
  5520. std::string media_type;
  5521. double quality;
  5522. int order; // Original order in header
  5523. };
  5524. std::vector<AcceptEntry> entries;
  5525. int order = 0;
  5526. bool has_invalid_entry = false;
  5527. // Split by comma and parse each entry
  5528. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5529. std::string entry(b, e);
  5530. entry = trim_copy(entry);
  5531. if (entry.empty()) {
  5532. has_invalid_entry = true;
  5533. return;
  5534. }
  5535. AcceptEntry accept_entry;
  5536. accept_entry.quality = 1.0; // Default quality
  5537. accept_entry.order = order++;
  5538. // Find q= parameter
  5539. auto q_pos = entry.find(";q=");
  5540. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  5541. if (q_pos != std::string::npos) {
  5542. // Extract media type (before q parameter)
  5543. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  5544. // Extract quality value
  5545. auto q_start = entry.find('=', q_pos) + 1;
  5546. auto q_end = entry.find(';', q_start);
  5547. if (q_end == std::string::npos) { q_end = entry.length(); }
  5548. std::string quality_str =
  5549. trim_copy(entry.substr(q_start, q_end - q_start));
  5550. if (quality_str.empty()) {
  5551. has_invalid_entry = true;
  5552. return;
  5553. }
  5554. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5555. {
  5556. std::istringstream iss(quality_str);
  5557. iss >> accept_entry.quality;
  5558. // Check if conversion was successful and entire string was consumed
  5559. if (iss.fail() || !iss.eof()) {
  5560. has_invalid_entry = true;
  5561. return;
  5562. }
  5563. }
  5564. #else
  5565. try {
  5566. accept_entry.quality = std::stod(quality_str);
  5567. } catch (...) {
  5568. has_invalid_entry = true;
  5569. return;
  5570. }
  5571. #endif
  5572. // Check if quality is in valid range [0.0, 1.0]
  5573. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  5574. has_invalid_entry = true;
  5575. return;
  5576. }
  5577. } else {
  5578. // No quality parameter, use entire entry as media type
  5579. accept_entry.media_type = entry;
  5580. }
  5581. // Remove additional parameters from media type
  5582. auto param_pos = accept_entry.media_type.find(';');
  5583. if (param_pos != std::string::npos) {
  5584. accept_entry.media_type =
  5585. trim_copy(accept_entry.media_type.substr(0, param_pos));
  5586. }
  5587. // Basic validation of media type format
  5588. if (accept_entry.media_type.empty()) {
  5589. has_invalid_entry = true;
  5590. return;
  5591. }
  5592. // Check for basic media type format (should contain '/' or be '*')
  5593. if (accept_entry.media_type != "*" &&
  5594. accept_entry.media_type.find('/') == std::string::npos) {
  5595. has_invalid_entry = true;
  5596. return;
  5597. }
  5598. entries.push_back(std::move(accept_entry));
  5599. });
  5600. // Return false if any invalid entry was found
  5601. if (has_invalid_entry) { return false; }
  5602. // Sort by quality (descending), then by original order (ascending)
  5603. std::sort(entries.begin(), entries.end(),
  5604. [](const AcceptEntry &a, const AcceptEntry &b) {
  5605. if (a.quality != b.quality) {
  5606. return a.quality > b.quality; // Higher quality first
  5607. }
  5608. return a.order < b.order; // Earlier order first for same quality
  5609. });
  5610. // Extract sorted media types
  5611. content_types.reserve(entries.size());
  5612. for (auto &entry : entries) {
  5613. content_types.push_back(std::move(entry.media_type));
  5614. }
  5615. return true;
  5616. }
  5617. class FormDataParser {
  5618. public:
  5619. FormDataParser() = default;
  5620. void set_boundary(std::string &&boundary) {
  5621. boundary_ = std::move(boundary);
  5622. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  5623. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  5624. }
  5625. bool is_valid() const { return is_valid_; }
  5626. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  5627. const ContentReceiver &content_callback) {
  5628. buf_append(buf, n);
  5629. while (buf_size() > 0) {
  5630. switch (state_) {
  5631. case 0: { // Initial boundary
  5632. auto pos = buf_find(dash_boundary_crlf_);
  5633. if (pos == buf_size()) { return true; }
  5634. buf_erase(pos + dash_boundary_crlf_.size());
  5635. state_ = 1;
  5636. break;
  5637. }
  5638. case 1: { // New entry
  5639. clear_file_info();
  5640. state_ = 2;
  5641. break;
  5642. }
  5643. case 2: { // Headers
  5644. auto pos = buf_find(crlf_);
  5645. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5646. while (pos < buf_size()) {
  5647. // Empty line
  5648. if (pos == 0) {
  5649. if (!header_callback(file_)) {
  5650. is_valid_ = false;
  5651. return false;
  5652. }
  5653. buf_erase(crlf_.size());
  5654. state_ = 3;
  5655. break;
  5656. }
  5657. const auto header = buf_head(pos);
  5658. if (!parse_header(header.data(), header.data() + header.size(),
  5659. [&](const std::string &, const std::string &) {})) {
  5660. is_valid_ = false;
  5661. return false;
  5662. }
  5663. // Parse and emplace space trimmed headers into a map
  5664. if (!parse_header(
  5665. header.data(), header.data() + header.size(),
  5666. [&](const std::string &key, const std::string &val) {
  5667. file_.headers.emplace(key, val);
  5668. })) {
  5669. is_valid_ = false;
  5670. return false;
  5671. }
  5672. constexpr const char header_content_type[] = "Content-Type:";
  5673. if (start_with_case_ignore(header, header_content_type)) {
  5674. file_.content_type =
  5675. trim_copy(header.substr(str_len(header_content_type)));
  5676. } else {
  5677. thread_local const std::regex re_content_disposition(
  5678. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  5679. std::regex_constants::icase);
  5680. std::smatch m;
  5681. if (std::regex_match(header, m, re_content_disposition)) {
  5682. Params params;
  5683. parse_disposition_params(m[1], params);
  5684. auto it = params.find("name");
  5685. if (it != params.end()) {
  5686. file_.name = it->second;
  5687. } else {
  5688. is_valid_ = false;
  5689. return false;
  5690. }
  5691. it = params.find("filename");
  5692. if (it != params.end()) { file_.filename = it->second; }
  5693. it = params.find("filename*");
  5694. if (it != params.end()) {
  5695. // Only allow UTF-8 encoding...
  5696. thread_local const std::regex re_rfc5987_encoding(
  5697. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  5698. std::smatch m2;
  5699. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  5700. file_.filename = decode_path_component(m2[1]); // override...
  5701. } else {
  5702. is_valid_ = false;
  5703. return false;
  5704. }
  5705. }
  5706. }
  5707. }
  5708. buf_erase(pos + crlf_.size());
  5709. pos = buf_find(crlf_);
  5710. }
  5711. if (state_ != 3) { return true; }
  5712. break;
  5713. }
  5714. case 3: { // Body
  5715. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  5716. auto pos = buf_find(crlf_dash_boundary_);
  5717. if (pos < buf_size()) {
  5718. if (!content_callback(buf_data(), pos)) {
  5719. is_valid_ = false;
  5720. return false;
  5721. }
  5722. buf_erase(pos + crlf_dash_boundary_.size());
  5723. state_ = 4;
  5724. } else {
  5725. auto len = buf_size() - crlf_dash_boundary_.size();
  5726. if (len > 0) {
  5727. if (!content_callback(buf_data(), len)) {
  5728. is_valid_ = false;
  5729. return false;
  5730. }
  5731. buf_erase(len);
  5732. }
  5733. return true;
  5734. }
  5735. break;
  5736. }
  5737. case 4: { // Boundary
  5738. if (crlf_.size() > buf_size()) { return true; }
  5739. if (buf_start_with(crlf_)) {
  5740. buf_erase(crlf_.size());
  5741. state_ = 1;
  5742. } else {
  5743. if (dash_.size() > buf_size()) { return true; }
  5744. if (buf_start_with(dash_)) {
  5745. buf_erase(dash_.size());
  5746. is_valid_ = true;
  5747. buf_erase(buf_size()); // Remove epilogue
  5748. } else {
  5749. return true;
  5750. }
  5751. }
  5752. break;
  5753. }
  5754. }
  5755. }
  5756. return true;
  5757. }
  5758. private:
  5759. void clear_file_info() {
  5760. file_.name.clear();
  5761. file_.filename.clear();
  5762. file_.content_type.clear();
  5763. file_.headers.clear();
  5764. }
  5765. bool start_with_case_ignore(const std::string &a, const char *b) const {
  5766. const auto b_len = strlen(b);
  5767. if (a.size() < b_len) { return false; }
  5768. for (size_t i = 0; i < b_len; i++) {
  5769. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  5770. return false;
  5771. }
  5772. }
  5773. return true;
  5774. }
  5775. const std::string dash_ = "--";
  5776. const std::string crlf_ = "\r\n";
  5777. std::string boundary_;
  5778. std::string dash_boundary_crlf_;
  5779. std::string crlf_dash_boundary_;
  5780. size_t state_ = 0;
  5781. bool is_valid_ = false;
  5782. FormData file_;
  5783. // Buffer
  5784. bool start_with(const std::string &a, size_t spos, size_t epos,
  5785. const std::string &b) const {
  5786. if (epos - spos < b.size()) { return false; }
  5787. for (size_t i = 0; i < b.size(); i++) {
  5788. if (a[i + spos] != b[i]) { return false; }
  5789. }
  5790. return true;
  5791. }
  5792. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  5793. const char *buf_data() const { return &buf_[buf_spos_]; }
  5794. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  5795. bool buf_start_with(const std::string &s) const {
  5796. return start_with(buf_, buf_spos_, buf_epos_, s);
  5797. }
  5798. size_t buf_find(const std::string &s) const {
  5799. auto c = s.front();
  5800. size_t off = buf_spos_;
  5801. while (off < buf_epos_) {
  5802. auto pos = off;
  5803. while (true) {
  5804. if (pos == buf_epos_) { return buf_size(); }
  5805. if (buf_[pos] == c) { break; }
  5806. pos++;
  5807. }
  5808. auto remaining_size = buf_epos_ - pos;
  5809. if (s.size() > remaining_size) { return buf_size(); }
  5810. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  5811. off = pos + 1;
  5812. }
  5813. return buf_size();
  5814. }
  5815. void buf_append(const char *data, size_t n) {
  5816. auto remaining_size = buf_size();
  5817. if (remaining_size > 0 && buf_spos_ > 0) {
  5818. for (size_t i = 0; i < remaining_size; i++) {
  5819. buf_[i] = buf_[buf_spos_ + i];
  5820. }
  5821. }
  5822. buf_spos_ = 0;
  5823. buf_epos_ = remaining_size;
  5824. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  5825. for (size_t i = 0; i < n; i++) {
  5826. buf_[buf_epos_ + i] = data[i];
  5827. }
  5828. buf_epos_ += n;
  5829. }
  5830. void buf_erase(size_t size) { buf_spos_ += size; }
  5831. std::string buf_;
  5832. size_t buf_spos_ = 0;
  5833. size_t buf_epos_ = 0;
  5834. };
  5835. inline std::string random_string(size_t length) {
  5836. constexpr const char data[] =
  5837. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  5838. thread_local auto engine([]() {
  5839. // std::random_device might actually be deterministic on some
  5840. // platforms, but due to lack of support in the c++ standard library,
  5841. // doing better requires either some ugly hacks or breaking portability.
  5842. std::random_device seed_gen;
  5843. // Request 128 bits of entropy for initialization
  5844. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  5845. return std::mt19937(seed_sequence);
  5846. }());
  5847. std::string result;
  5848. for (size_t i = 0; i < length; i++) {
  5849. result += data[engine() % (sizeof(data) - 1)];
  5850. }
  5851. return result;
  5852. }
  5853. inline std::string make_multipart_data_boundary() {
  5854. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  5855. }
  5856. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  5857. auto valid = true;
  5858. for (size_t i = 0; i < boundary.size(); i++) {
  5859. auto c = boundary[i];
  5860. if (!std::isalnum(c) && c != '-' && c != '_') {
  5861. valid = false;
  5862. break;
  5863. }
  5864. }
  5865. return valid;
  5866. }
  5867. template <typename T>
  5868. inline std::string
  5869. serialize_multipart_formdata_item_begin(const T &item,
  5870. const std::string &boundary) {
  5871. std::string body = "--" + boundary + "\r\n";
  5872. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5873. if (!item.filename.empty()) {
  5874. body += "; filename=\"" + item.filename + "\"";
  5875. }
  5876. body += "\r\n";
  5877. if (!item.content_type.empty()) {
  5878. body += "Content-Type: " + item.content_type + "\r\n";
  5879. }
  5880. body += "\r\n";
  5881. return body;
  5882. }
  5883. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  5884. inline std::string
  5885. serialize_multipart_formdata_finish(const std::string &boundary) {
  5886. return "--" + boundary + "--\r\n";
  5887. }
  5888. inline std::string
  5889. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  5890. return "multipart/form-data; boundary=" + boundary;
  5891. }
  5892. inline std::string
  5893. serialize_multipart_formdata(const UploadFormDataItems &items,
  5894. const std::string &boundary, bool finish = true) {
  5895. std::string body;
  5896. for (const auto &item : items) {
  5897. body += serialize_multipart_formdata_item_begin(item, boundary);
  5898. body += item.content + serialize_multipart_formdata_item_end();
  5899. }
  5900. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  5901. return body;
  5902. }
  5903. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  5904. if (ranges.size() <= 1) return;
  5905. // Sort ranges by start position
  5906. std::sort(ranges.begin(), ranges.end(),
  5907. [](const Range &a, const Range &b) { return a.first < b.first; });
  5908. Ranges coalesced;
  5909. coalesced.reserve(ranges.size());
  5910. for (auto &r : ranges) {
  5911. auto first_pos = r.first;
  5912. auto last_pos = r.second;
  5913. // Handle special cases like in range_error
  5914. if (first_pos == -1 && last_pos == -1) {
  5915. first_pos = 0;
  5916. last_pos = static_cast<ssize_t>(content_length);
  5917. }
  5918. if (first_pos == -1) {
  5919. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  5920. last_pos = static_cast<ssize_t>(content_length) - 1;
  5921. }
  5922. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  5923. last_pos = static_cast<ssize_t>(content_length) - 1;
  5924. }
  5925. // Skip invalid ranges
  5926. if (!(0 <= first_pos && first_pos <= last_pos &&
  5927. last_pos < static_cast<ssize_t>(content_length))) {
  5928. continue;
  5929. }
  5930. // Coalesce with previous range if overlapping or adjacent (but not
  5931. // identical)
  5932. if (!coalesced.empty()) {
  5933. auto &prev = coalesced.back();
  5934. // Check if current range overlaps or is adjacent to previous range
  5935. // but don't coalesce identical ranges (allow duplicates)
  5936. if (first_pos <= prev.second + 1 &&
  5937. !(first_pos == prev.first && last_pos == prev.second)) {
  5938. // Extend the previous range
  5939. prev.second = (std::max)(prev.second, last_pos);
  5940. continue;
  5941. }
  5942. }
  5943. // Add new range
  5944. coalesced.emplace_back(first_pos, last_pos);
  5945. }
  5946. ranges = std::move(coalesced);
  5947. }
  5948. inline bool range_error(Request &req, Response &res) {
  5949. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  5950. ssize_t content_len = static_cast<ssize_t>(
  5951. res.content_length_ ? res.content_length_ : res.body.size());
  5952. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  5953. size_t overwrapping_count = 0;
  5954. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  5955. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  5956. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  5957. // Too many ranges
  5958. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  5959. for (auto &r : req.ranges) {
  5960. auto &first_pos = r.first;
  5961. auto &last_pos = r.second;
  5962. if (first_pos == -1 && last_pos == -1) {
  5963. first_pos = 0;
  5964. last_pos = content_len;
  5965. }
  5966. if (first_pos == -1) {
  5967. first_pos = content_len - last_pos;
  5968. last_pos = content_len - 1;
  5969. }
  5970. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  5971. // A client can limit the number of bytes requested without knowing the
  5972. // size of the selected representation. If the last-pos value is absent,
  5973. // or if the value is greater than or equal to the current length of the
  5974. // representation data, the byte range is interpreted as the remainder of
  5975. // the representation (i.e., the server replaces the value of last-pos
  5976. // with a value that is one less than the current length of the selected
  5977. // representation).
  5978. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  5979. if (last_pos == -1 || last_pos >= content_len) {
  5980. last_pos = content_len - 1;
  5981. }
  5982. // Range must be within content length
  5983. if (!(0 <= first_pos && first_pos <= last_pos &&
  5984. last_pos <= content_len - 1)) {
  5985. return true;
  5986. }
  5987. // Request must not have more than two overlapping ranges
  5988. for (const auto &processed_range : processed_ranges) {
  5989. if (!(last_pos < processed_range.first ||
  5990. first_pos > processed_range.second)) {
  5991. overwrapping_count++;
  5992. if (overwrapping_count > 2) { return true; }
  5993. break; // Only count once per range
  5994. }
  5995. }
  5996. processed_ranges.emplace_back(first_pos, last_pos);
  5997. }
  5998. // After validation, coalesce overlapping ranges as per RFC 9110
  5999. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  6000. }
  6001. return false;
  6002. }
  6003. inline std::pair<size_t, size_t>
  6004. get_range_offset_and_length(Range r, size_t content_length) {
  6005. assert(r.first != -1 && r.second != -1);
  6006. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  6007. assert(r.first <= r.second &&
  6008. r.second < static_cast<ssize_t>(content_length));
  6009. (void)(content_length);
  6010. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  6011. }
  6012. inline std::string make_content_range_header_field(
  6013. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  6014. auto st = offset_and_length.first;
  6015. auto ed = st + offset_and_length.second - 1;
  6016. std::string field = "bytes ";
  6017. field += std::to_string(st);
  6018. field += '-';
  6019. field += std::to_string(ed);
  6020. field += '/';
  6021. field += std::to_string(content_length);
  6022. return field;
  6023. }
  6024. template <typename SToken, typename CToken, typename Content>
  6025. bool process_multipart_ranges_data(const Request &req,
  6026. const std::string &boundary,
  6027. const std::string &content_type,
  6028. size_t content_length, SToken stoken,
  6029. CToken ctoken, Content content) {
  6030. for (size_t i = 0; i < req.ranges.size(); i++) {
  6031. ctoken("--");
  6032. stoken(boundary);
  6033. ctoken("\r\n");
  6034. if (!content_type.empty()) {
  6035. ctoken("Content-Type: ");
  6036. stoken(content_type);
  6037. ctoken("\r\n");
  6038. }
  6039. auto offset_and_length =
  6040. get_range_offset_and_length(req.ranges[i], content_length);
  6041. ctoken("Content-Range: ");
  6042. stoken(make_content_range_header_field(offset_and_length, content_length));
  6043. ctoken("\r\n");
  6044. ctoken("\r\n");
  6045. if (!content(offset_and_length.first, offset_and_length.second)) {
  6046. return false;
  6047. }
  6048. ctoken("\r\n");
  6049. }
  6050. ctoken("--");
  6051. stoken(boundary);
  6052. ctoken("--");
  6053. return true;
  6054. }
  6055. inline void make_multipart_ranges_data(const Request &req, Response &res,
  6056. const std::string &boundary,
  6057. const std::string &content_type,
  6058. size_t content_length,
  6059. std::string &data) {
  6060. process_multipart_ranges_data(
  6061. req, boundary, content_type, content_length,
  6062. [&](const std::string &token) { data += token; },
  6063. [&](const std::string &token) { data += token; },
  6064. [&](size_t offset, size_t length) {
  6065. assert(offset + length <= content_length);
  6066. data += res.body.substr(offset, length);
  6067. return true;
  6068. });
  6069. }
  6070. inline size_t get_multipart_ranges_data_length(const Request &req,
  6071. const std::string &boundary,
  6072. const std::string &content_type,
  6073. size_t content_length) {
  6074. size_t data_length = 0;
  6075. process_multipart_ranges_data(
  6076. req, boundary, content_type, content_length,
  6077. [&](const std::string &token) { data_length += token.size(); },
  6078. [&](const std::string &token) { data_length += token.size(); },
  6079. [&](size_t /*offset*/, size_t length) {
  6080. data_length += length;
  6081. return true;
  6082. });
  6083. return data_length;
  6084. }
  6085. template <typename T>
  6086. inline bool
  6087. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  6088. const std::string &boundary,
  6089. const std::string &content_type,
  6090. size_t content_length, const T &is_shutting_down) {
  6091. return process_multipart_ranges_data(
  6092. req, boundary, content_type, content_length,
  6093. [&](const std::string &token) { strm.write(token); },
  6094. [&](const std::string &token) { strm.write(token); },
  6095. [&](size_t offset, size_t length) {
  6096. return write_content(strm, res.content_provider_, offset, length,
  6097. is_shutting_down);
  6098. });
  6099. }
  6100. inline bool expect_content(const Request &req) {
  6101. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  6102. req.method == "DELETE") {
  6103. return true;
  6104. }
  6105. if (req.has_header("Content-Length") &&
  6106. req.get_header_value_u64("Content-Length") > 0) {
  6107. return true;
  6108. }
  6109. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  6110. return false;
  6111. }
  6112. inline bool has_crlf(const std::string &s) {
  6113. auto p = s.c_str();
  6114. while (*p) {
  6115. if (*p == '\r' || *p == '\n') { return true; }
  6116. p++;
  6117. }
  6118. return false;
  6119. }
  6120. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6121. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  6122. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  6123. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  6124. unsigned int hash_length = 0;
  6125. unsigned char hash[EVP_MAX_MD_SIZE];
  6126. EVP_DigestInit_ex(context.get(), algo, nullptr);
  6127. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  6128. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  6129. std::stringstream ss;
  6130. for (auto i = 0u; i < hash_length; ++i) {
  6131. ss << std::hex << std::setw(2) << std::setfill('0')
  6132. << static_cast<unsigned int>(hash[i]);
  6133. }
  6134. return ss.str();
  6135. }
  6136. inline std::string MD5(const std::string &s) {
  6137. return message_digest(s, EVP_md5());
  6138. }
  6139. inline std::string SHA_256(const std::string &s) {
  6140. return message_digest(s, EVP_sha256());
  6141. }
  6142. inline std::string SHA_512(const std::string &s) {
  6143. return message_digest(s, EVP_sha512());
  6144. }
  6145. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  6146. inline std::string MD5(const std::string &s) {
  6147. unsigned char hash[16];
  6148. #if MBEDTLS_VERSION_MAJOR >= 3
  6149. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6150. hash);
  6151. #else
  6152. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6153. hash);
  6154. #endif
  6155. std::stringstream ss;
  6156. for (auto i = 0u; i < 16; ++i) {
  6157. ss << std::hex << std::setw(2) << std::setfill('0')
  6158. << static_cast<unsigned int>(hash[i]);
  6159. }
  6160. return ss.str();
  6161. }
  6162. inline std::string SHA_256(const std::string &s) {
  6163. unsigned char hash[32];
  6164. #if MBEDTLS_VERSION_MAJOR >= 3
  6165. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6166. hash, 0);
  6167. #else
  6168. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6169. s.size(), hash, 0);
  6170. #endif
  6171. std::stringstream ss;
  6172. for (auto i = 0u; i < 32; ++i) {
  6173. ss << std::hex << std::setw(2) << std::setfill('0')
  6174. << static_cast<unsigned int>(hash[i]);
  6175. }
  6176. return ss.str();
  6177. }
  6178. inline std::string SHA_512(const std::string &s) {
  6179. unsigned char hash[64];
  6180. #if MBEDTLS_VERSION_MAJOR >= 3
  6181. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6182. hash, 0);
  6183. #else
  6184. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6185. s.size(), hash, 0);
  6186. #endif
  6187. std::stringstream ss;
  6188. for (auto i = 0u; i < 64; ++i) {
  6189. ss << std::hex << std::setw(2) << std::setfill('0')
  6190. << static_cast<unsigned int>(hash[i]);
  6191. }
  6192. return ss.str();
  6193. }
  6194. #endif
  6195. #ifdef CPPHTTPLIB_SSL_ENABLED
  6196. inline std::pair<std::string, std::string> make_digest_authentication_header(
  6197. const Request &req, const std::map<std::string, std::string> &auth,
  6198. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  6199. const std::string &password, bool is_proxy = false) {
  6200. std::string nc;
  6201. {
  6202. std::stringstream ss;
  6203. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  6204. nc = ss.str();
  6205. }
  6206. std::string qop;
  6207. if (auth.find("qop") != auth.end()) {
  6208. qop = auth.at("qop");
  6209. if (qop.find("auth-int") != std::string::npos) {
  6210. qop = "auth-int";
  6211. } else if (qop.find("auth") != std::string::npos) {
  6212. qop = "auth";
  6213. } else {
  6214. qop.clear();
  6215. }
  6216. }
  6217. std::string algo = "MD5";
  6218. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  6219. std::string response;
  6220. {
  6221. auto H = algo == "SHA-256" ? detail::SHA_256
  6222. : algo == "SHA-512" ? detail::SHA_512
  6223. : detail::MD5;
  6224. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  6225. auto A2 = req.method + ":" + req.path;
  6226. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  6227. if (qop.empty()) {
  6228. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  6229. } else {
  6230. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  6231. ":" + qop + ":" + H(A2));
  6232. }
  6233. }
  6234. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  6235. auto field = "Digest username=\"" + username + "\", realm=\"" +
  6236. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  6237. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  6238. (qop.empty() ? ", response=\""
  6239. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  6240. cnonce + "\", response=\"") +
  6241. response + "\"" +
  6242. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  6243. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6244. return std::make_pair(key, field);
  6245. }
  6246. #endif // CPPHTTPLIB_SSL_ENABLED
  6247. #ifdef _WIN32
  6248. class WSInit {
  6249. public:
  6250. WSInit() {
  6251. WSADATA wsaData;
  6252. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  6253. }
  6254. ~WSInit() {
  6255. if (is_valid_) WSACleanup();
  6256. }
  6257. bool is_valid_ = false;
  6258. };
  6259. static WSInit wsinit_;
  6260. #endif
  6261. inline bool parse_www_authenticate(const Response &res,
  6262. std::map<std::string, std::string> &auth,
  6263. bool is_proxy) {
  6264. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  6265. if (res.has_header(auth_key)) {
  6266. thread_local auto re =
  6267. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  6268. auto s = res.get_header_value(auth_key);
  6269. auto pos = s.find(' ');
  6270. if (pos != std::string::npos) {
  6271. auto type = s.substr(0, pos);
  6272. if (type == "Basic") {
  6273. return false;
  6274. } else if (type == "Digest") {
  6275. s = s.substr(pos + 1);
  6276. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  6277. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  6278. const auto &m = *i;
  6279. auto key = s.substr(static_cast<size_t>(m.position(1)),
  6280. static_cast<size_t>(m.length(1)));
  6281. auto val = m.length(2) > 0
  6282. ? s.substr(static_cast<size_t>(m.position(2)),
  6283. static_cast<size_t>(m.length(2)))
  6284. : s.substr(static_cast<size_t>(m.position(3)),
  6285. static_cast<size_t>(m.length(3)));
  6286. auth[std::move(key)] = std::move(val);
  6287. }
  6288. return true;
  6289. }
  6290. }
  6291. }
  6292. return false;
  6293. }
  6294. class ContentProviderAdapter {
  6295. public:
  6296. explicit ContentProviderAdapter(
  6297. ContentProviderWithoutLength &&content_provider)
  6298. : content_provider_(std::move(content_provider)) {}
  6299. bool operator()(size_t offset, size_t, DataSink &sink) {
  6300. return content_provider_(offset, sink);
  6301. }
  6302. private:
  6303. ContentProviderWithoutLength content_provider_;
  6304. };
  6305. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  6306. namespace fields {
  6307. inline bool is_token_char(char c) {
  6308. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  6309. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  6310. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  6311. }
  6312. inline bool is_token(const std::string &s) {
  6313. if (s.empty()) { return false; }
  6314. for (auto c : s) {
  6315. if (!is_token_char(c)) { return false; }
  6316. }
  6317. return true;
  6318. }
  6319. inline bool is_field_name(const std::string &s) { return is_token(s); }
  6320. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  6321. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  6322. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  6323. inline bool is_field_content(const std::string &s) {
  6324. if (s.empty()) { return true; }
  6325. if (s.size() == 1) {
  6326. return is_field_vchar(s[0]);
  6327. } else if (s.size() == 2) {
  6328. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  6329. } else {
  6330. size_t i = 0;
  6331. if (!is_field_vchar(s[i])) { return false; }
  6332. i++;
  6333. while (i < s.size() - 1) {
  6334. auto c = s[i++];
  6335. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  6336. } else {
  6337. return false;
  6338. }
  6339. }
  6340. return is_field_vchar(s[i]);
  6341. }
  6342. }
  6343. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  6344. } // namespace fields
  6345. } // namespace detail
  6346. inline const char *status_message(int status) {
  6347. switch (status) {
  6348. case StatusCode::Continue_100: return "Continue";
  6349. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  6350. case StatusCode::Processing_102: return "Processing";
  6351. case StatusCode::EarlyHints_103: return "Early Hints";
  6352. case StatusCode::OK_200: return "OK";
  6353. case StatusCode::Created_201: return "Created";
  6354. case StatusCode::Accepted_202: return "Accepted";
  6355. case StatusCode::NonAuthoritativeInformation_203:
  6356. return "Non-Authoritative Information";
  6357. case StatusCode::NoContent_204: return "No Content";
  6358. case StatusCode::ResetContent_205: return "Reset Content";
  6359. case StatusCode::PartialContent_206: return "Partial Content";
  6360. case StatusCode::MultiStatus_207: return "Multi-Status";
  6361. case StatusCode::AlreadyReported_208: return "Already Reported";
  6362. case StatusCode::IMUsed_226: return "IM Used";
  6363. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  6364. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  6365. case StatusCode::Found_302: return "Found";
  6366. case StatusCode::SeeOther_303: return "See Other";
  6367. case StatusCode::NotModified_304: return "Not Modified";
  6368. case StatusCode::UseProxy_305: return "Use Proxy";
  6369. case StatusCode::unused_306: return "unused";
  6370. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  6371. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  6372. case StatusCode::BadRequest_400: return "Bad Request";
  6373. case StatusCode::Unauthorized_401: return "Unauthorized";
  6374. case StatusCode::PaymentRequired_402: return "Payment Required";
  6375. case StatusCode::Forbidden_403: return "Forbidden";
  6376. case StatusCode::NotFound_404: return "Not Found";
  6377. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  6378. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  6379. case StatusCode::ProxyAuthenticationRequired_407:
  6380. return "Proxy Authentication Required";
  6381. case StatusCode::RequestTimeout_408: return "Request Timeout";
  6382. case StatusCode::Conflict_409: return "Conflict";
  6383. case StatusCode::Gone_410: return "Gone";
  6384. case StatusCode::LengthRequired_411: return "Length Required";
  6385. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  6386. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  6387. case StatusCode::UriTooLong_414: return "URI Too Long";
  6388. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  6389. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  6390. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  6391. case StatusCode::ImATeapot_418: return "I'm a teapot";
  6392. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  6393. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  6394. case StatusCode::Locked_423: return "Locked";
  6395. case StatusCode::FailedDependency_424: return "Failed Dependency";
  6396. case StatusCode::TooEarly_425: return "Too Early";
  6397. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  6398. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  6399. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  6400. case StatusCode::RequestHeaderFieldsTooLarge_431:
  6401. return "Request Header Fields Too Large";
  6402. case StatusCode::UnavailableForLegalReasons_451:
  6403. return "Unavailable For Legal Reasons";
  6404. case StatusCode::NotImplemented_501: return "Not Implemented";
  6405. case StatusCode::BadGateway_502: return "Bad Gateway";
  6406. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  6407. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  6408. case StatusCode::HttpVersionNotSupported_505:
  6409. return "HTTP Version Not Supported";
  6410. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  6411. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  6412. case StatusCode::LoopDetected_508: return "Loop Detected";
  6413. case StatusCode::NotExtended_510: return "Not Extended";
  6414. case StatusCode::NetworkAuthenticationRequired_511:
  6415. return "Network Authentication Required";
  6416. default:
  6417. case StatusCode::InternalServerError_500: return "Internal Server Error";
  6418. }
  6419. }
  6420. inline std::string to_string(const Error error) {
  6421. switch (error) {
  6422. case Error::Success: return "Success (no error)";
  6423. case Error::Unknown: return "Unknown";
  6424. case Error::Connection: return "Could not establish connection";
  6425. case Error::BindIPAddress: return "Failed to bind IP address";
  6426. case Error::Read: return "Failed to read connection";
  6427. case Error::Write: return "Failed to write connection";
  6428. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  6429. case Error::Canceled: return "Connection handling canceled";
  6430. case Error::SSLConnection: return "SSL connection failed";
  6431. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  6432. case Error::SSLServerVerification: return "SSL server verification failed";
  6433. case Error::SSLServerHostnameVerification:
  6434. return "SSL server hostname verification failed";
  6435. case Error::UnsupportedMultipartBoundaryChars:
  6436. return "Unsupported HTTP multipart boundary characters";
  6437. case Error::Compression: return "Compression failed";
  6438. case Error::ConnectionTimeout: return "Connection timed out";
  6439. case Error::ProxyConnection: return "Proxy connection failed";
  6440. case Error::ConnectionClosed: return "Connection closed by server";
  6441. case Error::Timeout: return "Read timeout";
  6442. case Error::ResourceExhaustion: return "Resource exhaustion";
  6443. case Error::TooManyFormDataFiles: return "Too many form data files";
  6444. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  6445. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  6446. case Error::ExceedMaxSocketDescriptorCount:
  6447. return "Exceeded maximum socket descriptor count";
  6448. case Error::InvalidRequestLine: return "Invalid request line";
  6449. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  6450. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  6451. case Error::InvalidHeaders: return "Invalid headers";
  6452. case Error::MultipartParsing: return "Multipart parsing failed";
  6453. case Error::OpenFile: return "Failed to open file";
  6454. case Error::Listen: return "Failed to listen on socket";
  6455. case Error::GetSockName: return "Failed to get socket name";
  6456. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  6457. case Error::HTTPParsing: return "HTTP parsing failed";
  6458. case Error::InvalidRangeHeader: return "Invalid Range header";
  6459. default: break;
  6460. }
  6461. return "Invalid";
  6462. }
  6463. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  6464. os << to_string(obj);
  6465. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  6466. return os;
  6467. }
  6468. inline std::string hosted_at(const std::string &hostname) {
  6469. std::vector<std::string> addrs;
  6470. hosted_at(hostname, addrs);
  6471. if (addrs.empty()) { return std::string(); }
  6472. return addrs[0];
  6473. }
  6474. inline void hosted_at(const std::string &hostname,
  6475. std::vector<std::string> &addrs) {
  6476. struct addrinfo hints;
  6477. struct addrinfo *result;
  6478. memset(&hints, 0, sizeof(struct addrinfo));
  6479. hints.ai_family = AF_UNSPEC;
  6480. hints.ai_socktype = SOCK_STREAM;
  6481. hints.ai_protocol = 0;
  6482. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  6483. &result, 0)) {
  6484. #if defined __linux__ && !defined __ANDROID__
  6485. res_init();
  6486. #endif
  6487. return;
  6488. }
  6489. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6490. for (auto rp = result; rp; rp = rp->ai_next) {
  6491. const auto &addr =
  6492. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  6493. std::string ip;
  6494. auto dummy = -1;
  6495. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  6496. dummy)) {
  6497. addrs.emplace_back(std::move(ip));
  6498. }
  6499. }
  6500. }
  6501. inline std::string encode_uri_component(const std::string &value) {
  6502. std::ostringstream escaped;
  6503. escaped.fill('0');
  6504. escaped << std::hex;
  6505. for (auto c : value) {
  6506. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6507. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6508. c == ')') {
  6509. escaped << c;
  6510. } else {
  6511. escaped << std::uppercase;
  6512. escaped << '%' << std::setw(2)
  6513. << static_cast<int>(static_cast<unsigned char>(c));
  6514. escaped << std::nouppercase;
  6515. }
  6516. }
  6517. return escaped.str();
  6518. }
  6519. inline std::string encode_uri(const std::string &value) {
  6520. std::ostringstream escaped;
  6521. escaped.fill('0');
  6522. escaped << std::hex;
  6523. for (auto c : value) {
  6524. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6525. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6526. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  6527. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  6528. escaped << c;
  6529. } else {
  6530. escaped << std::uppercase;
  6531. escaped << '%' << std::setw(2)
  6532. << static_cast<int>(static_cast<unsigned char>(c));
  6533. escaped << std::nouppercase;
  6534. }
  6535. }
  6536. return escaped.str();
  6537. }
  6538. inline std::string decode_uri_component(const std::string &value) {
  6539. std::string result;
  6540. for (size_t i = 0; i < value.size(); i++) {
  6541. if (value[i] == '%' && i + 2 < value.size()) {
  6542. auto val = 0;
  6543. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6544. result += static_cast<char>(val);
  6545. i += 2;
  6546. } else {
  6547. result += value[i];
  6548. }
  6549. } else {
  6550. result += value[i];
  6551. }
  6552. }
  6553. return result;
  6554. }
  6555. inline std::string decode_uri(const std::string &value) {
  6556. std::string result;
  6557. for (size_t i = 0; i < value.size(); i++) {
  6558. if (value[i] == '%' && i + 2 < value.size()) {
  6559. auto val = 0;
  6560. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6561. result += static_cast<char>(val);
  6562. i += 2;
  6563. } else {
  6564. result += value[i];
  6565. }
  6566. } else {
  6567. result += value[i];
  6568. }
  6569. }
  6570. return result;
  6571. }
  6572. inline std::string encode_path_component(const std::string &component) {
  6573. std::string result;
  6574. result.reserve(component.size() * 3);
  6575. for (size_t i = 0; i < component.size(); i++) {
  6576. auto c = static_cast<unsigned char>(component[i]);
  6577. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  6578. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6579. result += static_cast<char>(c);
  6580. }
  6581. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  6582. // "," / ";" / "="
  6583. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  6584. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  6585. c == '=') {
  6586. result += static_cast<char>(c);
  6587. }
  6588. // Colon is allowed in path segments except first segment
  6589. else if (c == ':') {
  6590. result += static_cast<char>(c);
  6591. }
  6592. // @ is allowed in path
  6593. else if (c == '@') {
  6594. result += static_cast<char>(c);
  6595. } else {
  6596. result += '%';
  6597. char hex[3];
  6598. snprintf(hex, sizeof(hex), "%02X", c);
  6599. result.append(hex, 2);
  6600. }
  6601. }
  6602. return result;
  6603. }
  6604. inline std::string decode_path_component(const std::string &component) {
  6605. std::string result;
  6606. result.reserve(component.size());
  6607. for (size_t i = 0; i < component.size(); i++) {
  6608. if (component[i] == '%' && i + 1 < component.size()) {
  6609. if (component[i + 1] == 'u') {
  6610. // Unicode %uXXXX encoding
  6611. auto val = 0;
  6612. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  6613. // 4 digits Unicode codes
  6614. char buff[4];
  6615. size_t len = detail::to_utf8(val, buff);
  6616. if (len > 0) { result.append(buff, len); }
  6617. i += 5; // 'u0000'
  6618. } else {
  6619. result += component[i];
  6620. }
  6621. } else {
  6622. // Standard %XX encoding
  6623. auto val = 0;
  6624. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  6625. // 2 digits hex codes
  6626. result += static_cast<char>(val);
  6627. i += 2; // 'XX'
  6628. } else {
  6629. result += component[i];
  6630. }
  6631. }
  6632. } else {
  6633. result += component[i];
  6634. }
  6635. }
  6636. return result;
  6637. }
  6638. inline std::string encode_query_component(const std::string &component,
  6639. bool space_as_plus) {
  6640. std::string result;
  6641. result.reserve(component.size() * 3);
  6642. for (size_t i = 0; i < component.size(); i++) {
  6643. auto c = static_cast<unsigned char>(component[i]);
  6644. // Unreserved characters per RFC 3986
  6645. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6646. result += static_cast<char>(c);
  6647. }
  6648. // Space handling
  6649. else if (c == ' ') {
  6650. if (space_as_plus) {
  6651. result += '+';
  6652. } else {
  6653. result += "%20";
  6654. }
  6655. }
  6656. // Plus sign handling
  6657. else if (c == '+') {
  6658. if (space_as_plus) {
  6659. result += "%2B";
  6660. } else {
  6661. result += static_cast<char>(c);
  6662. }
  6663. }
  6664. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  6665. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  6666. c == '*' || c == ',' || c == ';') {
  6667. result += static_cast<char>(c);
  6668. }
  6669. // Colon and @ are allowed in query
  6670. else if (c == ':' || c == '@') {
  6671. result += static_cast<char>(c);
  6672. }
  6673. // Forward slash is allowed in query values
  6674. else if (c == '/') {
  6675. result += static_cast<char>(c);
  6676. }
  6677. // Question mark is allowed in query values (after first ?)
  6678. else if (c == '?') {
  6679. result += static_cast<char>(c);
  6680. } else {
  6681. result += '%';
  6682. char hex[3];
  6683. snprintf(hex, sizeof(hex), "%02X", c);
  6684. result.append(hex, 2);
  6685. }
  6686. }
  6687. return result;
  6688. }
  6689. inline std::string decode_query_component(const std::string &component,
  6690. bool plus_as_space) {
  6691. std::string result;
  6692. result.reserve(component.size());
  6693. for (size_t i = 0; i < component.size(); i++) {
  6694. if (component[i] == '%' && i + 2 < component.size()) {
  6695. std::string hex = component.substr(i + 1, 2);
  6696. char *end;
  6697. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  6698. if (end == hex.c_str() + 2) {
  6699. result += static_cast<char>(value);
  6700. i += 2;
  6701. } else {
  6702. result += component[i];
  6703. }
  6704. } else if (component[i] == '+' && plus_as_space) {
  6705. result += ' '; // + becomes space in form-urlencoded
  6706. } else {
  6707. result += component[i];
  6708. }
  6709. }
  6710. return result;
  6711. }
  6712. inline std::string append_query_params(const std::string &path,
  6713. const Params &params) {
  6714. std::string path_with_query = path;
  6715. thread_local const std::regex re("[^?]+\\?.*");
  6716. auto delm = std::regex_match(path, re) ? '&' : '?';
  6717. path_with_query += delm + detail::params_to_query_str(params);
  6718. return path_with_query;
  6719. }
  6720. // Header utilities
  6721. inline std::pair<std::string, std::string>
  6722. make_range_header(const Ranges &ranges) {
  6723. std::string field = "bytes=";
  6724. auto i = 0;
  6725. for (const auto &r : ranges) {
  6726. if (i != 0) { field += ", "; }
  6727. if (r.first != -1) { field += std::to_string(r.first); }
  6728. field += '-';
  6729. if (r.second != -1) { field += std::to_string(r.second); }
  6730. i++;
  6731. }
  6732. return std::make_pair("Range", std::move(field));
  6733. }
  6734. inline std::pair<std::string, std::string>
  6735. make_basic_authentication_header(const std::string &username,
  6736. const std::string &password, bool is_proxy) {
  6737. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  6738. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6739. return std::make_pair(key, std::move(field));
  6740. }
  6741. inline std::pair<std::string, std::string>
  6742. make_bearer_token_authentication_header(const std::string &token,
  6743. bool is_proxy = false) {
  6744. auto field = "Bearer " + token;
  6745. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6746. return std::make_pair(key, std::move(field));
  6747. }
  6748. // Request implementation
  6749. inline bool Request::has_header(const std::string &key) const {
  6750. return detail::has_header(headers, key);
  6751. }
  6752. inline std::string Request::get_header_value(const std::string &key,
  6753. const char *def, size_t id) const {
  6754. return detail::get_header_value(headers, key, def, id);
  6755. }
  6756. inline size_t Request::get_header_value_count(const std::string &key) const {
  6757. auto r = headers.equal_range(key);
  6758. return static_cast<size_t>(std::distance(r.first, r.second));
  6759. }
  6760. inline void Request::set_header(const std::string &key,
  6761. const std::string &val) {
  6762. if (detail::fields::is_field_name(key) &&
  6763. detail::fields::is_field_value(val)) {
  6764. headers.emplace(key, val);
  6765. }
  6766. }
  6767. inline bool Request::has_trailer(const std::string &key) const {
  6768. return trailers.find(key) != trailers.end();
  6769. }
  6770. inline std::string Request::get_trailer_value(const std::string &key,
  6771. size_t id) const {
  6772. auto rng = trailers.equal_range(key);
  6773. auto it = rng.first;
  6774. std::advance(it, static_cast<ssize_t>(id));
  6775. if (it != rng.second) { return it->second; }
  6776. return std::string();
  6777. }
  6778. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  6779. auto r = trailers.equal_range(key);
  6780. return static_cast<size_t>(std::distance(r.first, r.second));
  6781. }
  6782. inline bool Request::has_param(const std::string &key) const {
  6783. return params.find(key) != params.end();
  6784. }
  6785. inline std::string Request::get_param_value(const std::string &key,
  6786. size_t id) const {
  6787. auto rng = params.equal_range(key);
  6788. auto it = rng.first;
  6789. std::advance(it, static_cast<ssize_t>(id));
  6790. if (it != rng.second) { return it->second; }
  6791. return std::string();
  6792. }
  6793. inline size_t Request::get_param_value_count(const std::string &key) const {
  6794. auto r = params.equal_range(key);
  6795. return static_cast<size_t>(std::distance(r.first, r.second));
  6796. }
  6797. inline bool Request::is_multipart_form_data() const {
  6798. const auto &content_type = get_header_value("Content-Type");
  6799. return !content_type.rfind("multipart/form-data", 0);
  6800. }
  6801. // Multipart FormData implementation
  6802. inline std::string MultipartFormData::get_field(const std::string &key,
  6803. size_t id) const {
  6804. auto rng = fields.equal_range(key);
  6805. auto it = rng.first;
  6806. std::advance(it, static_cast<ssize_t>(id));
  6807. if (it != rng.second) { return it->second.content; }
  6808. return std::string();
  6809. }
  6810. inline std::vector<std::string>
  6811. MultipartFormData::get_fields(const std::string &key) const {
  6812. std::vector<std::string> values;
  6813. auto rng = fields.equal_range(key);
  6814. for (auto it = rng.first; it != rng.second; it++) {
  6815. values.push_back(it->second.content);
  6816. }
  6817. return values;
  6818. }
  6819. inline bool MultipartFormData::has_field(const std::string &key) const {
  6820. return fields.find(key) != fields.end();
  6821. }
  6822. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  6823. auto r = fields.equal_range(key);
  6824. return static_cast<size_t>(std::distance(r.first, r.second));
  6825. }
  6826. inline FormData MultipartFormData::get_file(const std::string &key,
  6827. size_t id) const {
  6828. auto rng = files.equal_range(key);
  6829. auto it = rng.first;
  6830. std::advance(it, static_cast<ssize_t>(id));
  6831. if (it != rng.second) { return it->second; }
  6832. return FormData();
  6833. }
  6834. inline std::vector<FormData>
  6835. MultipartFormData::get_files(const std::string &key) const {
  6836. std::vector<FormData> values;
  6837. auto rng = files.equal_range(key);
  6838. for (auto it = rng.first; it != rng.second; it++) {
  6839. values.push_back(it->second);
  6840. }
  6841. return values;
  6842. }
  6843. inline bool MultipartFormData::has_file(const std::string &key) const {
  6844. return files.find(key) != files.end();
  6845. }
  6846. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  6847. auto r = files.equal_range(key);
  6848. return static_cast<size_t>(std::distance(r.first, r.second));
  6849. }
  6850. // Response implementation
  6851. inline bool Response::has_header(const std::string &key) const {
  6852. return headers.find(key) != headers.end();
  6853. }
  6854. inline std::string Response::get_header_value(const std::string &key,
  6855. const char *def,
  6856. size_t id) const {
  6857. return detail::get_header_value(headers, key, def, id);
  6858. }
  6859. inline size_t Response::get_header_value_count(const std::string &key) const {
  6860. auto r = headers.equal_range(key);
  6861. return static_cast<size_t>(std::distance(r.first, r.second));
  6862. }
  6863. inline void Response::set_header(const std::string &key,
  6864. const std::string &val) {
  6865. if (detail::fields::is_field_name(key) &&
  6866. detail::fields::is_field_value(val)) {
  6867. headers.emplace(key, val);
  6868. }
  6869. }
  6870. inline bool Response::has_trailer(const std::string &key) const {
  6871. return trailers.find(key) != trailers.end();
  6872. }
  6873. inline std::string Response::get_trailer_value(const std::string &key,
  6874. size_t id) const {
  6875. auto rng = trailers.equal_range(key);
  6876. auto it = rng.first;
  6877. std::advance(it, static_cast<ssize_t>(id));
  6878. if (it != rng.second) { return it->second; }
  6879. return std::string();
  6880. }
  6881. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  6882. auto r = trailers.equal_range(key);
  6883. return static_cast<size_t>(std::distance(r.first, r.second));
  6884. }
  6885. inline void Response::set_redirect(const std::string &url, int stat) {
  6886. if (detail::fields::is_field_value(url)) {
  6887. set_header("Location", url);
  6888. if (300 <= stat && stat < 400) {
  6889. this->status = stat;
  6890. } else {
  6891. this->status = StatusCode::Found_302;
  6892. }
  6893. }
  6894. }
  6895. inline void Response::set_content(const char *s, size_t n,
  6896. const std::string &content_type) {
  6897. body.assign(s, n);
  6898. auto rng = headers.equal_range("Content-Type");
  6899. headers.erase(rng.first, rng.second);
  6900. set_header("Content-Type", content_type);
  6901. }
  6902. inline void Response::set_content(const std::string &s,
  6903. const std::string &content_type) {
  6904. set_content(s.data(), s.size(), content_type);
  6905. }
  6906. inline void Response::set_content(std::string &&s,
  6907. const std::string &content_type) {
  6908. body = std::move(s);
  6909. auto rng = headers.equal_range("Content-Type");
  6910. headers.erase(rng.first, rng.second);
  6911. set_header("Content-Type", content_type);
  6912. }
  6913. inline void Response::set_content_provider(
  6914. size_t in_length, const std::string &content_type, ContentProvider provider,
  6915. ContentProviderResourceReleaser resource_releaser) {
  6916. set_header("Content-Type", content_type);
  6917. content_length_ = in_length;
  6918. if (in_length > 0) { content_provider_ = std::move(provider); }
  6919. content_provider_resource_releaser_ = std::move(resource_releaser);
  6920. is_chunked_content_provider_ = false;
  6921. }
  6922. inline void Response::set_content_provider(
  6923. const std::string &content_type, ContentProviderWithoutLength provider,
  6924. ContentProviderResourceReleaser resource_releaser) {
  6925. set_header("Content-Type", content_type);
  6926. content_length_ = 0;
  6927. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6928. content_provider_resource_releaser_ = std::move(resource_releaser);
  6929. is_chunked_content_provider_ = false;
  6930. }
  6931. inline void Response::set_chunked_content_provider(
  6932. const std::string &content_type, ContentProviderWithoutLength provider,
  6933. ContentProviderResourceReleaser resource_releaser) {
  6934. set_header("Content-Type", content_type);
  6935. content_length_ = 0;
  6936. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6937. content_provider_resource_releaser_ = std::move(resource_releaser);
  6938. is_chunked_content_provider_ = true;
  6939. }
  6940. inline void Response::set_file_content(const std::string &path,
  6941. const std::string &content_type) {
  6942. file_content_path_ = path;
  6943. file_content_content_type_ = content_type;
  6944. }
  6945. inline void Response::set_file_content(const std::string &path) {
  6946. file_content_path_ = path;
  6947. }
  6948. // Result implementation
  6949. inline bool Result::has_request_header(const std::string &key) const {
  6950. return request_headers_.find(key) != request_headers_.end();
  6951. }
  6952. inline std::string Result::get_request_header_value(const std::string &key,
  6953. const char *def,
  6954. size_t id) const {
  6955. return detail::get_header_value(request_headers_, key, def, id);
  6956. }
  6957. inline size_t
  6958. Result::get_request_header_value_count(const std::string &key) const {
  6959. auto r = request_headers_.equal_range(key);
  6960. return static_cast<size_t>(std::distance(r.first, r.second));
  6961. }
  6962. // Stream implementation
  6963. inline ssize_t Stream::write(const char *ptr) {
  6964. return write(ptr, strlen(ptr));
  6965. }
  6966. inline ssize_t Stream::write(const std::string &s) {
  6967. return write(s.data(), s.size());
  6968. }
  6969. // BodyReader implementation
  6970. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  6971. if (!stream) {
  6972. last_error = Error::Connection;
  6973. return -1;
  6974. }
  6975. if (eof) { return 0; }
  6976. if (!chunked) {
  6977. // Content-Length based reading
  6978. if (bytes_read >= content_length) {
  6979. eof = true;
  6980. return 0;
  6981. }
  6982. auto remaining = content_length - bytes_read;
  6983. auto to_read = (std::min)(len, remaining);
  6984. auto n = stream->read(buf, to_read);
  6985. if (n < 0) {
  6986. last_error = stream->get_error();
  6987. if (last_error == Error::Success) { last_error = Error::Read; }
  6988. eof = true;
  6989. return n;
  6990. }
  6991. if (n == 0) {
  6992. // Unexpected EOF before content_length
  6993. last_error = stream->get_error();
  6994. if (last_error == Error::Success) { last_error = Error::Read; }
  6995. eof = true;
  6996. return 0;
  6997. }
  6998. bytes_read += static_cast<size_t>(n);
  6999. if (bytes_read >= content_length) { eof = true; }
  7000. return n;
  7001. }
  7002. // Chunked transfer encoding: delegate to shared decoder instance.
  7003. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  7004. size_t chunk_offset = 0;
  7005. size_t chunk_total = 0;
  7006. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  7007. if (n < 0) {
  7008. last_error = stream->get_error();
  7009. if (last_error == Error::Success) { last_error = Error::Read; }
  7010. eof = true;
  7011. return n;
  7012. }
  7013. if (n == 0) {
  7014. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  7015. eof = true;
  7016. return 0;
  7017. }
  7018. bytes_read += static_cast<size_t>(n);
  7019. return n;
  7020. }
  7021. namespace detail {
  7022. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  7023. time_t timeout_sec, time_t timeout_usec,
  7024. time_t &actual_timeout_sec,
  7025. time_t &actual_timeout_usec) {
  7026. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  7027. auto actual_timeout_msec =
  7028. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  7029. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  7030. actual_timeout_sec = actual_timeout_msec / 1000;
  7031. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  7032. }
  7033. // Socket stream implementation
  7034. inline SocketStream::SocketStream(
  7035. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  7036. time_t write_timeout_sec, time_t write_timeout_usec,
  7037. time_t max_timeout_msec,
  7038. std::chrono::time_point<std::chrono::steady_clock> start_time)
  7039. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  7040. read_timeout_usec_(read_timeout_usec),
  7041. write_timeout_sec_(write_timeout_sec),
  7042. write_timeout_usec_(write_timeout_usec),
  7043. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  7044. read_buff_(read_buff_size_, 0) {}
  7045. inline SocketStream::~SocketStream() = default;
  7046. inline bool SocketStream::is_readable() const {
  7047. return read_buff_off_ < read_buff_content_size_;
  7048. }
  7049. inline bool SocketStream::wait_readable() const {
  7050. if (max_timeout_msec_ <= 0) {
  7051. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  7052. }
  7053. time_t read_timeout_sec;
  7054. time_t read_timeout_usec;
  7055. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  7056. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  7057. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  7058. }
  7059. inline bool SocketStream::wait_writable() const {
  7060. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  7061. is_socket_alive(sock_);
  7062. }
  7063. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  7064. #ifdef _WIN32
  7065. size =
  7066. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7067. #else
  7068. size = (std::min)(size,
  7069. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  7070. #endif
  7071. if (read_buff_off_ < read_buff_content_size_) {
  7072. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  7073. if (size <= remaining_size) {
  7074. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  7075. read_buff_off_ += size;
  7076. return static_cast<ssize_t>(size);
  7077. } else {
  7078. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  7079. read_buff_off_ += remaining_size;
  7080. return static_cast<ssize_t>(remaining_size);
  7081. }
  7082. }
  7083. if (!wait_readable()) {
  7084. error_ = Error::Timeout;
  7085. return -1;
  7086. }
  7087. read_buff_off_ = 0;
  7088. read_buff_content_size_ = 0;
  7089. if (size < read_buff_size_) {
  7090. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  7091. CPPHTTPLIB_RECV_FLAGS);
  7092. if (n <= 0) {
  7093. if (n == 0) {
  7094. error_ = Error::ConnectionClosed;
  7095. } else {
  7096. error_ = Error::Read;
  7097. }
  7098. return n;
  7099. } else if (n <= static_cast<ssize_t>(size)) {
  7100. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  7101. return n;
  7102. } else {
  7103. memcpy(ptr, read_buff_.data(), size);
  7104. read_buff_off_ = size;
  7105. read_buff_content_size_ = static_cast<size_t>(n);
  7106. return static_cast<ssize_t>(size);
  7107. }
  7108. } else {
  7109. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  7110. if (n <= 0) {
  7111. if (n == 0) {
  7112. error_ = Error::ConnectionClosed;
  7113. } else {
  7114. error_ = Error::Read;
  7115. }
  7116. }
  7117. return n;
  7118. }
  7119. }
  7120. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  7121. if (!wait_writable()) { return -1; }
  7122. #if defined(_WIN32) && !defined(_WIN64)
  7123. size =
  7124. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7125. #endif
  7126. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  7127. }
  7128. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  7129. int &port) const {
  7130. return detail::get_remote_ip_and_port(sock_, ip, port);
  7131. }
  7132. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  7133. int &port) const {
  7134. return detail::get_local_ip_and_port(sock_, ip, port);
  7135. }
  7136. inline socket_t SocketStream::socket() const { return sock_; }
  7137. inline time_t SocketStream::duration() const {
  7138. return std::chrono::duration_cast<std::chrono::milliseconds>(
  7139. std::chrono::steady_clock::now() - start_time_)
  7140. .count();
  7141. }
  7142. // Buffer stream implementation
  7143. inline bool BufferStream::is_readable() const { return true; }
  7144. inline bool BufferStream::wait_readable() const { return true; }
  7145. inline bool BufferStream::wait_writable() const { return true; }
  7146. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  7147. #if defined(_MSC_VER) && _MSC_VER < 1910
  7148. auto len_read = buffer._Copy_s(ptr, size, size, position);
  7149. #else
  7150. auto len_read = buffer.copy(ptr, size, position);
  7151. #endif
  7152. position += static_cast<size_t>(len_read);
  7153. return static_cast<ssize_t>(len_read);
  7154. }
  7155. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  7156. buffer.append(ptr, size);
  7157. return static_cast<ssize_t>(size);
  7158. }
  7159. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  7160. int & /*port*/) const {}
  7161. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  7162. int & /*port*/) const {}
  7163. inline socket_t BufferStream::socket() const { return 0; }
  7164. inline time_t BufferStream::duration() const { return 0; }
  7165. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  7166. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  7167. : MatcherBase(pattern) {
  7168. constexpr const char marker[] = "/:";
  7169. // One past the last ending position of a path param substring
  7170. std::size_t last_param_end = 0;
  7171. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7172. // Needed to ensure that parameter names are unique during matcher
  7173. // construction
  7174. // If exceptions are disabled, only last duplicate path
  7175. // parameter will be set
  7176. std::unordered_set<std::string> param_name_set;
  7177. #endif
  7178. while (true) {
  7179. const auto marker_pos = pattern.find(
  7180. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  7181. if (marker_pos == std::string::npos) { break; }
  7182. static_fragments_.push_back(
  7183. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  7184. const auto param_name_start = marker_pos + str_len(marker);
  7185. auto sep_pos = pattern.find(separator, param_name_start);
  7186. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  7187. auto param_name =
  7188. pattern.substr(param_name_start, sep_pos - param_name_start);
  7189. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7190. if (param_name_set.find(param_name) != param_name_set.cend()) {
  7191. std::string msg = "Encountered path parameter '" + param_name +
  7192. "' multiple times in route pattern '" + pattern + "'.";
  7193. throw std::invalid_argument(msg);
  7194. }
  7195. #endif
  7196. param_names_.push_back(std::move(param_name));
  7197. last_param_end = sep_pos + 1;
  7198. }
  7199. if (last_param_end < pattern.length()) {
  7200. static_fragments_.push_back(pattern.substr(last_param_end));
  7201. }
  7202. }
  7203. inline bool PathParamsMatcher::match(Request &request) const {
  7204. request.matches = std::smatch();
  7205. request.path_params.clear();
  7206. request.path_params.reserve(param_names_.size());
  7207. // One past the position at which the path matched the pattern last time
  7208. std::size_t starting_pos = 0;
  7209. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  7210. const auto &fragment = static_fragments_[i];
  7211. if (starting_pos + fragment.length() > request.path.length()) {
  7212. return false;
  7213. }
  7214. // Avoid unnecessary allocation by using strncmp instead of substr +
  7215. // comparison
  7216. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  7217. fragment.length()) != 0) {
  7218. return false;
  7219. }
  7220. starting_pos += fragment.length();
  7221. // Should only happen when we have a static fragment after a param
  7222. // Example: '/users/:id/subscriptions'
  7223. // The 'subscriptions' fragment here does not have a corresponding param
  7224. if (i >= param_names_.size()) { continue; }
  7225. auto sep_pos = request.path.find(separator, starting_pos);
  7226. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  7227. const auto &param_name = param_names_[i];
  7228. request.path_params.emplace(
  7229. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  7230. // Mark everything up to '/' as matched
  7231. starting_pos = sep_pos + 1;
  7232. }
  7233. // Returns false if the path is longer than the pattern
  7234. return starting_pos >= request.path.length();
  7235. }
  7236. inline bool RegexMatcher::match(Request &request) const {
  7237. request.path_params.clear();
  7238. return std::regex_match(request.path, request.matches, regex_);
  7239. }
  7240. // Enclose IPv6 address in brackets if needed
  7241. inline std::string prepare_host_string(const std::string &host) {
  7242. // Enclose IPv6 address in brackets (but not if already enclosed)
  7243. if (host.find(':') == std::string::npos ||
  7244. (!host.empty() && host[0] == '[')) {
  7245. // IPv4, hostname, or already bracketed IPv6
  7246. return host;
  7247. } else {
  7248. // IPv6 address without brackets
  7249. return "[" + host + "]";
  7250. }
  7251. }
  7252. inline std::string make_host_and_port_string(const std::string &host, int port,
  7253. bool is_ssl) {
  7254. auto result = prepare_host_string(host);
  7255. // Append port if not default
  7256. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  7257. ; // do nothing
  7258. } else {
  7259. result += ":" + std::to_string(port);
  7260. }
  7261. return result;
  7262. }
  7263. // Create "host:port" string always including port number (for CONNECT method)
  7264. inline std::string
  7265. make_host_and_port_string_always_port(const std::string &host, int port) {
  7266. return prepare_host_string(host) + ":" + std::to_string(port);
  7267. }
  7268. template <typename T>
  7269. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  7270. T header_writer, Error &error) {
  7271. for (const auto &h : headers) {
  7272. if (!detail::fields::is_field_name(h.first) ||
  7273. !detail::fields::is_field_value(h.second)) {
  7274. error = Error::InvalidHeaders;
  7275. return false;
  7276. }
  7277. }
  7278. if (header_writer(strm, headers) <= 0) {
  7279. error = Error::Write;
  7280. return false;
  7281. }
  7282. return true;
  7283. }
  7284. } // namespace detail
  7285. // HTTP server implementation
  7286. inline Server::Server()
  7287. : new_task_queue(
  7288. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  7289. #ifndef _WIN32
  7290. signal(SIGPIPE, SIG_IGN);
  7291. #endif
  7292. }
  7293. inline Server::~Server() = default;
  7294. inline std::unique_ptr<detail::MatcherBase>
  7295. Server::make_matcher(const std::string &pattern) {
  7296. if (pattern.find("/:") != std::string::npos) {
  7297. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  7298. } else {
  7299. return detail::make_unique<detail::RegexMatcher>(pattern);
  7300. }
  7301. }
  7302. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  7303. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7304. return *this;
  7305. }
  7306. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  7307. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7308. return *this;
  7309. }
  7310. inline Server &Server::Post(const std::string &pattern,
  7311. HandlerWithContentReader handler) {
  7312. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7313. std::move(handler));
  7314. return *this;
  7315. }
  7316. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  7317. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7318. return *this;
  7319. }
  7320. inline Server &Server::Put(const std::string &pattern,
  7321. HandlerWithContentReader handler) {
  7322. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7323. std::move(handler));
  7324. return *this;
  7325. }
  7326. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  7327. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7328. return *this;
  7329. }
  7330. inline Server &Server::Patch(const std::string &pattern,
  7331. HandlerWithContentReader handler) {
  7332. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7333. std::move(handler));
  7334. return *this;
  7335. }
  7336. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  7337. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7338. return *this;
  7339. }
  7340. inline Server &Server::Delete(const std::string &pattern,
  7341. HandlerWithContentReader handler) {
  7342. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7343. std::move(handler));
  7344. return *this;
  7345. }
  7346. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  7347. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7348. return *this;
  7349. }
  7350. inline bool Server::set_base_dir(const std::string &dir,
  7351. const std::string &mount_point) {
  7352. return set_mount_point(mount_point, dir);
  7353. }
  7354. inline bool Server::set_mount_point(const std::string &mount_point,
  7355. const std::string &dir, Headers headers) {
  7356. detail::FileStat stat(dir);
  7357. if (stat.is_dir()) {
  7358. std::string mnt = !mount_point.empty() ? mount_point : "/";
  7359. if (!mnt.empty() && mnt[0] == '/') {
  7360. base_dirs_.push_back({std::move(mnt), dir, std::move(headers)});
  7361. return true;
  7362. }
  7363. }
  7364. return false;
  7365. }
  7366. inline bool Server::remove_mount_point(const std::string &mount_point) {
  7367. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  7368. if (it->mount_point == mount_point) {
  7369. base_dirs_.erase(it);
  7370. return true;
  7371. }
  7372. }
  7373. return false;
  7374. }
  7375. inline Server &
  7376. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  7377. const std::string &mime) {
  7378. file_extension_and_mimetype_map_[ext] = mime;
  7379. return *this;
  7380. }
  7381. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  7382. default_file_mimetype_ = mime;
  7383. return *this;
  7384. }
  7385. inline Server &Server::set_file_request_handler(Handler handler) {
  7386. file_request_handler_ = std::move(handler);
  7387. return *this;
  7388. }
  7389. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  7390. std::true_type) {
  7391. error_handler_ = std::move(handler);
  7392. return *this;
  7393. }
  7394. inline Server &Server::set_error_handler_core(Handler handler,
  7395. std::false_type) {
  7396. error_handler_ = [handler](const Request &req, Response &res) {
  7397. handler(req, res);
  7398. return HandlerResponse::Handled;
  7399. };
  7400. return *this;
  7401. }
  7402. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  7403. exception_handler_ = std::move(handler);
  7404. return *this;
  7405. }
  7406. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  7407. pre_routing_handler_ = std::move(handler);
  7408. return *this;
  7409. }
  7410. inline Server &Server::set_post_routing_handler(Handler handler) {
  7411. post_routing_handler_ = std::move(handler);
  7412. return *this;
  7413. }
  7414. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  7415. pre_request_handler_ = std::move(handler);
  7416. return *this;
  7417. }
  7418. inline Server &Server::set_logger(Logger logger) {
  7419. logger_ = std::move(logger);
  7420. return *this;
  7421. }
  7422. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  7423. error_logger_ = std::move(error_logger);
  7424. return *this;
  7425. }
  7426. inline Server &Server::set_pre_compression_logger(Logger logger) {
  7427. pre_compression_logger_ = std::move(logger);
  7428. return *this;
  7429. }
  7430. inline Server &
  7431. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  7432. expect_100_continue_handler_ = std::move(handler);
  7433. return *this;
  7434. }
  7435. inline Server &Server::set_address_family(int family) {
  7436. address_family_ = family;
  7437. return *this;
  7438. }
  7439. inline Server &Server::set_tcp_nodelay(bool on) {
  7440. tcp_nodelay_ = on;
  7441. return *this;
  7442. }
  7443. inline Server &Server::set_ipv6_v6only(bool on) {
  7444. ipv6_v6only_ = on;
  7445. return *this;
  7446. }
  7447. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  7448. socket_options_ = std::move(socket_options);
  7449. return *this;
  7450. }
  7451. inline Server &Server::set_default_headers(Headers headers) {
  7452. default_headers_ = std::move(headers);
  7453. return *this;
  7454. }
  7455. inline Server &Server::set_header_writer(
  7456. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7457. header_writer_ = writer;
  7458. return *this;
  7459. }
  7460. inline Server &
  7461. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  7462. trusted_proxies_ = proxies;
  7463. return *this;
  7464. }
  7465. inline Server &Server::set_keep_alive_max_count(size_t count) {
  7466. keep_alive_max_count_ = count;
  7467. return *this;
  7468. }
  7469. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  7470. keep_alive_timeout_sec_ = sec;
  7471. return *this;
  7472. }
  7473. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  7474. read_timeout_sec_ = sec;
  7475. read_timeout_usec_ = usec;
  7476. return *this;
  7477. }
  7478. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  7479. write_timeout_sec_ = sec;
  7480. write_timeout_usec_ = usec;
  7481. return *this;
  7482. }
  7483. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  7484. idle_interval_sec_ = sec;
  7485. idle_interval_usec_ = usec;
  7486. return *this;
  7487. }
  7488. inline Server &Server::set_payload_max_length(size_t length) {
  7489. payload_max_length_ = length;
  7490. return *this;
  7491. }
  7492. inline bool Server::bind_to_port(const std::string &host, int port,
  7493. int socket_flags) {
  7494. auto ret = bind_internal(host, port, socket_flags);
  7495. if (ret == -1) { is_decommissioned = true; }
  7496. return ret >= 0;
  7497. }
  7498. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  7499. auto ret = bind_internal(host, 0, socket_flags);
  7500. if (ret == -1) { is_decommissioned = true; }
  7501. return ret;
  7502. }
  7503. inline bool Server::listen_after_bind() { return listen_internal(); }
  7504. inline bool Server::listen(const std::string &host, int port,
  7505. int socket_flags) {
  7506. return bind_to_port(host, port, socket_flags) && listen_internal();
  7507. }
  7508. inline bool Server::is_running() const { return is_running_; }
  7509. inline void Server::wait_until_ready() const {
  7510. while (!is_running_ && !is_decommissioned) {
  7511. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7512. }
  7513. }
  7514. inline void Server::stop() {
  7515. if (is_running_) {
  7516. assert(svr_sock_ != INVALID_SOCKET);
  7517. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  7518. detail::shutdown_socket(sock);
  7519. detail::close_socket(sock);
  7520. }
  7521. is_decommissioned = false;
  7522. }
  7523. inline void Server::decommission() { is_decommissioned = true; }
  7524. inline bool Server::parse_request_line(const char *s, Request &req) const {
  7525. auto len = strlen(s);
  7526. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  7527. len -= 2;
  7528. {
  7529. size_t count = 0;
  7530. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  7531. switch (count) {
  7532. case 0: req.method = std::string(b, e); break;
  7533. case 1: req.target = std::string(b, e); break;
  7534. case 2: req.version = std::string(b, e); break;
  7535. default: break;
  7536. }
  7537. count++;
  7538. });
  7539. if (count != 3) { return false; }
  7540. }
  7541. thread_local const std::set<std::string> methods{
  7542. "GET", "HEAD", "POST", "PUT", "DELETE",
  7543. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7544. if (methods.find(req.method) == methods.end()) {
  7545. output_error_log(Error::InvalidHTTPMethod, &req);
  7546. return false;
  7547. }
  7548. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  7549. output_error_log(Error::InvalidHTTPVersion, &req);
  7550. return false;
  7551. }
  7552. {
  7553. // Skip URL fragment
  7554. for (size_t i = 0; i < req.target.size(); i++) {
  7555. if (req.target[i] == '#') {
  7556. req.target.erase(i);
  7557. break;
  7558. }
  7559. }
  7560. detail::divide(req.target, '?',
  7561. [&](const char *lhs_data, std::size_t lhs_size,
  7562. const char *rhs_data, std::size_t rhs_size) {
  7563. req.path =
  7564. decode_path_component(std::string(lhs_data, lhs_size));
  7565. detail::parse_query_text(rhs_data, rhs_size, req.params);
  7566. });
  7567. }
  7568. return true;
  7569. }
  7570. inline bool Server::write_response(Stream &strm, bool close_connection,
  7571. Request &req, Response &res) {
  7572. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  7573. // incorrectly to the error content.
  7574. req.ranges.clear();
  7575. return write_response_core(strm, close_connection, req, res, false);
  7576. }
  7577. inline bool Server::write_response_with_content(Stream &strm,
  7578. bool close_connection,
  7579. const Request &req,
  7580. Response &res) {
  7581. return write_response_core(strm, close_connection, req, res, true);
  7582. }
  7583. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  7584. const Request &req, Response &res,
  7585. bool need_apply_ranges) {
  7586. assert(res.status != -1);
  7587. if (400 <= res.status && error_handler_ &&
  7588. error_handler_(req, res) == HandlerResponse::Handled) {
  7589. need_apply_ranges = true;
  7590. }
  7591. std::string content_type;
  7592. std::string boundary;
  7593. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  7594. // Prepare additional headers
  7595. if (close_connection || req.get_header_value("Connection") == "close" ||
  7596. 400 <= res.status) { // Don't leave connections open after errors
  7597. res.set_header("Connection", "close");
  7598. } else {
  7599. std::string s = "timeout=";
  7600. s += std::to_string(keep_alive_timeout_sec_);
  7601. s += ", max=";
  7602. s += std::to_string(keep_alive_max_count_);
  7603. res.set_header("Keep-Alive", s);
  7604. }
  7605. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  7606. !res.has_header("Content-Type")) {
  7607. res.set_header("Content-Type", "text/plain");
  7608. }
  7609. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  7610. !res.has_header("Content-Length")) {
  7611. res.set_header("Content-Length", "0");
  7612. }
  7613. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  7614. res.set_header("Accept-Ranges", "bytes");
  7615. }
  7616. if (post_routing_handler_) { post_routing_handler_(req, res); }
  7617. // Response line and headers
  7618. {
  7619. detail::BufferStream bstrm;
  7620. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  7621. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  7622. // Flush buffer
  7623. auto &data = bstrm.get_buffer();
  7624. detail::write_data(strm, data.data(), data.size());
  7625. }
  7626. // Body
  7627. auto ret = true;
  7628. if (req.method != "HEAD") {
  7629. if (!res.body.empty()) {
  7630. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  7631. ret = false;
  7632. }
  7633. } else if (res.content_provider_) {
  7634. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  7635. res.content_provider_success_ = true;
  7636. } else {
  7637. ret = false;
  7638. }
  7639. }
  7640. }
  7641. // Log
  7642. output_log(req, res);
  7643. return ret;
  7644. }
  7645. inline bool
  7646. Server::write_content_with_provider(Stream &strm, const Request &req,
  7647. Response &res, const std::string &boundary,
  7648. const std::string &content_type) {
  7649. auto is_shutting_down = [this]() {
  7650. return this->svr_sock_ == INVALID_SOCKET;
  7651. };
  7652. if (res.content_length_ > 0) {
  7653. if (req.ranges.empty()) {
  7654. return detail::write_content(strm, res.content_provider_, 0,
  7655. res.content_length_, is_shutting_down);
  7656. } else if (req.ranges.size() == 1) {
  7657. auto offset_and_length = detail::get_range_offset_and_length(
  7658. req.ranges[0], res.content_length_);
  7659. return detail::write_content(strm, res.content_provider_,
  7660. offset_and_length.first,
  7661. offset_and_length.second, is_shutting_down);
  7662. } else {
  7663. return detail::write_multipart_ranges_data(
  7664. strm, req, res, boundary, content_type, res.content_length_,
  7665. is_shutting_down);
  7666. }
  7667. } else {
  7668. if (res.is_chunked_content_provider_) {
  7669. auto type = detail::encoding_type(req, res);
  7670. std::unique_ptr<detail::compressor> compressor;
  7671. if (type == detail::EncodingType::Gzip) {
  7672. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7673. compressor = detail::make_unique<detail::gzip_compressor>();
  7674. #endif
  7675. } else if (type == detail::EncodingType::Brotli) {
  7676. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7677. compressor = detail::make_unique<detail::brotli_compressor>();
  7678. #endif
  7679. } else if (type == detail::EncodingType::Zstd) {
  7680. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7681. compressor = detail::make_unique<detail::zstd_compressor>();
  7682. #endif
  7683. } else {
  7684. compressor = detail::make_unique<detail::nocompressor>();
  7685. }
  7686. assert(compressor != nullptr);
  7687. return detail::write_content_chunked(strm, res.content_provider_,
  7688. is_shutting_down, *compressor);
  7689. } else {
  7690. return detail::write_content_without_length(strm, res.content_provider_,
  7691. is_shutting_down);
  7692. }
  7693. }
  7694. }
  7695. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  7696. FormFields::iterator cur_field;
  7697. FormFiles::iterator cur_file;
  7698. auto is_text_field = false;
  7699. size_t count = 0;
  7700. if (read_content_core(
  7701. strm, req, res,
  7702. // Regular
  7703. [&](const char *buf, size_t n) {
  7704. // Prevent arithmetic overflow when checking sizes.
  7705. // Avoid computing (req.body.size() + n) directly because
  7706. // adding two unsigned `size_t` values can wrap around and
  7707. // produce a small result instead of indicating overflow.
  7708. // Instead, check using subtraction: ensure `n` does not
  7709. // exceed the remaining capacity `max_size() - size()`.
  7710. if (req.body.size() >= req.body.max_size() ||
  7711. n > req.body.max_size() - req.body.size()) {
  7712. return false;
  7713. }
  7714. // Limit decompressed body size to payload_max_length_ to protect
  7715. // against "zip bomb" attacks where a small compressed payload
  7716. // decompresses to a massive size.
  7717. if (payload_max_length_ > 0 &&
  7718. (req.body.size() >= payload_max_length_ ||
  7719. n > payload_max_length_ - req.body.size())) {
  7720. return false;
  7721. }
  7722. req.body.append(buf, n);
  7723. return true;
  7724. },
  7725. // Multipart FormData
  7726. [&](const FormData &file) {
  7727. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  7728. output_error_log(Error::TooManyFormDataFiles, &req);
  7729. return false;
  7730. }
  7731. if (file.filename.empty()) {
  7732. cur_field = req.form.fields.emplace(
  7733. file.name, FormField{file.name, file.content, file.headers});
  7734. is_text_field = true;
  7735. } else {
  7736. cur_file = req.form.files.emplace(file.name, file);
  7737. is_text_field = false;
  7738. }
  7739. return true;
  7740. },
  7741. [&](const char *buf, size_t n) {
  7742. if (is_text_field) {
  7743. auto &content = cur_field->second.content;
  7744. if (content.size() + n > content.max_size()) { return false; }
  7745. content.append(buf, n);
  7746. } else {
  7747. auto &content = cur_file->second.content;
  7748. if (content.size() + n > content.max_size()) { return false; }
  7749. content.append(buf, n);
  7750. }
  7751. return true;
  7752. })) {
  7753. const auto &content_type = req.get_header_value("Content-Type");
  7754. if (!content_type.find("application/x-www-form-urlencoded")) {
  7755. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  7756. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  7757. output_error_log(Error::ExceedMaxPayloadSize, &req);
  7758. return false;
  7759. }
  7760. detail::parse_query_text(req.body, req.params);
  7761. }
  7762. return true;
  7763. }
  7764. return false;
  7765. }
  7766. inline bool Server::read_content_with_content_receiver(
  7767. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7768. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  7769. return read_content_core(strm, req, res, std::move(receiver),
  7770. std::move(multipart_header),
  7771. std::move(multipart_receiver));
  7772. }
  7773. inline bool Server::read_content_core(
  7774. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7775. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  7776. detail::FormDataParser multipart_form_data_parser;
  7777. ContentReceiverWithProgress out;
  7778. if (req.is_multipart_form_data()) {
  7779. const auto &content_type = req.get_header_value("Content-Type");
  7780. std::string boundary;
  7781. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  7782. res.status = StatusCode::BadRequest_400;
  7783. output_error_log(Error::MultipartParsing, &req);
  7784. return false;
  7785. }
  7786. multipart_form_data_parser.set_boundary(std::move(boundary));
  7787. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  7788. return multipart_form_data_parser.parse(buf, n, multipart_header,
  7789. multipart_receiver);
  7790. };
  7791. } else {
  7792. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  7793. size_t /*len*/) { return receiver(buf, n); };
  7794. }
  7795. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  7796. // are true (no Transfer-Encoding and no Content-Length), then the message
  7797. // body length is zero (no message body is present).
  7798. //
  7799. // For non-SSL builds, peek into the socket to detect clients that send a
  7800. // body without a Content-Length header (raw HTTP over TCP). If there is
  7801. // pending data that exceeds the configured payload limit, treat this as an
  7802. // oversized request and fail early (causing connection close). For SSL
  7803. // builds we cannot reliably peek the decrypted application bytes, so keep
  7804. // the original behaviour.
  7805. #if !defined(CPPHTTPLIB_OPENSSL_SUPPORT)
  7806. if (!req.has_header("Content-Length") &&
  7807. !detail::is_chunked_transfer_encoding(req.headers)) {
  7808. // Only peek if payload_max_length is set to a finite value
  7809. if (payload_max_length_ > 0 &&
  7810. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  7811. socket_t s = strm.socket();
  7812. if (s != INVALID_SOCKET) {
  7813. // Peek to check if there is any pending data
  7814. char peekbuf[1];
  7815. ssize_t n = ::recv(s, peekbuf, 1, MSG_PEEK);
  7816. if (n > 0) {
  7817. // There is data, so read it with payload limit enforcement
  7818. auto result = detail::read_content_without_length(
  7819. strm, payload_max_length_, out);
  7820. if (result == detail::ReadContentResult::PayloadTooLarge) {
  7821. res.status = StatusCode::PayloadTooLarge_413;
  7822. return false;
  7823. } else if (result != detail::ReadContentResult::Success) {
  7824. return false;
  7825. }
  7826. return true;
  7827. }
  7828. }
  7829. }
  7830. return true;
  7831. }
  7832. #else
  7833. if (!req.has_header("Content-Length") &&
  7834. !detail::is_chunked_transfer_encoding(req.headers)) {
  7835. return true;
  7836. }
  7837. #endif
  7838. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  7839. out, true)) {
  7840. return false;
  7841. }
  7842. if (req.is_multipart_form_data()) {
  7843. if (!multipart_form_data_parser.is_valid()) {
  7844. res.status = StatusCode::BadRequest_400;
  7845. output_error_log(Error::MultipartParsing, &req);
  7846. return false;
  7847. }
  7848. }
  7849. return true;
  7850. }
  7851. inline bool Server::handle_file_request(Request &req, Response &res) {
  7852. for (const auto &entry : base_dirs_) {
  7853. // Prefix match
  7854. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  7855. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  7856. if (detail::is_valid_path(sub_path)) {
  7857. auto path = entry.base_dir + sub_path;
  7858. if (path.back() == '/') { path += "index.html"; }
  7859. detail::FileStat stat(path);
  7860. if (stat.is_dir()) {
  7861. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  7862. return true;
  7863. }
  7864. if (stat.is_file()) {
  7865. for (const auto &kv : entry.headers) {
  7866. res.set_header(kv.first, kv.second);
  7867. }
  7868. auto etag = detail::compute_etag(stat);
  7869. if (!etag.empty()) { res.set_header("ETag", etag); }
  7870. auto mtime = stat.mtime();
  7871. auto last_modified = detail::file_mtime_to_http_date(mtime);
  7872. if (!last_modified.empty()) {
  7873. res.set_header("Last-Modified", last_modified);
  7874. }
  7875. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  7876. check_if_range(req, etag, mtime);
  7877. auto mm = std::make_shared<detail::mmap>(path.c_str());
  7878. if (!mm->is_open()) {
  7879. output_error_log(Error::OpenFile, &req);
  7880. return false;
  7881. }
  7882. res.set_content_provider(
  7883. mm->size(),
  7884. detail::find_content_type(path, file_extension_and_mimetype_map_,
  7885. default_file_mimetype_),
  7886. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  7887. sink.write(mm->data() + offset, length);
  7888. return true;
  7889. });
  7890. if (req.method != "HEAD" && file_request_handler_) {
  7891. file_request_handler_(req, res);
  7892. }
  7893. return true;
  7894. } else {
  7895. output_error_log(Error::OpenFile, &req);
  7896. }
  7897. }
  7898. }
  7899. }
  7900. return false;
  7901. }
  7902. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  7903. const std::string &etag,
  7904. time_t mtime) const {
  7905. // Handle conditional GET:
  7906. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  7907. // 2. If-Modified-Since is checked only when If-None-Match is absent
  7908. if (req.has_header("If-None-Match")) {
  7909. if (!etag.empty()) {
  7910. auto val = req.get_header_value("If-None-Match");
  7911. // NOTE: We use exact string matching here. This works correctly
  7912. // because our server always generates weak ETags (W/"..."), and
  7913. // clients typically send back the same ETag they received.
  7914. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  7915. // If-None-Match, where W/"x" and "x" would match, but this
  7916. // simplified implementation requires exact matches.
  7917. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  7918. [&](const char *b, const char *e) {
  7919. return std::equal(b, e, "*") ||
  7920. std::equal(b, e, etag.begin());
  7921. });
  7922. if (ret) {
  7923. res.status = StatusCode::NotModified_304;
  7924. return true;
  7925. }
  7926. }
  7927. } else if (req.has_header("If-Modified-Since")) {
  7928. auto val = req.get_header_value("If-Modified-Since");
  7929. auto t = detail::parse_http_date(val);
  7930. if (t != static_cast<time_t>(-1) && mtime <= t) {
  7931. res.status = StatusCode::NotModified_304;
  7932. return true;
  7933. }
  7934. }
  7935. return false;
  7936. }
  7937. inline bool Server::check_if_range(Request &req, const std::string &etag,
  7938. time_t mtime) const {
  7939. // Handle If-Range for partial content requests (RFC 9110
  7940. // Section 13.1.5). If-Range is only evaluated when Range header is
  7941. // present. If the validator matches, serve partial content; otherwise
  7942. // serve full content.
  7943. if (!req.ranges.empty() && req.has_header("If-Range")) {
  7944. auto val = req.get_header_value("If-Range");
  7945. auto is_valid_range = [&]() {
  7946. if (detail::is_strong_etag(val)) {
  7947. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  7948. // comparison.
  7949. return (!etag.empty() && val == etag);
  7950. } else if (detail::is_weak_etag(val)) {
  7951. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  7952. return false;
  7953. } else {
  7954. // HTTP-date comparison
  7955. auto t = detail::parse_http_date(val);
  7956. return (t != static_cast<time_t>(-1) && mtime <= t);
  7957. }
  7958. };
  7959. if (!is_valid_range()) {
  7960. // Validator doesn't match: ignore Range and serve full content
  7961. req.ranges.clear();
  7962. return false;
  7963. }
  7964. }
  7965. return true;
  7966. }
  7967. inline socket_t
  7968. Server::create_server_socket(const std::string &host, int port,
  7969. int socket_flags,
  7970. SocketOptions socket_options) const {
  7971. return detail::create_socket(
  7972. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  7973. ipv6_v6only_, std::move(socket_options),
  7974. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  7975. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  7976. output_error_log(Error::BindIPAddress, nullptr);
  7977. return false;
  7978. }
  7979. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  7980. output_error_log(Error::Listen, nullptr);
  7981. return false;
  7982. }
  7983. return true;
  7984. });
  7985. }
  7986. inline int Server::bind_internal(const std::string &host, int port,
  7987. int socket_flags) {
  7988. if (is_decommissioned) { return -1; }
  7989. if (!is_valid()) { return -1; }
  7990. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  7991. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  7992. if (port == 0) {
  7993. struct sockaddr_storage addr;
  7994. socklen_t addr_len = sizeof(addr);
  7995. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  7996. &addr_len) == -1) {
  7997. output_error_log(Error::GetSockName, nullptr);
  7998. return -1;
  7999. }
  8000. if (addr.ss_family == AF_INET) {
  8001. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  8002. } else if (addr.ss_family == AF_INET6) {
  8003. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  8004. } else {
  8005. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  8006. return -1;
  8007. }
  8008. } else {
  8009. return port;
  8010. }
  8011. }
  8012. inline bool Server::listen_internal() {
  8013. if (is_decommissioned) { return false; }
  8014. auto ret = true;
  8015. is_running_ = true;
  8016. auto se = detail::scope_exit([&]() { is_running_ = false; });
  8017. {
  8018. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  8019. while (svr_sock_ != INVALID_SOCKET) {
  8020. #ifndef _WIN32
  8021. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  8022. #endif
  8023. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  8024. idle_interval_usec_);
  8025. if (val == 0) { // Timeout
  8026. task_queue->on_idle();
  8027. continue;
  8028. }
  8029. #ifndef _WIN32
  8030. }
  8031. #endif
  8032. #if defined _WIN32
  8033. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  8034. // OVERLAPPED
  8035. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  8036. #elif defined SOCK_CLOEXEC
  8037. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  8038. #else
  8039. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  8040. #endif
  8041. if (sock == INVALID_SOCKET) {
  8042. if (errno == EMFILE) {
  8043. // The per-process limit of open file descriptors has been reached.
  8044. // Try to accept new connections after a short sleep.
  8045. std::this_thread::sleep_for(std::chrono::microseconds{1});
  8046. continue;
  8047. } else if (errno == EINTR || errno == EAGAIN) {
  8048. continue;
  8049. }
  8050. if (svr_sock_ != INVALID_SOCKET) {
  8051. detail::close_socket(svr_sock_);
  8052. ret = false;
  8053. output_error_log(Error::Connection, nullptr);
  8054. } else {
  8055. ; // The server socket was closed by user.
  8056. }
  8057. break;
  8058. }
  8059. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  8060. read_timeout_sec_, read_timeout_usec_);
  8061. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  8062. write_timeout_sec_, write_timeout_usec_);
  8063. if (!task_queue->enqueue(
  8064. [this, sock]() { process_and_close_socket(sock); })) {
  8065. output_error_log(Error::ResourceExhaustion, nullptr);
  8066. detail::shutdown_socket(sock);
  8067. detail::close_socket(sock);
  8068. }
  8069. }
  8070. task_queue->shutdown();
  8071. }
  8072. is_decommissioned = !ret;
  8073. return ret;
  8074. }
  8075. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  8076. if (pre_routing_handler_ &&
  8077. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  8078. return true;
  8079. }
  8080. // File handler
  8081. if ((req.method == "GET" || req.method == "HEAD") &&
  8082. handle_file_request(req, res)) {
  8083. return true;
  8084. }
  8085. if (detail::expect_content(req)) {
  8086. // Content reader handler
  8087. {
  8088. ContentReader reader(
  8089. [&](ContentReceiver receiver) {
  8090. auto result = read_content_with_content_receiver(
  8091. strm, req, res, std::move(receiver), nullptr, nullptr);
  8092. if (!result) { output_error_log(Error::Read, &req); }
  8093. return result;
  8094. },
  8095. [&](FormDataHeader header, ContentReceiver receiver) {
  8096. auto result = read_content_with_content_receiver(
  8097. strm, req, res, nullptr, std::move(header),
  8098. std::move(receiver));
  8099. if (!result) { output_error_log(Error::Read, &req); }
  8100. return result;
  8101. });
  8102. if (req.method == "POST") {
  8103. if (dispatch_request_for_content_reader(
  8104. req, res, std::move(reader),
  8105. post_handlers_for_content_reader_)) {
  8106. return true;
  8107. }
  8108. } else if (req.method == "PUT") {
  8109. if (dispatch_request_for_content_reader(
  8110. req, res, std::move(reader),
  8111. put_handlers_for_content_reader_)) {
  8112. return true;
  8113. }
  8114. } else if (req.method == "PATCH") {
  8115. if (dispatch_request_for_content_reader(
  8116. req, res, std::move(reader),
  8117. patch_handlers_for_content_reader_)) {
  8118. return true;
  8119. }
  8120. } else if (req.method == "DELETE") {
  8121. if (dispatch_request_for_content_reader(
  8122. req, res, std::move(reader),
  8123. delete_handlers_for_content_reader_)) {
  8124. return true;
  8125. }
  8126. }
  8127. }
  8128. // Read content into `req.body`
  8129. if (!read_content(strm, req, res)) {
  8130. output_error_log(Error::Read, &req);
  8131. return false;
  8132. }
  8133. }
  8134. // Regular handler
  8135. if (req.method == "GET" || req.method == "HEAD") {
  8136. return dispatch_request(req, res, get_handlers_);
  8137. } else if (req.method == "POST") {
  8138. return dispatch_request(req, res, post_handlers_);
  8139. } else if (req.method == "PUT") {
  8140. return dispatch_request(req, res, put_handlers_);
  8141. } else if (req.method == "DELETE") {
  8142. return dispatch_request(req, res, delete_handlers_);
  8143. } else if (req.method == "OPTIONS") {
  8144. return dispatch_request(req, res, options_handlers_);
  8145. } else if (req.method == "PATCH") {
  8146. return dispatch_request(req, res, patch_handlers_);
  8147. }
  8148. res.status = StatusCode::BadRequest_400;
  8149. return false;
  8150. }
  8151. inline bool Server::dispatch_request(Request &req, Response &res,
  8152. const Handlers &handlers) const {
  8153. for (const auto &x : handlers) {
  8154. const auto &matcher = x.first;
  8155. const auto &handler = x.second;
  8156. if (matcher->match(req)) {
  8157. req.matched_route = matcher->pattern();
  8158. if (!pre_request_handler_ ||
  8159. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8160. handler(req, res);
  8161. }
  8162. return true;
  8163. }
  8164. }
  8165. return false;
  8166. }
  8167. inline void Server::apply_ranges(const Request &req, Response &res,
  8168. std::string &content_type,
  8169. std::string &boundary) const {
  8170. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  8171. auto it = res.headers.find("Content-Type");
  8172. if (it != res.headers.end()) {
  8173. content_type = it->second;
  8174. res.headers.erase(it);
  8175. }
  8176. boundary = detail::make_multipart_data_boundary();
  8177. res.set_header("Content-Type",
  8178. "multipart/byteranges; boundary=" + boundary);
  8179. }
  8180. auto type = detail::encoding_type(req, res);
  8181. if (res.body.empty()) {
  8182. if (res.content_length_ > 0) {
  8183. size_t length = 0;
  8184. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8185. length = res.content_length_;
  8186. } else if (req.ranges.size() == 1) {
  8187. auto offset_and_length = detail::get_range_offset_and_length(
  8188. req.ranges[0], res.content_length_);
  8189. length = offset_and_length.second;
  8190. auto content_range = detail::make_content_range_header_field(
  8191. offset_and_length, res.content_length_);
  8192. res.set_header("Content-Range", content_range);
  8193. } else {
  8194. length = detail::get_multipart_ranges_data_length(
  8195. req, boundary, content_type, res.content_length_);
  8196. }
  8197. res.set_header("Content-Length", std::to_string(length));
  8198. } else {
  8199. if (res.content_provider_) {
  8200. if (res.is_chunked_content_provider_) {
  8201. res.set_header("Transfer-Encoding", "chunked");
  8202. if (type == detail::EncodingType::Gzip) {
  8203. res.set_header("Content-Encoding", "gzip");
  8204. res.set_header("Vary", "Accept-Encoding");
  8205. } else if (type == detail::EncodingType::Brotli) {
  8206. res.set_header("Content-Encoding", "br");
  8207. res.set_header("Vary", "Accept-Encoding");
  8208. } else if (type == detail::EncodingType::Zstd) {
  8209. res.set_header("Content-Encoding", "zstd");
  8210. res.set_header("Vary", "Accept-Encoding");
  8211. }
  8212. }
  8213. }
  8214. }
  8215. } else {
  8216. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8217. ;
  8218. } else if (req.ranges.size() == 1) {
  8219. auto offset_and_length =
  8220. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  8221. auto offset = offset_and_length.first;
  8222. auto length = offset_and_length.second;
  8223. auto content_range = detail::make_content_range_header_field(
  8224. offset_and_length, res.body.size());
  8225. res.set_header("Content-Range", content_range);
  8226. assert(offset + length <= res.body.size());
  8227. res.body = res.body.substr(offset, length);
  8228. } else {
  8229. std::string data;
  8230. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  8231. res.body.size(), data);
  8232. res.body.swap(data);
  8233. }
  8234. if (type != detail::EncodingType::None) {
  8235. output_pre_compression_log(req, res);
  8236. std::unique_ptr<detail::compressor> compressor;
  8237. std::string content_encoding;
  8238. if (type == detail::EncodingType::Gzip) {
  8239. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8240. compressor = detail::make_unique<detail::gzip_compressor>();
  8241. content_encoding = "gzip";
  8242. #endif
  8243. } else if (type == detail::EncodingType::Brotli) {
  8244. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8245. compressor = detail::make_unique<detail::brotli_compressor>();
  8246. content_encoding = "br";
  8247. #endif
  8248. } else if (type == detail::EncodingType::Zstd) {
  8249. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8250. compressor = detail::make_unique<detail::zstd_compressor>();
  8251. content_encoding = "zstd";
  8252. #endif
  8253. }
  8254. if (compressor) {
  8255. std::string compressed;
  8256. if (compressor->compress(res.body.data(), res.body.size(), true,
  8257. [&](const char *data, size_t data_len) {
  8258. compressed.append(data, data_len);
  8259. return true;
  8260. })) {
  8261. res.body.swap(compressed);
  8262. res.set_header("Content-Encoding", content_encoding);
  8263. res.set_header("Vary", "Accept-Encoding");
  8264. }
  8265. }
  8266. }
  8267. auto length = std::to_string(res.body.size());
  8268. res.set_header("Content-Length", length);
  8269. }
  8270. }
  8271. inline bool Server::dispatch_request_for_content_reader(
  8272. Request &req, Response &res, ContentReader content_reader,
  8273. const HandlersForContentReader &handlers) const {
  8274. for (const auto &x : handlers) {
  8275. const auto &matcher = x.first;
  8276. const auto &handler = x.second;
  8277. if (matcher->match(req)) {
  8278. req.matched_route = matcher->pattern();
  8279. if (!pre_request_handler_ ||
  8280. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8281. handler(req, res, content_reader);
  8282. }
  8283. return true;
  8284. }
  8285. }
  8286. return false;
  8287. }
  8288. inline std::string
  8289. get_client_ip(const std::string &x_forwarded_for,
  8290. const std::vector<std::string> &trusted_proxies) {
  8291. // X-Forwarded-For is a comma-separated list per RFC 7239
  8292. std::vector<std::string> ip_list;
  8293. detail::split(x_forwarded_for.data(),
  8294. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  8295. [&](const char *b, const char *e) {
  8296. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  8297. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  8298. });
  8299. for (size_t i = 0; i < ip_list.size(); ++i) {
  8300. auto ip = ip_list[i];
  8301. auto is_trusted_proxy =
  8302. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  8303. [&](const std::string &proxy) { return ip == proxy; });
  8304. if (is_trusted_proxy) {
  8305. if (i == 0) {
  8306. // If the trusted proxy is the first IP, there's no preceding client IP
  8307. return ip;
  8308. } else {
  8309. // Return the IP immediately before the trusted proxy
  8310. return ip_list[i - 1];
  8311. }
  8312. }
  8313. }
  8314. // If no trusted proxy is found, return the first IP in the list
  8315. return ip_list.front();
  8316. }
  8317. inline bool
  8318. Server::process_request(Stream &strm, const std::string &remote_addr,
  8319. int remote_port, const std::string &local_addr,
  8320. int local_port, bool close_connection,
  8321. bool &connection_closed,
  8322. const std::function<void(Request &)> &setup_request) {
  8323. std::array<char, 2048> buf{};
  8324. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8325. // Connection has been closed on client
  8326. if (!line_reader.getline()) { return false; }
  8327. Request req;
  8328. req.start_time_ = std::chrono::steady_clock::now();
  8329. req.remote_addr = remote_addr;
  8330. req.remote_port = remote_port;
  8331. req.local_addr = local_addr;
  8332. req.local_port = local_port;
  8333. Response res;
  8334. res.version = "HTTP/1.1";
  8335. res.headers = default_headers_;
  8336. #ifdef __APPLE__
  8337. // Socket file descriptor exceeded FD_SETSIZE...
  8338. if (strm.socket() >= FD_SETSIZE) {
  8339. Headers dummy;
  8340. detail::read_headers(strm, dummy);
  8341. res.status = StatusCode::InternalServerError_500;
  8342. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  8343. return write_response(strm, close_connection, req, res);
  8344. }
  8345. #endif
  8346. // Request line and headers
  8347. if (!parse_request_line(line_reader.ptr(), req)) {
  8348. res.status = StatusCode::BadRequest_400;
  8349. output_error_log(Error::InvalidRequestLine, &req);
  8350. return write_response(strm, close_connection, req, res);
  8351. }
  8352. // Request headers
  8353. if (!detail::read_headers(strm, req.headers)) {
  8354. res.status = StatusCode::BadRequest_400;
  8355. output_error_log(Error::InvalidHeaders, &req);
  8356. return write_response(strm, close_connection, req, res);
  8357. }
  8358. // Check if the request URI doesn't exceed the limit
  8359. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  8360. res.status = StatusCode::UriTooLong_414;
  8361. output_error_log(Error::ExceedUriMaxLength, &req);
  8362. return write_response(strm, close_connection, req, res);
  8363. }
  8364. if (req.get_header_value("Connection") == "close") {
  8365. connection_closed = true;
  8366. }
  8367. if (req.version == "HTTP/1.0" &&
  8368. req.get_header_value("Connection") != "Keep-Alive") {
  8369. connection_closed = true;
  8370. }
  8371. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  8372. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  8373. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  8374. } else {
  8375. req.remote_addr = remote_addr;
  8376. }
  8377. req.remote_port = remote_port;
  8378. req.local_addr = local_addr;
  8379. req.local_port = local_port;
  8380. if (req.has_header("Accept")) {
  8381. const auto &accept_header = req.get_header_value("Accept");
  8382. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  8383. res.status = StatusCode::BadRequest_400;
  8384. output_error_log(Error::HTTPParsing, &req);
  8385. return write_response(strm, close_connection, req, res);
  8386. }
  8387. }
  8388. if (req.has_header("Range")) {
  8389. const auto &range_header_value = req.get_header_value("Range");
  8390. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  8391. res.status = StatusCode::RangeNotSatisfiable_416;
  8392. output_error_log(Error::InvalidRangeHeader, &req);
  8393. return write_response(strm, close_connection, req, res);
  8394. }
  8395. }
  8396. if (setup_request) { setup_request(req); }
  8397. if (req.get_header_value("Expect") == "100-continue") {
  8398. int status = StatusCode::Continue_100;
  8399. if (expect_100_continue_handler_) {
  8400. status = expect_100_continue_handler_(req, res);
  8401. }
  8402. switch (status) {
  8403. case StatusCode::Continue_100:
  8404. case StatusCode::ExpectationFailed_417:
  8405. detail::write_response_line(strm, status);
  8406. strm.write("\r\n");
  8407. break;
  8408. default:
  8409. connection_closed = true;
  8410. return write_response(strm, true, req, res);
  8411. }
  8412. }
  8413. // Setup `is_connection_closed` method
  8414. auto sock = strm.socket();
  8415. req.is_connection_closed = [sock]() {
  8416. return !detail::is_socket_alive(sock);
  8417. };
  8418. // Routing
  8419. auto routed = false;
  8420. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8421. routed = routing(req, res, strm);
  8422. #else
  8423. try {
  8424. routed = routing(req, res, strm);
  8425. } catch (std::exception &e) {
  8426. if (exception_handler_) {
  8427. auto ep = std::current_exception();
  8428. exception_handler_(req, res, ep);
  8429. routed = true;
  8430. } else {
  8431. res.status = StatusCode::InternalServerError_500;
  8432. std::string val;
  8433. auto s = e.what();
  8434. for (size_t i = 0; s[i]; i++) {
  8435. switch (s[i]) {
  8436. case '\r': val += "\\r"; break;
  8437. case '\n': val += "\\n"; break;
  8438. default: val += s[i]; break;
  8439. }
  8440. }
  8441. res.set_header("EXCEPTION_WHAT", val);
  8442. }
  8443. } catch (...) {
  8444. if (exception_handler_) {
  8445. auto ep = std::current_exception();
  8446. exception_handler_(req, res, ep);
  8447. routed = true;
  8448. } else {
  8449. res.status = StatusCode::InternalServerError_500;
  8450. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  8451. }
  8452. }
  8453. #endif
  8454. if (routed) {
  8455. if (res.status == -1) {
  8456. res.status = req.ranges.empty() ? StatusCode::OK_200
  8457. : StatusCode::PartialContent_206;
  8458. }
  8459. // Serve file content by using a content provider
  8460. if (!res.file_content_path_.empty()) {
  8461. const auto &path = res.file_content_path_;
  8462. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8463. if (!mm->is_open()) {
  8464. res.body.clear();
  8465. res.content_length_ = 0;
  8466. res.content_provider_ = nullptr;
  8467. res.status = StatusCode::NotFound_404;
  8468. output_error_log(Error::OpenFile, &req);
  8469. return write_response(strm, close_connection, req, res);
  8470. }
  8471. auto content_type = res.file_content_content_type_;
  8472. if (content_type.empty()) {
  8473. content_type = detail::find_content_type(
  8474. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  8475. }
  8476. res.set_content_provider(
  8477. mm->size(), content_type,
  8478. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8479. sink.write(mm->data() + offset, length);
  8480. return true;
  8481. });
  8482. }
  8483. if (detail::range_error(req, res)) {
  8484. res.body.clear();
  8485. res.content_length_ = 0;
  8486. res.content_provider_ = nullptr;
  8487. res.status = StatusCode::RangeNotSatisfiable_416;
  8488. return write_response(strm, close_connection, req, res);
  8489. }
  8490. return write_response_with_content(strm, close_connection, req, res);
  8491. } else {
  8492. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  8493. return write_response(strm, close_connection, req, res);
  8494. }
  8495. }
  8496. inline bool Server::is_valid() const { return true; }
  8497. inline bool Server::process_and_close_socket(socket_t sock) {
  8498. std::string remote_addr;
  8499. int remote_port = 0;
  8500. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8501. std::string local_addr;
  8502. int local_port = 0;
  8503. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8504. auto ret = detail::process_server_socket(
  8505. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8506. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8507. write_timeout_usec_,
  8508. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8509. return process_request(strm, remote_addr, remote_port, local_addr,
  8510. local_port, close_connection, connection_closed,
  8511. nullptr);
  8512. });
  8513. detail::shutdown_socket(sock);
  8514. detail::close_socket(sock);
  8515. return ret;
  8516. }
  8517. inline void Server::output_log(const Request &req, const Response &res) const {
  8518. if (logger_) {
  8519. std::lock_guard<std::mutex> guard(logger_mutex_);
  8520. logger_(req, res);
  8521. }
  8522. }
  8523. inline void Server::output_pre_compression_log(const Request &req,
  8524. const Response &res) const {
  8525. if (pre_compression_logger_) {
  8526. std::lock_guard<std::mutex> guard(logger_mutex_);
  8527. pre_compression_logger_(req, res);
  8528. }
  8529. }
  8530. inline void Server::output_error_log(const Error &err,
  8531. const Request *req) const {
  8532. if (error_logger_) {
  8533. std::lock_guard<std::mutex> guard(logger_mutex_);
  8534. error_logger_(err, req);
  8535. }
  8536. }
  8537. // HTTP client implementation
  8538. inline ClientImpl::ClientImpl(const std::string &host)
  8539. : ClientImpl(host, 80, std::string(), std::string()) {}
  8540. inline ClientImpl::ClientImpl(const std::string &host, int port)
  8541. : ClientImpl(host, port, std::string(), std::string()) {}
  8542. inline ClientImpl::ClientImpl(const std::string &host, int port,
  8543. const std::string &client_cert_path,
  8544. const std::string &client_key_path)
  8545. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  8546. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  8547. inline ClientImpl::~ClientImpl() {
  8548. // Wait until all the requests in flight are handled.
  8549. size_t retry_count = 10;
  8550. while (retry_count-- > 0) {
  8551. {
  8552. std::lock_guard<std::mutex> guard(socket_mutex_);
  8553. if (socket_requests_in_flight_ == 0) { break; }
  8554. }
  8555. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  8556. }
  8557. std::lock_guard<std::mutex> guard(socket_mutex_);
  8558. shutdown_socket(socket_);
  8559. close_socket(socket_);
  8560. }
  8561. inline bool ClientImpl::is_valid() const { return true; }
  8562. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  8563. client_cert_path_ = rhs.client_cert_path_;
  8564. client_key_path_ = rhs.client_key_path_;
  8565. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  8566. read_timeout_sec_ = rhs.read_timeout_sec_;
  8567. read_timeout_usec_ = rhs.read_timeout_usec_;
  8568. write_timeout_sec_ = rhs.write_timeout_sec_;
  8569. write_timeout_usec_ = rhs.write_timeout_usec_;
  8570. max_timeout_msec_ = rhs.max_timeout_msec_;
  8571. basic_auth_username_ = rhs.basic_auth_username_;
  8572. basic_auth_password_ = rhs.basic_auth_password_;
  8573. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  8574. #ifdef CPPHTTPLIB_SSL_ENABLED
  8575. digest_auth_username_ = rhs.digest_auth_username_;
  8576. digest_auth_password_ = rhs.digest_auth_password_;
  8577. #endif
  8578. keep_alive_ = rhs.keep_alive_;
  8579. follow_location_ = rhs.follow_location_;
  8580. path_encode_ = rhs.path_encode_;
  8581. address_family_ = rhs.address_family_;
  8582. tcp_nodelay_ = rhs.tcp_nodelay_;
  8583. ipv6_v6only_ = rhs.ipv6_v6only_;
  8584. socket_options_ = rhs.socket_options_;
  8585. compress_ = rhs.compress_;
  8586. decompress_ = rhs.decompress_;
  8587. interface_ = rhs.interface_;
  8588. proxy_host_ = rhs.proxy_host_;
  8589. proxy_port_ = rhs.proxy_port_;
  8590. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  8591. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  8592. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  8593. #ifdef CPPHTTPLIB_SSL_ENABLED
  8594. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  8595. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  8596. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  8597. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  8598. server_certificate_verification_ = rhs.server_certificate_verification_;
  8599. server_hostname_verification_ = rhs.server_hostname_verification_;
  8600. #endif
  8601. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8602. ca_cert_store_ = rhs.ca_cert_store_;
  8603. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  8604. #endif
  8605. logger_ = rhs.logger_;
  8606. error_logger_ = rhs.error_logger_;
  8607. }
  8608. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  8609. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8610. return detail::create_client_socket(
  8611. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  8612. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  8613. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  8614. write_timeout_sec_, write_timeout_usec_, interface_, error);
  8615. }
  8616. // Check is custom IP specified for host_
  8617. std::string ip;
  8618. auto it = addr_map_.find(host_);
  8619. if (it != addr_map_.end()) { ip = it->second; }
  8620. return detail::create_client_socket(
  8621. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  8622. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  8623. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8624. write_timeout_usec_, interface_, error);
  8625. }
  8626. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  8627. Error &error) {
  8628. auto sock = create_client_socket(error);
  8629. if (sock == INVALID_SOCKET) { return false; }
  8630. socket.sock = sock;
  8631. return true;
  8632. }
  8633. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  8634. return create_and_connect_socket(socket, error);
  8635. }
  8636. #ifdef CPPHTTPLIB_SSL_ENABLED
  8637. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  8638. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  8639. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  8640. if (!initialize_ssl(socket, error)) {
  8641. shutdown_socket(socket);
  8642. close_socket(socket);
  8643. return false;
  8644. }
  8645. return true;
  8646. }
  8647. #endif
  8648. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  8649. bool /*shutdown_gracefully*/) {
  8650. // If there are any requests in flight from threads other than us, then it's
  8651. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  8652. assert(socket_requests_in_flight_ == 0 ||
  8653. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8654. }
  8655. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  8656. if (socket.sock == INVALID_SOCKET) { return; }
  8657. detail::shutdown_socket(socket.sock);
  8658. }
  8659. inline void ClientImpl::close_socket(Socket &socket) {
  8660. // If there are requests in flight in another thread, usually closing
  8661. // the socket will be fine and they will simply receive an error when
  8662. // using the closed socket, but it is still a bug since rarely the OS
  8663. // may reassign the socket id to be used for a new socket, and then
  8664. // suddenly they will be operating on a live socket that is different
  8665. // than the one they intended!
  8666. assert(socket_requests_in_flight_ == 0 ||
  8667. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8668. // It is also a bug if this happens while SSL is still active
  8669. #ifdef CPPHTTPLIB_SSL_ENABLED
  8670. assert(socket.ssl == nullptr);
  8671. #endif
  8672. if (socket.sock == INVALID_SOCKET) { return; }
  8673. detail::close_socket(socket.sock);
  8674. socket.sock = INVALID_SOCKET;
  8675. }
  8676. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  8677. Response &res,
  8678. bool skip_100_continue) const {
  8679. std::array<char, 2048> buf{};
  8680. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8681. if (!line_reader.getline()) { return false; }
  8682. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  8683. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  8684. #else
  8685. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  8686. #endif
  8687. std::cmatch m;
  8688. if (!std::regex_match(line_reader.ptr(), m, re)) {
  8689. return req.method == "CONNECT";
  8690. }
  8691. res.version = std::string(m[1]);
  8692. res.status = std::stoi(std::string(m[2]));
  8693. res.reason = std::string(m[3]);
  8694. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  8695. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  8696. if (!line_reader.getline()) { return false; } // CRLF
  8697. if (!line_reader.getline()) { return false; } // next response line
  8698. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  8699. res.version = std::string(m[1]);
  8700. res.status = std::stoi(std::string(m[2]));
  8701. res.reason = std::string(m[3]);
  8702. }
  8703. return true;
  8704. }
  8705. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  8706. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  8707. auto ret = send_(req, res, error);
  8708. if (error == Error::SSLPeerCouldBeClosed_) {
  8709. assert(!ret);
  8710. ret = send_(req, res, error);
  8711. }
  8712. return ret;
  8713. }
  8714. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  8715. {
  8716. std::lock_guard<std::mutex> guard(socket_mutex_);
  8717. // Set this to false immediately - if it ever gets set to true by the end
  8718. // of the request, we know another thread instructed us to close the
  8719. // socket.
  8720. socket_should_be_closed_when_request_is_done_ = false;
  8721. auto is_alive = false;
  8722. if (socket_.is_open()) {
  8723. is_alive = detail::is_socket_alive(socket_.sock);
  8724. #ifdef CPPHTTPLIB_SSL_ENABLED
  8725. if (is_alive && is_ssl()) {
  8726. if (detail::tls::tls_is_peer_closed(socket_.ssl, socket_.sock)) {
  8727. is_alive = false;
  8728. }
  8729. }
  8730. #endif
  8731. if (!is_alive) {
  8732. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  8733. // seems like the other side has already closed the connection Also,
  8734. // there cannot be any requests in flight from other threads since we
  8735. // locked request_mutex_, so safe to close everything immediately
  8736. const bool shutdown_gracefully = false;
  8737. shutdown_ssl(socket_, shutdown_gracefully);
  8738. shutdown_socket(socket_);
  8739. close_socket(socket_);
  8740. }
  8741. }
  8742. if (!is_alive) {
  8743. if (!ensure_socket_connection(socket_, error)) {
  8744. output_error_log(error, &req);
  8745. return false;
  8746. }
  8747. #ifdef CPPHTTPLIB_SSL_ENABLED
  8748. // TODO: refactoring
  8749. if (is_ssl()) {
  8750. auto &scli = static_cast<SSLClient &>(*this);
  8751. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8752. auto success = false;
  8753. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  8754. error)) {
  8755. if (!success) { output_error_log(error, &req); }
  8756. return success;
  8757. }
  8758. }
  8759. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8760. if (!scli.initialize_ssl(socket_, error)) {
  8761. output_error_log(error, &req);
  8762. return false;
  8763. }
  8764. }
  8765. }
  8766. #endif
  8767. }
  8768. // Mark the current socket as being in use so that it cannot be closed by
  8769. // anyone else while this request is ongoing, even though we will be
  8770. // releasing the mutex.
  8771. if (socket_requests_in_flight_ > 1) {
  8772. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  8773. }
  8774. socket_requests_in_flight_ += 1;
  8775. socket_requests_are_from_thread_ = std::this_thread::get_id();
  8776. }
  8777. for (const auto &header : default_headers_) {
  8778. if (req.headers.find(header.first) == req.headers.end()) {
  8779. req.headers.insert(header);
  8780. }
  8781. }
  8782. auto ret = false;
  8783. auto close_connection = !keep_alive_;
  8784. auto se = detail::scope_exit([&]() {
  8785. // Briefly lock mutex in order to mark that a request is no longer ongoing
  8786. std::lock_guard<std::mutex> guard(socket_mutex_);
  8787. socket_requests_in_flight_ -= 1;
  8788. if (socket_requests_in_flight_ <= 0) {
  8789. assert(socket_requests_in_flight_ == 0);
  8790. socket_requests_are_from_thread_ = std::thread::id();
  8791. }
  8792. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  8793. !ret) {
  8794. shutdown_ssl(socket_, true);
  8795. shutdown_socket(socket_);
  8796. close_socket(socket_);
  8797. }
  8798. });
  8799. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  8800. return handle_request(strm, req, res, close_connection, error);
  8801. });
  8802. if (!ret) {
  8803. if (error == Error::Success) {
  8804. error = Error::Unknown;
  8805. output_error_log(error, &req);
  8806. }
  8807. }
  8808. return ret;
  8809. }
  8810. inline Result ClientImpl::send(const Request &req) {
  8811. auto req2 = req;
  8812. return send_(std::move(req2));
  8813. }
  8814. inline Result ClientImpl::send_(Request &&req) {
  8815. auto res = detail::make_unique<Response>();
  8816. auto error = Error::Success;
  8817. auto ret = send(req, *res, error);
  8818. #ifdef CPPHTTPLIB_SSL_ENABLED
  8819. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  8820. last_ssl_error_, last_backend_error_};
  8821. #else
  8822. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  8823. #endif
  8824. }
  8825. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  8826. const std::string &ct) {
  8827. (void)for_stream;
  8828. for (const auto &header : default_headers_) {
  8829. if (!r.has_header(header.first)) { r.headers.insert(header); }
  8830. }
  8831. if (!r.has_header("Host")) {
  8832. if (address_family_ == AF_UNIX) {
  8833. r.headers.emplace("Host", "localhost");
  8834. } else {
  8835. r.headers.emplace(
  8836. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  8837. }
  8838. }
  8839. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  8840. if (!r.content_receiver) {
  8841. if (!r.has_header("Accept-Encoding")) {
  8842. std::string accept_encoding;
  8843. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8844. accept_encoding = "br";
  8845. #endif
  8846. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8847. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8848. accept_encoding += "gzip, deflate";
  8849. #endif
  8850. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8851. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8852. accept_encoding += "zstd";
  8853. #endif
  8854. r.set_header("Accept-Encoding", accept_encoding);
  8855. }
  8856. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  8857. if (!r.has_header("User-Agent")) {
  8858. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  8859. r.set_header("User-Agent", agent);
  8860. }
  8861. #endif
  8862. }
  8863. if (!r.body.empty()) {
  8864. if (!ct.empty() && !r.has_header("Content-Type")) {
  8865. r.headers.emplace("Content-Type", ct);
  8866. }
  8867. if (!r.has_header("Content-Length")) {
  8868. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  8869. }
  8870. }
  8871. }
  8872. inline ClientImpl::StreamHandle
  8873. ClientImpl::open_stream(const std::string &method, const std::string &path,
  8874. const Params &params, const Headers &headers,
  8875. const std::string &body,
  8876. const std::string &content_type) {
  8877. StreamHandle handle;
  8878. handle.response = detail::make_unique<Response>();
  8879. handle.error = Error::Success;
  8880. auto query_path = params.empty() ? path : append_query_params(path, params);
  8881. handle.connection_ = detail::make_unique<ClientConnection>();
  8882. {
  8883. std::lock_guard<std::mutex> guard(socket_mutex_);
  8884. auto is_alive = false;
  8885. if (socket_.is_open()) {
  8886. is_alive = detail::is_socket_alive(socket_.sock);
  8887. #ifdef CPPHTTPLIB_SSL_ENABLED
  8888. if (is_alive && is_ssl()) {
  8889. if (detail::tls::tls_is_peer_closed(socket_.ssl, socket_.sock)) {
  8890. is_alive = false;
  8891. }
  8892. }
  8893. #endif
  8894. if (!is_alive) {
  8895. shutdown_ssl(socket_, false);
  8896. shutdown_socket(socket_);
  8897. close_socket(socket_);
  8898. }
  8899. }
  8900. if (!is_alive) {
  8901. if (!ensure_socket_connection(socket_, handle.error)) {
  8902. handle.response.reset();
  8903. return handle;
  8904. }
  8905. #ifdef CPPHTTPLIB_SSL_ENABLED
  8906. if (is_ssl()) {
  8907. auto &scli = static_cast<SSLClient &>(*this);
  8908. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8909. if (!scli.initialize_ssl(socket_, handle.error)) {
  8910. handle.response.reset();
  8911. return handle;
  8912. }
  8913. }
  8914. }
  8915. #endif
  8916. }
  8917. transfer_socket_ownership_to_handle(handle);
  8918. }
  8919. #ifdef CPPHTTPLIB_SSL_ENABLED
  8920. if (is_ssl() && handle.connection_->session) {
  8921. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  8922. handle.connection_->sock, handle.connection_->session,
  8923. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8924. write_timeout_usec_);
  8925. } else {
  8926. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8927. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8928. write_timeout_sec_, write_timeout_usec_);
  8929. }
  8930. #else
  8931. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8932. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8933. write_timeout_sec_, write_timeout_usec_);
  8934. #endif
  8935. handle.stream_ = handle.socket_stream_.get();
  8936. Request req;
  8937. req.method = method;
  8938. req.path = query_path;
  8939. req.headers = headers;
  8940. req.body = body;
  8941. prepare_default_headers(req, true, content_type);
  8942. auto &strm = *handle.stream_;
  8943. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  8944. handle.error = Error::Write;
  8945. handle.response.reset();
  8946. return handle;
  8947. }
  8948. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  8949. handle.error)) {
  8950. handle.response.reset();
  8951. return handle;
  8952. }
  8953. if (!body.empty()) {
  8954. if (strm.write(body.data(), body.size()) < 0) {
  8955. handle.error = Error::Write;
  8956. handle.response.reset();
  8957. return handle;
  8958. }
  8959. }
  8960. if (!read_response_line(strm, req, *handle.response) ||
  8961. !detail::read_headers(strm, handle.response->headers)) {
  8962. handle.error = Error::Read;
  8963. handle.response.reset();
  8964. return handle;
  8965. }
  8966. handle.body_reader_.stream = handle.stream_;
  8967. auto content_length_str = handle.response->get_header_value("Content-Length");
  8968. if (!content_length_str.empty()) {
  8969. handle.body_reader_.content_length =
  8970. static_cast<size_t>(std::stoull(content_length_str));
  8971. }
  8972. auto transfer_encoding =
  8973. handle.response->get_header_value("Transfer-Encoding");
  8974. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  8975. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  8976. if (!content_encoding.empty()) {
  8977. handle.decompressor_ = detail::create_decompressor(content_encoding);
  8978. }
  8979. return handle;
  8980. }
  8981. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  8982. if (!is_valid() || !response) { return -1; }
  8983. if (decompressor_) { return read_with_decompression(buf, len); }
  8984. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  8985. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  8986. trailers_parsed_ = true;
  8987. if (body_reader_.chunked_decoder) {
  8988. if (!body_reader_.chunked_decoder->parse_trailers_into(
  8989. response->trailers, response->headers)) {
  8990. return n;
  8991. }
  8992. } else {
  8993. detail::ChunkedDecoder dec(*stream_);
  8994. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  8995. return n;
  8996. }
  8997. }
  8998. }
  8999. return n;
  9000. }
  9001. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  9002. size_t len) {
  9003. if (decompress_offset_ < decompress_buffer_.size()) {
  9004. auto available = decompress_buffer_.size() - decompress_offset_;
  9005. auto to_copy = (std::min)(len, available);
  9006. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  9007. decompress_offset_ += to_copy;
  9008. return static_cast<ssize_t>(to_copy);
  9009. }
  9010. decompress_buffer_.clear();
  9011. decompress_offset_ = 0;
  9012. constexpr size_t kDecompressionBufferSize = 8192;
  9013. char compressed_buf[kDecompressionBufferSize];
  9014. while (true) {
  9015. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  9016. sizeof(compressed_buf));
  9017. if (n <= 0) { return n; }
  9018. bool decompress_ok =
  9019. decompressor_->decompress(compressed_buf, static_cast<size_t>(n),
  9020. [this](const char *data, size_t data_len) {
  9021. decompress_buffer_.append(data, data_len);
  9022. return true;
  9023. });
  9024. if (!decompress_ok) {
  9025. body_reader_.last_error = Error::Read;
  9026. return -1;
  9027. }
  9028. if (!decompress_buffer_.empty()) { break; }
  9029. }
  9030. auto to_copy = (std::min)(len, decompress_buffer_.size());
  9031. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  9032. decompress_offset_ = to_copy;
  9033. return static_cast<ssize_t>(to_copy);
  9034. }
  9035. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  9036. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  9037. return;
  9038. }
  9039. trailers_parsed_ = true;
  9040. const auto bufsiz = 128;
  9041. char line_buf[bufsiz];
  9042. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  9043. if (!line_reader.getline()) { return; }
  9044. if (!detail::parse_trailers(line_reader, response->trailers,
  9045. response->headers)) {
  9046. return;
  9047. }
  9048. }
  9049. // Inline method implementations for `ChunkedDecoder`.
  9050. namespace detail {
  9051. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  9052. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  9053. size_t &out_chunk_offset,
  9054. size_t &out_chunk_total) {
  9055. if (finished) { return 0; }
  9056. if (chunk_remaining == 0) {
  9057. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9058. if (!lr.getline()) { return -1; }
  9059. char *endptr = nullptr;
  9060. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  9061. if (endptr == lr.ptr()) { return -1; }
  9062. if (chunk_len == ULONG_MAX) { return -1; }
  9063. if (chunk_len == 0) {
  9064. chunk_remaining = 0;
  9065. finished = true;
  9066. out_chunk_offset = 0;
  9067. out_chunk_total = 0;
  9068. return 0;
  9069. }
  9070. chunk_remaining = static_cast<size_t>(chunk_len);
  9071. last_chunk_total = chunk_remaining;
  9072. last_chunk_offset = 0;
  9073. }
  9074. auto to_read = (std::min)(chunk_remaining, len);
  9075. auto n = strm.read(buf, to_read);
  9076. if (n <= 0) { return -1; }
  9077. auto offset_before = last_chunk_offset;
  9078. last_chunk_offset += static_cast<size_t>(n);
  9079. chunk_remaining -= static_cast<size_t>(n);
  9080. out_chunk_offset = offset_before;
  9081. out_chunk_total = last_chunk_total;
  9082. if (chunk_remaining == 0) {
  9083. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9084. if (!lr.getline()) { return -1; }
  9085. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  9086. }
  9087. return n;
  9088. }
  9089. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  9090. const Headers &src_headers) {
  9091. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9092. if (!lr.getline()) { return false; }
  9093. return parse_trailers(lr, dest, src_headers);
  9094. }
  9095. } // namespace detail
  9096. inline void
  9097. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  9098. handle.connection_->sock = socket_.sock;
  9099. #ifdef CPPHTTPLIB_SSL_ENABLED
  9100. handle.connection_->session = socket_.ssl;
  9101. socket_.ssl = nullptr;
  9102. #endif
  9103. socket_.sock = INVALID_SOCKET;
  9104. }
  9105. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  9106. Response &res, bool close_connection,
  9107. Error &error) {
  9108. if (req.path.empty()) {
  9109. error = Error::Connection;
  9110. output_error_log(error, &req);
  9111. return false;
  9112. }
  9113. auto req_save = req;
  9114. bool ret;
  9115. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  9116. auto req2 = req;
  9117. req2.path = "http://" +
  9118. detail::make_host_and_port_string(host_, port_, false) +
  9119. req.path;
  9120. ret = process_request(strm, req2, res, close_connection, error);
  9121. req = std::move(req2);
  9122. req.path = req_save.path;
  9123. } else {
  9124. ret = process_request(strm, req, res, close_connection, error);
  9125. }
  9126. if (!ret) { return false; }
  9127. if (res.get_header_value("Connection") == "close" ||
  9128. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  9129. // TODO this requires a not-entirely-obvious chain of calls to be correct
  9130. // for this to be safe.
  9131. // This is safe to call because handle_request is only called by send_
  9132. // which locks the request mutex during the process. It would be a bug
  9133. // to call it from a different thread since it's a thread-safety issue
  9134. // to do these things to the socket if another thread is using the socket.
  9135. std::lock_guard<std::mutex> guard(socket_mutex_);
  9136. shutdown_ssl(socket_, true);
  9137. shutdown_socket(socket_);
  9138. close_socket(socket_);
  9139. }
  9140. if (300 < res.status && res.status < 400 && follow_location_) {
  9141. req = std::move(req_save);
  9142. ret = redirect(req, res, error);
  9143. }
  9144. #ifdef CPPHTTPLIB_SSL_ENABLED
  9145. if ((res.status == StatusCode::Unauthorized_401 ||
  9146. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  9147. req.authorization_count_ < 5) {
  9148. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  9149. const auto &username =
  9150. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  9151. const auto &password =
  9152. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  9153. if (!username.empty() && !password.empty()) {
  9154. std::map<std::string, std::string> auth;
  9155. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  9156. Request new_req = req;
  9157. new_req.authorization_count_ += 1;
  9158. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  9159. : "Authorization");
  9160. new_req.headers.insert(detail::make_digest_authentication_header(
  9161. req, auth, new_req.authorization_count_, detail::random_string(10),
  9162. username, password, is_proxy));
  9163. Response new_res;
  9164. ret = send(new_req, new_res, error);
  9165. if (ret) { res = std::move(new_res); }
  9166. }
  9167. }
  9168. }
  9169. #endif
  9170. return ret;
  9171. }
  9172. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  9173. if (req.redirect_count_ == 0) {
  9174. error = Error::ExceedRedirectCount;
  9175. output_error_log(error, &req);
  9176. return false;
  9177. }
  9178. auto location = res.get_header_value("location");
  9179. if (location.empty()) { return false; }
  9180. thread_local const std::regex re(
  9181. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  9182. std::smatch m;
  9183. if (!std::regex_match(location, m, re)) { return false; }
  9184. auto scheme = is_ssl() ? "https" : "http";
  9185. auto next_scheme = m[1].str();
  9186. auto next_host = m[2].str();
  9187. if (next_host.empty()) { next_host = m[3].str(); }
  9188. auto port_str = m[4].str();
  9189. auto next_path = m[5].str();
  9190. auto next_query = m[6].str();
  9191. auto next_port = port_;
  9192. if (!port_str.empty()) {
  9193. next_port = std::stoi(port_str);
  9194. } else if (!next_scheme.empty()) {
  9195. next_port = next_scheme == "https" ? 443 : 80;
  9196. }
  9197. if (next_scheme.empty()) { next_scheme = scheme; }
  9198. if (next_host.empty()) { next_host = host_; }
  9199. if (next_path.empty()) { next_path = "/"; }
  9200. auto path = decode_query_component(next_path, true) + next_query;
  9201. // Same host redirect - use current client
  9202. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  9203. return detail::redirect(*this, req, res, path, location, error);
  9204. }
  9205. // Cross-host/scheme redirect - create new client with robust setup
  9206. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  9207. path, location, error);
  9208. }
  9209. // New method for robust redirect client creation
  9210. inline bool ClientImpl::create_redirect_client(
  9211. const std::string &scheme, const std::string &host, int port, Request &req,
  9212. Response &res, const std::string &path, const std::string &location,
  9213. Error &error) {
  9214. // Determine if we need SSL
  9215. auto need_ssl = (scheme == "https");
  9216. // Clean up request headers that are host/client specific
  9217. // Remove headers that should not be carried over to new host
  9218. auto headers_to_remove =
  9219. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  9220. for (const auto &header_name : headers_to_remove) {
  9221. auto it = req.headers.find(header_name);
  9222. while (it != req.headers.end()) {
  9223. it = req.headers.erase(it);
  9224. it = req.headers.find(header_name);
  9225. }
  9226. }
  9227. // Create appropriate client type and handle redirect
  9228. if (need_ssl) {
  9229. #ifdef CPPHTTPLIB_SSL_ENABLED
  9230. // Create SSL client for HTTPS redirect
  9231. SSLClient redirect_client(host, port);
  9232. // Setup basic client configuration first
  9233. setup_redirect_client(redirect_client);
  9234. // SSL-specific configuration for proxy environments
  9235. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9236. // Critical: Disable SSL verification for proxy environments
  9237. redirect_client.enable_server_certificate_verification(false);
  9238. redirect_client.enable_server_hostname_verification(false);
  9239. } else {
  9240. // For direct SSL connections, copy SSL verification settings
  9241. redirect_client.enable_server_certificate_verification(
  9242. server_certificate_verification_);
  9243. redirect_client.enable_server_hostname_verification(
  9244. server_hostname_verification_);
  9245. }
  9246. // Transfer CA certificate to redirect client
  9247. if (!ca_cert_pem_.empty()) {
  9248. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  9249. ca_cert_pem_.size());
  9250. }
  9251. if (!ca_cert_file_path_.empty()) {
  9252. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  9253. }
  9254. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9255. // OpenSSL-specific: Handle CA certificate store
  9256. if (ca_cert_store_ && X509_STORE_up_ref(ca_cert_store_)) {
  9257. redirect_client.set_ca_cert_store(ca_cert_store_);
  9258. }
  9259. #endif
  9260. // Client certificates are set through constructor for SSLClient
  9261. // NOTE: SSLClient constructor already takes client_cert_path and
  9262. // client_key_path so we need to create it properly if client certs are
  9263. // needed
  9264. // Execute the redirect
  9265. return detail::redirect(redirect_client, req, res, path, location, error);
  9266. #else
  9267. // SSL not supported - set appropriate error
  9268. error = Error::SSLConnection;
  9269. output_error_log(error, &req);
  9270. return false;
  9271. #endif
  9272. } else {
  9273. // HTTP redirect
  9274. ClientImpl redirect_client(host, port);
  9275. // Setup client with robust configuration
  9276. setup_redirect_client(redirect_client);
  9277. // Execute the redirect
  9278. return detail::redirect(redirect_client, req, res, path, location, error);
  9279. }
  9280. }
  9281. // New method for robust client setup (based on basic_manual_redirect.cpp
  9282. // logic)
  9283. template <typename ClientType>
  9284. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  9285. // Copy basic settings first
  9286. client.set_connection_timeout(connection_timeout_sec_);
  9287. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  9288. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  9289. client.set_keep_alive(keep_alive_);
  9290. client.set_follow_location(
  9291. true); // Enable redirects to handle multi-step redirects
  9292. client.set_path_encode(path_encode_);
  9293. client.set_compress(compress_);
  9294. client.set_decompress(decompress_);
  9295. // Copy authentication settings BEFORE proxy setup
  9296. if (!basic_auth_username_.empty()) {
  9297. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  9298. }
  9299. if (!bearer_token_auth_token_.empty()) {
  9300. client.set_bearer_token_auth(bearer_token_auth_token_);
  9301. }
  9302. #ifdef CPPHTTPLIB_SSL_ENABLED
  9303. if (!digest_auth_username_.empty()) {
  9304. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  9305. }
  9306. #endif
  9307. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  9308. // before proxy auth)
  9309. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9310. // First set proxy host and port
  9311. client.set_proxy(proxy_host_, proxy_port_);
  9312. // Then set proxy authentication (order matters!)
  9313. if (!proxy_basic_auth_username_.empty()) {
  9314. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  9315. proxy_basic_auth_password_);
  9316. }
  9317. if (!proxy_bearer_token_auth_token_.empty()) {
  9318. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  9319. }
  9320. #ifdef CPPHTTPLIB_SSL_ENABLED
  9321. if (!proxy_digest_auth_username_.empty()) {
  9322. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  9323. proxy_digest_auth_password_);
  9324. }
  9325. #endif
  9326. }
  9327. // Copy network and socket settings
  9328. client.set_address_family(address_family_);
  9329. client.set_tcp_nodelay(tcp_nodelay_);
  9330. client.set_ipv6_v6only(ipv6_v6only_);
  9331. if (socket_options_) { client.set_socket_options(socket_options_); }
  9332. if (!interface_.empty()) { client.set_interface(interface_); }
  9333. // Copy logging and headers
  9334. if (logger_) { client.set_logger(logger_); }
  9335. if (error_logger_) { client.set_error_logger(error_logger_); }
  9336. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  9337. // Each new client should generate its own headers based on its target host
  9338. }
  9339. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  9340. const Request &req,
  9341. Error &error) const {
  9342. auto is_shutting_down = []() { return false; };
  9343. if (req.is_chunked_content_provider_) {
  9344. // TODO: Brotli support
  9345. std::unique_ptr<detail::compressor> compressor;
  9346. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9347. if (compress_) {
  9348. compressor = detail::make_unique<detail::gzip_compressor>();
  9349. } else
  9350. #endif
  9351. {
  9352. compressor = detail::make_unique<detail::nocompressor>();
  9353. }
  9354. return detail::write_content_chunked(strm, req.content_provider_,
  9355. is_shutting_down, *compressor, error);
  9356. } else {
  9357. return detail::write_content_with_progress(
  9358. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  9359. req.upload_progress, error);
  9360. }
  9361. }
  9362. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  9363. bool close_connection, Error &error,
  9364. bool skip_body) {
  9365. // Prepare additional headers
  9366. if (close_connection) {
  9367. if (!req.has_header("Connection")) {
  9368. req.set_header("Connection", "close");
  9369. }
  9370. }
  9371. std::string ct_for_defaults;
  9372. if (!req.has_header("Content-Type") && !req.body.empty()) {
  9373. ct_for_defaults = "text/plain";
  9374. }
  9375. prepare_default_headers(req, false, ct_for_defaults);
  9376. if (req.body.empty()) {
  9377. if (req.content_provider_) {
  9378. if (!req.is_chunked_content_provider_) {
  9379. if (!req.has_header("Content-Length")) {
  9380. auto length = std::to_string(req.content_length_);
  9381. req.set_header("Content-Length", length);
  9382. }
  9383. }
  9384. } else {
  9385. if (req.method == "POST" || req.method == "PUT" ||
  9386. req.method == "PATCH") {
  9387. req.set_header("Content-Length", "0");
  9388. }
  9389. }
  9390. }
  9391. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  9392. if (!req.has_header("Authorization")) {
  9393. req.headers.insert(make_basic_authentication_header(
  9394. basic_auth_username_, basic_auth_password_, false));
  9395. }
  9396. }
  9397. if (!proxy_basic_auth_username_.empty() &&
  9398. !proxy_basic_auth_password_.empty()) {
  9399. if (!req.has_header("Proxy-Authorization")) {
  9400. req.headers.insert(make_basic_authentication_header(
  9401. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  9402. }
  9403. }
  9404. if (!bearer_token_auth_token_.empty()) {
  9405. if (!req.has_header("Authorization")) {
  9406. req.headers.insert(make_bearer_token_authentication_header(
  9407. bearer_token_auth_token_, false));
  9408. }
  9409. }
  9410. if (!proxy_bearer_token_auth_token_.empty()) {
  9411. if (!req.has_header("Proxy-Authorization")) {
  9412. req.headers.insert(make_bearer_token_authentication_header(
  9413. proxy_bearer_token_auth_token_, true));
  9414. }
  9415. }
  9416. // Request line and headers
  9417. {
  9418. detail::BufferStream bstrm;
  9419. // Extract path and query from req.path
  9420. std::string path_part, query_part;
  9421. auto query_pos = req.path.find('?');
  9422. if (query_pos != std::string::npos) {
  9423. path_part = req.path.substr(0, query_pos);
  9424. query_part = req.path.substr(query_pos + 1);
  9425. } else {
  9426. path_part = req.path;
  9427. query_part = "";
  9428. }
  9429. // Encode path part. If the original `req.path` already contained a
  9430. // query component, preserve its raw query string (including parameter
  9431. // order) instead of reparsing and reassembling it which may reorder
  9432. // parameters due to container ordering (e.g. `Params` uses
  9433. // `std::multimap`). When there is no query in `req.path`, fall back to
  9434. // building a query from `req.params` so existing callers that pass
  9435. // `Params` continue to work.
  9436. auto path_with_query =
  9437. path_encode_ ? detail::encode_path(path_part) : path_part;
  9438. if (!query_part.empty()) {
  9439. // Normalize the query string (decode then re-encode) while preserving
  9440. // the original parameter order.
  9441. auto normalized = detail::normalize_query_string(query_part);
  9442. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  9443. // Still populate req.params for handlers/users who read them.
  9444. detail::parse_query_text(query_part, req.params);
  9445. } else {
  9446. // No query in path; parse any query_part (empty) and append params
  9447. // from `req.params` when present (preserves prior behavior for
  9448. // callers who provide Params separately).
  9449. detail::parse_query_text(query_part, req.params);
  9450. if (!req.params.empty()) {
  9451. path_with_query = append_query_params(path_with_query, req.params);
  9452. }
  9453. }
  9454. // Write request line and headers
  9455. detail::write_request_line(bstrm, req.method, path_with_query);
  9456. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  9457. error)) {
  9458. output_error_log(error, &req);
  9459. return false;
  9460. }
  9461. // Flush buffer
  9462. auto &data = bstrm.get_buffer();
  9463. if (!detail::write_data(strm, data.data(), data.size())) {
  9464. error = Error::Write;
  9465. output_error_log(error, &req);
  9466. return false;
  9467. }
  9468. }
  9469. // After sending request line and headers, wait briefly for an early server
  9470. // response (e.g. 4xx) and avoid sending a potentially large request body
  9471. // unnecessarily. This workaround is only enabled on Windows because Unix
  9472. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  9473. // buffering can accept large writes even when the peer already responded.
  9474. // Check the stream first (which covers SSL via `is_readable()`), then
  9475. // fall back to select on the socket. Only perform the wait for very large
  9476. // request bodies to avoid interfering with normal small requests and
  9477. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  9478. // response. Skip this check when using Expect: 100-continue, as the protocol
  9479. // handles early responses properly.
  9480. #if defined(_WIN32)
  9481. if (!skip_body &&
  9482. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  9483. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  9484. auto start = std::chrono::high_resolution_clock::now();
  9485. for (;;) {
  9486. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  9487. // from SSL internals. If the underlying socket is readable, assume an
  9488. // early response may be present.
  9489. auto sock = strm.socket();
  9490. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  9491. return false;
  9492. }
  9493. // Fallback to stream-level check for non-socket streams or when the
  9494. // socket isn't reporting readable. Avoid using `is_readable()` for
  9495. // SSL, since `SSL_pending()` may report buffered records that do not
  9496. // indicate a complete application-level response yet.
  9497. if (!is_ssl() && strm.is_readable()) { return false; }
  9498. auto now = std::chrono::high_resolution_clock::now();
  9499. auto elapsed =
  9500. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  9501. .count();
  9502. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  9503. break;
  9504. }
  9505. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  9506. }
  9507. }
  9508. #endif
  9509. // Body
  9510. if (skip_body) { return true; }
  9511. return write_request_body(strm, req, error);
  9512. }
  9513. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  9514. Error &error) {
  9515. if (req.body.empty()) {
  9516. return write_content_with_provider(strm, req, error);
  9517. }
  9518. if (req.upload_progress) {
  9519. auto body_size = req.body.size();
  9520. size_t written = 0;
  9521. auto data = req.body.data();
  9522. while (written < body_size) {
  9523. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  9524. if (!detail::write_data(strm, data + written, to_write)) {
  9525. error = Error::Write;
  9526. output_error_log(error, &req);
  9527. return false;
  9528. }
  9529. written += to_write;
  9530. if (!req.upload_progress(written, body_size)) {
  9531. error = Error::Canceled;
  9532. output_error_log(error, &req);
  9533. return false;
  9534. }
  9535. }
  9536. } else {
  9537. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  9538. error = Error::Write;
  9539. output_error_log(error, &req);
  9540. return false;
  9541. }
  9542. }
  9543. return true;
  9544. }
  9545. inline std::unique_ptr<Response>
  9546. ClientImpl::send_with_content_provider_and_receiver(
  9547. Request &req, const char *body, size_t content_length,
  9548. ContentProvider content_provider,
  9549. ContentProviderWithoutLength content_provider_without_length,
  9550. const std::string &content_type, ContentReceiver content_receiver,
  9551. Error &error) {
  9552. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9553. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9554. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  9555. #endif
  9556. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9557. if (compress_ && !content_provider_without_length) {
  9558. // TODO: Brotli support
  9559. detail::gzip_compressor compressor;
  9560. if (content_provider) {
  9561. auto ok = true;
  9562. size_t offset = 0;
  9563. DataSink data_sink;
  9564. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  9565. if (ok) {
  9566. auto last = offset + data_len == content_length;
  9567. auto ret = compressor.compress(
  9568. data, data_len, last,
  9569. [&](const char *compressed_data, size_t compressed_data_len) {
  9570. req.body.append(compressed_data, compressed_data_len);
  9571. return true;
  9572. });
  9573. if (ret) {
  9574. offset += data_len;
  9575. } else {
  9576. ok = false;
  9577. }
  9578. }
  9579. return ok;
  9580. };
  9581. while (ok && offset < content_length) {
  9582. if (!content_provider(offset, content_length - offset, data_sink)) {
  9583. error = Error::Canceled;
  9584. output_error_log(error, &req);
  9585. return nullptr;
  9586. }
  9587. }
  9588. } else {
  9589. if (!compressor.compress(body, content_length, true,
  9590. [&](const char *data, size_t data_len) {
  9591. req.body.append(data, data_len);
  9592. return true;
  9593. })) {
  9594. error = Error::Compression;
  9595. output_error_log(error, &req);
  9596. return nullptr;
  9597. }
  9598. }
  9599. } else
  9600. #endif
  9601. {
  9602. if (content_provider) {
  9603. req.content_length_ = content_length;
  9604. req.content_provider_ = std::move(content_provider);
  9605. req.is_chunked_content_provider_ = false;
  9606. } else if (content_provider_without_length) {
  9607. req.content_length_ = 0;
  9608. req.content_provider_ = detail::ContentProviderAdapter(
  9609. std::move(content_provider_without_length));
  9610. req.is_chunked_content_provider_ = true;
  9611. req.set_header("Transfer-Encoding", "chunked");
  9612. } else {
  9613. req.body.assign(body, content_length);
  9614. }
  9615. }
  9616. if (content_receiver) {
  9617. req.content_receiver =
  9618. [content_receiver](const char *data, size_t data_length,
  9619. size_t /*offset*/, size_t /*total_length*/) {
  9620. return content_receiver(data, data_length);
  9621. };
  9622. }
  9623. auto res = detail::make_unique<Response>();
  9624. return send(req, *res, error) ? std::move(res) : nullptr;
  9625. }
  9626. inline Result ClientImpl::send_with_content_provider_and_receiver(
  9627. const std::string &method, const std::string &path, const Headers &headers,
  9628. const char *body, size_t content_length, ContentProvider content_provider,
  9629. ContentProviderWithoutLength content_provider_without_length,
  9630. const std::string &content_type, ContentReceiver content_receiver,
  9631. UploadProgress progress) {
  9632. Request req;
  9633. req.method = method;
  9634. req.headers = headers;
  9635. req.path = path;
  9636. req.upload_progress = std::move(progress);
  9637. if (max_timeout_msec_ > 0) {
  9638. req.start_time_ = std::chrono::steady_clock::now();
  9639. }
  9640. auto error = Error::Success;
  9641. auto res = send_with_content_provider_and_receiver(
  9642. req, body, content_length, std::move(content_provider),
  9643. std::move(content_provider_without_length), content_type,
  9644. std::move(content_receiver), error);
  9645. #ifdef CPPHTTPLIB_SSL_ENABLED
  9646. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  9647. last_backend_error_};
  9648. #else
  9649. return Result{std::move(res), error, std::move(req.headers)};
  9650. #endif
  9651. }
  9652. inline void ClientImpl::output_log(const Request &req,
  9653. const Response &res) const {
  9654. if (logger_) {
  9655. std::lock_guard<std::mutex> guard(logger_mutex_);
  9656. logger_(req, res);
  9657. }
  9658. }
  9659. inline void ClientImpl::output_error_log(const Error &err,
  9660. const Request *req) const {
  9661. if (error_logger_) {
  9662. std::lock_guard<std::mutex> guard(logger_mutex_);
  9663. error_logger_(err, req);
  9664. }
  9665. }
  9666. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  9667. Response &res, bool close_connection,
  9668. Error &error) {
  9669. // Auto-add Expect: 100-continue for large bodies
  9670. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  9671. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  9672. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  9673. req.set_header("Expect", "100-continue");
  9674. }
  9675. }
  9676. // Check for Expect: 100-continue
  9677. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  9678. // Send request (skip body if using Expect: 100-continue)
  9679. auto write_request_success =
  9680. write_request(strm, req, close_connection, error, expect_100_continue);
  9681. #ifdef CPPHTTPLIB_SSL_ENABLED
  9682. if (is_ssl()) {
  9683. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  9684. if (!is_proxy_enabled) {
  9685. if (detail::tls::tls_is_peer_closed(socket_.ssl, socket_.sock)) {
  9686. error = Error::SSLPeerCouldBeClosed_;
  9687. output_error_log(error, &req);
  9688. return false;
  9689. }
  9690. }
  9691. }
  9692. #endif
  9693. // Handle Expect: 100-continue with timeout
  9694. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  9695. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  9696. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  9697. auto ret = detail::select_read(strm.socket(), sec, usec);
  9698. if (ret <= 0) {
  9699. // Timeout or error: send body anyway (server didn't respond in time)
  9700. if (!write_request_body(strm, req, error)) { return false; }
  9701. expect_100_continue = false; // Switch to normal response handling
  9702. }
  9703. }
  9704. // Receive response and headers
  9705. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  9706. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  9707. !detail::read_headers(strm, res.headers)) {
  9708. if (write_request_success) { error = Error::Read; }
  9709. output_error_log(error, &req);
  9710. return false;
  9711. }
  9712. if (!write_request_success) { return false; }
  9713. // Handle Expect: 100-continue response
  9714. if (expect_100_continue) {
  9715. if (res.status == StatusCode::Continue_100) {
  9716. // Server accepted, send the body
  9717. if (!write_request_body(strm, req, error)) { return false; }
  9718. // Read the actual response
  9719. res.headers.clear();
  9720. res.body.clear();
  9721. if (!read_response_line(strm, req, res) ||
  9722. !detail::read_headers(strm, res.headers)) {
  9723. error = Error::Read;
  9724. output_error_log(error, &req);
  9725. return false;
  9726. }
  9727. }
  9728. // If not 100 Continue, server returned an error; proceed with that response
  9729. }
  9730. // Body
  9731. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  9732. req.method != "CONNECT") {
  9733. auto redirect = 300 < res.status && res.status < 400 &&
  9734. res.status != StatusCode::NotModified_304 &&
  9735. follow_location_;
  9736. if (req.response_handler && !redirect) {
  9737. if (!req.response_handler(res)) {
  9738. error = Error::Canceled;
  9739. output_error_log(error, &req);
  9740. return false;
  9741. }
  9742. }
  9743. auto out =
  9744. req.content_receiver
  9745. ? static_cast<ContentReceiverWithProgress>(
  9746. [&](const char *buf, size_t n, size_t off, size_t len) {
  9747. if (redirect) { return true; }
  9748. auto ret = req.content_receiver(buf, n, off, len);
  9749. if (!ret) {
  9750. error = Error::Canceled;
  9751. output_error_log(error, &req);
  9752. }
  9753. return ret;
  9754. })
  9755. : static_cast<ContentReceiverWithProgress>(
  9756. [&](const char *buf, size_t n, size_t /*off*/,
  9757. size_t /*len*/) {
  9758. assert(res.body.size() + n <= res.body.max_size());
  9759. res.body.append(buf, n);
  9760. return true;
  9761. });
  9762. auto progress = [&](size_t current, size_t total) {
  9763. if (!req.download_progress || redirect) { return true; }
  9764. auto ret = req.download_progress(current, total);
  9765. if (!ret) {
  9766. error = Error::Canceled;
  9767. output_error_log(error, &req);
  9768. }
  9769. return ret;
  9770. };
  9771. if (res.has_header("Content-Length")) {
  9772. if (!req.content_receiver) {
  9773. auto len = res.get_header_value_u64("Content-Length");
  9774. if (len > res.body.max_size()) {
  9775. error = Error::Read;
  9776. output_error_log(error, &req);
  9777. return false;
  9778. }
  9779. res.body.reserve(static_cast<size_t>(len));
  9780. }
  9781. }
  9782. if (res.status != StatusCode::NotModified_304) {
  9783. int dummy_status;
  9784. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  9785. dummy_status, std::move(progress),
  9786. std::move(out), decompress_)) {
  9787. if (error != Error::Canceled) { error = Error::Read; }
  9788. output_error_log(error, &req);
  9789. return false;
  9790. }
  9791. }
  9792. }
  9793. // Log
  9794. output_log(req, res);
  9795. return true;
  9796. }
  9797. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  9798. const std::string &boundary, const UploadFormDataItems &items,
  9799. const FormDataProviderItems &provider_items) const {
  9800. size_t cur_item = 0;
  9801. size_t cur_start = 0;
  9802. // cur_item and cur_start are copied to within the std::function and
  9803. // maintain state between successive calls
  9804. return [&, cur_item, cur_start](size_t offset,
  9805. DataSink &sink) mutable -> bool {
  9806. if (!offset && !items.empty()) {
  9807. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  9808. return true;
  9809. } else if (cur_item < provider_items.size()) {
  9810. if (!cur_start) {
  9811. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  9812. provider_items[cur_item], boundary);
  9813. offset += begin.size();
  9814. cur_start = offset;
  9815. sink.os << begin;
  9816. }
  9817. DataSink cur_sink;
  9818. auto has_data = true;
  9819. cur_sink.write = sink.write;
  9820. cur_sink.done = [&]() { has_data = false; };
  9821. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  9822. return false;
  9823. }
  9824. if (!has_data) {
  9825. sink.os << detail::serialize_multipart_formdata_item_end();
  9826. cur_item++;
  9827. cur_start = 0;
  9828. }
  9829. return true;
  9830. } else {
  9831. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  9832. sink.done();
  9833. return true;
  9834. }
  9835. };
  9836. }
  9837. inline bool ClientImpl::process_socket(
  9838. const Socket &socket,
  9839. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9840. std::function<bool(Stream &strm)> callback) {
  9841. return detail::process_client_socket(
  9842. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9843. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  9844. }
  9845. inline bool ClientImpl::is_ssl() const { return false; }
  9846. inline Result ClientImpl::Get(const std::string &path,
  9847. DownloadProgress progress) {
  9848. return Get(path, Headers(), std::move(progress));
  9849. }
  9850. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9851. const Headers &headers,
  9852. DownloadProgress progress) {
  9853. if (params.empty()) { return Get(path, headers); }
  9854. std::string path_with_query = append_query_params(path, params);
  9855. return Get(path_with_query, headers, std::move(progress));
  9856. }
  9857. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9858. DownloadProgress progress) {
  9859. Request req;
  9860. req.method = "GET";
  9861. req.path = path;
  9862. req.headers = headers;
  9863. req.download_progress = std::move(progress);
  9864. if (max_timeout_msec_ > 0) {
  9865. req.start_time_ = std::chrono::steady_clock::now();
  9866. }
  9867. return send_(std::move(req));
  9868. }
  9869. inline Result ClientImpl::Get(const std::string &path,
  9870. ContentReceiver content_receiver,
  9871. DownloadProgress progress) {
  9872. return Get(path, Headers(), nullptr, std::move(content_receiver),
  9873. std::move(progress));
  9874. }
  9875. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9876. ContentReceiver content_receiver,
  9877. DownloadProgress progress) {
  9878. return Get(path, headers, nullptr, std::move(content_receiver),
  9879. std::move(progress));
  9880. }
  9881. inline Result ClientImpl::Get(const std::string &path,
  9882. ResponseHandler response_handler,
  9883. ContentReceiver content_receiver,
  9884. DownloadProgress progress) {
  9885. return Get(path, Headers(), std::move(response_handler),
  9886. std::move(content_receiver), std::move(progress));
  9887. }
  9888. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9889. ResponseHandler response_handler,
  9890. ContentReceiver content_receiver,
  9891. DownloadProgress progress) {
  9892. Request req;
  9893. req.method = "GET";
  9894. req.path = path;
  9895. req.headers = headers;
  9896. req.response_handler = std::move(response_handler);
  9897. req.content_receiver =
  9898. [content_receiver](const char *data, size_t data_length,
  9899. size_t /*offset*/, size_t /*total_length*/) {
  9900. return content_receiver(data, data_length);
  9901. };
  9902. req.download_progress = std::move(progress);
  9903. if (max_timeout_msec_ > 0) {
  9904. req.start_time_ = std::chrono::steady_clock::now();
  9905. }
  9906. return send_(std::move(req));
  9907. }
  9908. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9909. const Headers &headers,
  9910. ContentReceiver content_receiver,
  9911. DownloadProgress progress) {
  9912. return Get(path, params, headers, nullptr, std::move(content_receiver),
  9913. std::move(progress));
  9914. }
  9915. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9916. const Headers &headers,
  9917. ResponseHandler response_handler,
  9918. ContentReceiver content_receiver,
  9919. DownloadProgress progress) {
  9920. if (params.empty()) {
  9921. return Get(path, headers, std::move(response_handler),
  9922. std::move(content_receiver), std::move(progress));
  9923. }
  9924. std::string path_with_query = append_query_params(path, params);
  9925. return Get(path_with_query, headers, std::move(response_handler),
  9926. std::move(content_receiver), std::move(progress));
  9927. }
  9928. inline Result ClientImpl::Head(const std::string &path) {
  9929. return Head(path, Headers());
  9930. }
  9931. inline Result ClientImpl::Head(const std::string &path,
  9932. const Headers &headers) {
  9933. Request req;
  9934. req.method = "HEAD";
  9935. req.headers = headers;
  9936. req.path = path;
  9937. if (max_timeout_msec_ > 0) {
  9938. req.start_time_ = std::chrono::steady_clock::now();
  9939. }
  9940. return send_(std::move(req));
  9941. }
  9942. inline Result ClientImpl::Post(const std::string &path) {
  9943. return Post(path, std::string(), std::string());
  9944. }
  9945. inline Result ClientImpl::Post(const std::string &path,
  9946. const Headers &headers) {
  9947. return Post(path, headers, nullptr, 0, std::string());
  9948. }
  9949. inline Result ClientImpl::Post(const std::string &path, const char *body,
  9950. size_t content_length,
  9951. const std::string &content_type,
  9952. UploadProgress progress) {
  9953. return Post(path, Headers(), body, content_length, content_type, progress);
  9954. }
  9955. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  9956. const std::string &content_type,
  9957. UploadProgress progress) {
  9958. return Post(path, Headers(), body, content_type, progress);
  9959. }
  9960. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  9961. return Post(path, Headers(), params);
  9962. }
  9963. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9964. ContentProvider content_provider,
  9965. const std::string &content_type,
  9966. UploadProgress progress) {
  9967. return Post(path, Headers(), content_length, std::move(content_provider),
  9968. content_type, progress);
  9969. }
  9970. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9971. ContentProvider content_provider,
  9972. const std::string &content_type,
  9973. ContentReceiver content_receiver,
  9974. UploadProgress progress) {
  9975. return Post(path, Headers(), content_length, std::move(content_provider),
  9976. content_type, std::move(content_receiver), progress);
  9977. }
  9978. inline Result ClientImpl::Post(const std::string &path,
  9979. ContentProviderWithoutLength content_provider,
  9980. const std::string &content_type,
  9981. UploadProgress progress) {
  9982. return Post(path, Headers(), std::move(content_provider), content_type,
  9983. progress);
  9984. }
  9985. inline Result ClientImpl::Post(const std::string &path,
  9986. ContentProviderWithoutLength content_provider,
  9987. const std::string &content_type,
  9988. ContentReceiver content_receiver,
  9989. UploadProgress progress) {
  9990. return Post(path, Headers(), std::move(content_provider), content_type,
  9991. std::move(content_receiver), progress);
  9992. }
  9993. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9994. const Params &params) {
  9995. auto query = detail::params_to_query_str(params);
  9996. return Post(path, headers, query, "application/x-www-form-urlencoded");
  9997. }
  9998. inline Result ClientImpl::Post(const std::string &path,
  9999. const UploadFormDataItems &items,
  10000. UploadProgress progress) {
  10001. return Post(path, Headers(), items, progress);
  10002. }
  10003. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10004. const UploadFormDataItems &items,
  10005. UploadProgress progress) {
  10006. const auto &boundary = detail::make_multipart_data_boundary();
  10007. const auto &content_type =
  10008. detail::serialize_multipart_formdata_get_content_type(boundary);
  10009. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10010. return Post(path, headers, body, content_type, progress);
  10011. }
  10012. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10013. const UploadFormDataItems &items,
  10014. const std::string &boundary,
  10015. UploadProgress progress) {
  10016. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10017. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10018. }
  10019. const auto &content_type =
  10020. detail::serialize_multipart_formdata_get_content_type(boundary);
  10021. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10022. return Post(path, headers, body, content_type, progress);
  10023. }
  10024. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10025. const char *body, size_t content_length,
  10026. const std::string &content_type,
  10027. UploadProgress progress) {
  10028. return send_with_content_provider_and_receiver(
  10029. "POST", path, headers, body, content_length, nullptr, nullptr,
  10030. content_type, nullptr, progress);
  10031. }
  10032. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10033. const std::string &body,
  10034. const std::string &content_type,
  10035. UploadProgress progress) {
  10036. return send_with_content_provider_and_receiver(
  10037. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  10038. content_type, nullptr, progress);
  10039. }
  10040. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10041. size_t content_length,
  10042. ContentProvider content_provider,
  10043. const std::string &content_type,
  10044. UploadProgress progress) {
  10045. return send_with_content_provider_and_receiver(
  10046. "POST", path, headers, nullptr, content_length,
  10047. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10048. }
  10049. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10050. size_t content_length,
  10051. ContentProvider content_provider,
  10052. const std::string &content_type,
  10053. ContentReceiver content_receiver,
  10054. DownloadProgress progress) {
  10055. return send_with_content_provider_and_receiver(
  10056. "POST", path, headers, nullptr, content_length,
  10057. std::move(content_provider), nullptr, content_type,
  10058. std::move(content_receiver), std::move(progress));
  10059. }
  10060. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10061. ContentProviderWithoutLength content_provider,
  10062. const std::string &content_type,
  10063. UploadProgress progress) {
  10064. return send_with_content_provider_and_receiver(
  10065. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10066. content_type, nullptr, progress);
  10067. }
  10068. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10069. ContentProviderWithoutLength content_provider,
  10070. const std::string &content_type,
  10071. ContentReceiver content_receiver,
  10072. DownloadProgress progress) {
  10073. return send_with_content_provider_and_receiver(
  10074. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10075. content_type, std::move(content_receiver), std::move(progress));
  10076. }
  10077. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10078. const UploadFormDataItems &items,
  10079. const FormDataProviderItems &provider_items,
  10080. UploadProgress progress) {
  10081. const auto &boundary = detail::make_multipart_data_boundary();
  10082. const auto &content_type =
  10083. detail::serialize_multipart_formdata_get_content_type(boundary);
  10084. return send_with_content_provider_and_receiver(
  10085. "POST", path, headers, nullptr, 0, nullptr,
  10086. get_multipart_content_provider(boundary, items, provider_items),
  10087. content_type, nullptr, progress);
  10088. }
  10089. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10090. const std::string &body,
  10091. const std::string &content_type,
  10092. ContentReceiver content_receiver,
  10093. DownloadProgress progress) {
  10094. Request req;
  10095. req.method = "POST";
  10096. req.path = path;
  10097. req.headers = headers;
  10098. req.body = body;
  10099. req.content_receiver =
  10100. [content_receiver](const char *data, size_t data_length,
  10101. size_t /*offset*/, size_t /*total_length*/) {
  10102. return content_receiver(data, data_length);
  10103. };
  10104. req.download_progress = std::move(progress);
  10105. if (max_timeout_msec_ > 0) {
  10106. req.start_time_ = std::chrono::steady_clock::now();
  10107. }
  10108. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10109. return send_(std::move(req));
  10110. }
  10111. inline Result ClientImpl::Put(const std::string &path) {
  10112. return Put(path, std::string(), std::string());
  10113. }
  10114. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  10115. return Put(path, headers, nullptr, 0, std::string());
  10116. }
  10117. inline Result ClientImpl::Put(const std::string &path, const char *body,
  10118. size_t content_length,
  10119. const std::string &content_type,
  10120. UploadProgress progress) {
  10121. return Put(path, Headers(), body, content_length, content_type, progress);
  10122. }
  10123. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  10124. const std::string &content_type,
  10125. UploadProgress progress) {
  10126. return Put(path, Headers(), body, content_type, progress);
  10127. }
  10128. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  10129. return Put(path, Headers(), params);
  10130. }
  10131. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10132. ContentProvider content_provider,
  10133. const std::string &content_type,
  10134. UploadProgress progress) {
  10135. return Put(path, Headers(), content_length, std::move(content_provider),
  10136. content_type, progress);
  10137. }
  10138. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10139. ContentProvider content_provider,
  10140. const std::string &content_type,
  10141. ContentReceiver content_receiver,
  10142. UploadProgress progress) {
  10143. return Put(path, Headers(), content_length, std::move(content_provider),
  10144. content_type, std::move(content_receiver), progress);
  10145. }
  10146. inline Result ClientImpl::Put(const std::string &path,
  10147. ContentProviderWithoutLength content_provider,
  10148. const std::string &content_type,
  10149. UploadProgress progress) {
  10150. return Put(path, Headers(), std::move(content_provider), content_type,
  10151. progress);
  10152. }
  10153. inline Result ClientImpl::Put(const std::string &path,
  10154. ContentProviderWithoutLength content_provider,
  10155. const std::string &content_type,
  10156. ContentReceiver content_receiver,
  10157. UploadProgress progress) {
  10158. return Put(path, Headers(), std::move(content_provider), content_type,
  10159. std::move(content_receiver), progress);
  10160. }
  10161. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10162. const Params &params) {
  10163. auto query = detail::params_to_query_str(params);
  10164. return Put(path, headers, query, "application/x-www-form-urlencoded");
  10165. }
  10166. inline Result ClientImpl::Put(const std::string &path,
  10167. const UploadFormDataItems &items,
  10168. UploadProgress progress) {
  10169. return Put(path, Headers(), items, progress);
  10170. }
  10171. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10172. const UploadFormDataItems &items,
  10173. UploadProgress progress) {
  10174. const auto &boundary = detail::make_multipart_data_boundary();
  10175. const auto &content_type =
  10176. detail::serialize_multipart_formdata_get_content_type(boundary);
  10177. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10178. return Put(path, headers, body, content_type, progress);
  10179. }
  10180. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10181. const UploadFormDataItems &items,
  10182. const std::string &boundary,
  10183. UploadProgress progress) {
  10184. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10185. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10186. }
  10187. const auto &content_type =
  10188. detail::serialize_multipart_formdata_get_content_type(boundary);
  10189. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10190. return Put(path, headers, body, content_type, progress);
  10191. }
  10192. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10193. const char *body, size_t content_length,
  10194. const std::string &content_type,
  10195. UploadProgress progress) {
  10196. return send_with_content_provider_and_receiver(
  10197. "PUT", path, headers, body, content_length, nullptr, nullptr,
  10198. content_type, nullptr, progress);
  10199. }
  10200. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10201. const std::string &body,
  10202. const std::string &content_type,
  10203. UploadProgress progress) {
  10204. return send_with_content_provider_and_receiver(
  10205. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  10206. content_type, nullptr, progress);
  10207. }
  10208. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10209. size_t content_length,
  10210. ContentProvider content_provider,
  10211. const std::string &content_type,
  10212. UploadProgress progress) {
  10213. return send_with_content_provider_and_receiver(
  10214. "PUT", path, headers, nullptr, content_length,
  10215. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10216. }
  10217. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10218. size_t content_length,
  10219. ContentProvider content_provider,
  10220. const std::string &content_type,
  10221. ContentReceiver content_receiver,
  10222. UploadProgress progress) {
  10223. return send_with_content_provider_and_receiver(
  10224. "PUT", path, headers, nullptr, content_length,
  10225. std::move(content_provider), nullptr, content_type,
  10226. std::move(content_receiver), progress);
  10227. }
  10228. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10229. ContentProviderWithoutLength content_provider,
  10230. const std::string &content_type,
  10231. UploadProgress progress) {
  10232. return send_with_content_provider_and_receiver(
  10233. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10234. content_type, nullptr, progress);
  10235. }
  10236. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10237. ContentProviderWithoutLength content_provider,
  10238. const std::string &content_type,
  10239. ContentReceiver content_receiver,
  10240. UploadProgress progress) {
  10241. return send_with_content_provider_and_receiver(
  10242. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10243. content_type, std::move(content_receiver), progress);
  10244. }
  10245. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10246. const UploadFormDataItems &items,
  10247. const FormDataProviderItems &provider_items,
  10248. UploadProgress progress) {
  10249. const auto &boundary = detail::make_multipart_data_boundary();
  10250. const auto &content_type =
  10251. detail::serialize_multipart_formdata_get_content_type(boundary);
  10252. return send_with_content_provider_and_receiver(
  10253. "PUT", path, headers, nullptr, 0, nullptr,
  10254. get_multipart_content_provider(boundary, items, provider_items),
  10255. content_type, nullptr, progress);
  10256. }
  10257. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10258. const std::string &body,
  10259. const std::string &content_type,
  10260. ContentReceiver content_receiver,
  10261. DownloadProgress progress) {
  10262. Request req;
  10263. req.method = "PUT";
  10264. req.path = path;
  10265. req.headers = headers;
  10266. req.body = body;
  10267. req.content_receiver =
  10268. [content_receiver](const char *data, size_t data_length,
  10269. size_t /*offset*/, size_t /*total_length*/) {
  10270. return content_receiver(data, data_length);
  10271. };
  10272. req.download_progress = std::move(progress);
  10273. if (max_timeout_msec_ > 0) {
  10274. req.start_time_ = std::chrono::steady_clock::now();
  10275. }
  10276. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10277. return send_(std::move(req));
  10278. }
  10279. inline Result ClientImpl::Patch(const std::string &path) {
  10280. return Patch(path, std::string(), std::string());
  10281. }
  10282. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10283. UploadProgress progress) {
  10284. return Patch(path, headers, nullptr, 0, std::string(), progress);
  10285. }
  10286. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  10287. size_t content_length,
  10288. const std::string &content_type,
  10289. UploadProgress progress) {
  10290. return Patch(path, Headers(), body, content_length, content_type, progress);
  10291. }
  10292. inline Result ClientImpl::Patch(const std::string &path,
  10293. const std::string &body,
  10294. const std::string &content_type,
  10295. UploadProgress progress) {
  10296. return Patch(path, Headers(), body, content_type, progress);
  10297. }
  10298. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  10299. return Patch(path, Headers(), params);
  10300. }
  10301. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10302. ContentProvider content_provider,
  10303. const std::string &content_type,
  10304. UploadProgress progress) {
  10305. return Patch(path, Headers(), content_length, std::move(content_provider),
  10306. content_type, progress);
  10307. }
  10308. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10309. ContentProvider content_provider,
  10310. const std::string &content_type,
  10311. ContentReceiver content_receiver,
  10312. UploadProgress progress) {
  10313. return Patch(path, Headers(), content_length, std::move(content_provider),
  10314. content_type, std::move(content_receiver), progress);
  10315. }
  10316. inline Result ClientImpl::Patch(const std::string &path,
  10317. ContentProviderWithoutLength content_provider,
  10318. const std::string &content_type,
  10319. UploadProgress progress) {
  10320. return Patch(path, Headers(), std::move(content_provider), content_type,
  10321. progress);
  10322. }
  10323. inline Result ClientImpl::Patch(const std::string &path,
  10324. ContentProviderWithoutLength content_provider,
  10325. const std::string &content_type,
  10326. ContentReceiver content_receiver,
  10327. UploadProgress progress) {
  10328. return Patch(path, Headers(), std::move(content_provider), content_type,
  10329. std::move(content_receiver), progress);
  10330. }
  10331. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10332. const Params &params) {
  10333. auto query = detail::params_to_query_str(params);
  10334. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  10335. }
  10336. inline Result ClientImpl::Patch(const std::string &path,
  10337. const UploadFormDataItems &items,
  10338. UploadProgress progress) {
  10339. return Patch(path, Headers(), items, progress);
  10340. }
  10341. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10342. const UploadFormDataItems &items,
  10343. UploadProgress progress) {
  10344. const auto &boundary = detail::make_multipart_data_boundary();
  10345. const auto &content_type =
  10346. detail::serialize_multipart_formdata_get_content_type(boundary);
  10347. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10348. return Patch(path, headers, body, content_type, progress);
  10349. }
  10350. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10351. const UploadFormDataItems &items,
  10352. const std::string &boundary,
  10353. UploadProgress progress) {
  10354. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10355. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10356. }
  10357. const auto &content_type =
  10358. detail::serialize_multipart_formdata_get_content_type(boundary);
  10359. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10360. return Patch(path, headers, body, content_type, progress);
  10361. }
  10362. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10363. const char *body, size_t content_length,
  10364. const std::string &content_type,
  10365. UploadProgress progress) {
  10366. return send_with_content_provider_and_receiver(
  10367. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  10368. content_type, nullptr, progress);
  10369. }
  10370. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10371. const std::string &body,
  10372. const std::string &content_type,
  10373. UploadProgress progress) {
  10374. return send_with_content_provider_and_receiver(
  10375. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  10376. content_type, nullptr, progress);
  10377. }
  10378. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10379. size_t content_length,
  10380. ContentProvider content_provider,
  10381. const std::string &content_type,
  10382. UploadProgress progress) {
  10383. return send_with_content_provider_and_receiver(
  10384. "PATCH", path, headers, nullptr, content_length,
  10385. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10386. }
  10387. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10388. size_t content_length,
  10389. ContentProvider content_provider,
  10390. const std::string &content_type,
  10391. ContentReceiver content_receiver,
  10392. UploadProgress progress) {
  10393. return send_with_content_provider_and_receiver(
  10394. "PATCH", path, headers, nullptr, content_length,
  10395. std::move(content_provider), nullptr, content_type,
  10396. std::move(content_receiver), progress);
  10397. }
  10398. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10399. ContentProviderWithoutLength content_provider,
  10400. const std::string &content_type,
  10401. UploadProgress progress) {
  10402. return send_with_content_provider_and_receiver(
  10403. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10404. content_type, nullptr, progress);
  10405. }
  10406. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10407. ContentProviderWithoutLength content_provider,
  10408. const std::string &content_type,
  10409. ContentReceiver content_receiver,
  10410. UploadProgress progress) {
  10411. return send_with_content_provider_and_receiver(
  10412. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10413. content_type, std::move(content_receiver), progress);
  10414. }
  10415. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10416. const UploadFormDataItems &items,
  10417. const FormDataProviderItems &provider_items,
  10418. UploadProgress progress) {
  10419. const auto &boundary = detail::make_multipart_data_boundary();
  10420. const auto &content_type =
  10421. detail::serialize_multipart_formdata_get_content_type(boundary);
  10422. return send_with_content_provider_and_receiver(
  10423. "PATCH", path, headers, nullptr, 0, nullptr,
  10424. get_multipart_content_provider(boundary, items, provider_items),
  10425. content_type, nullptr, progress);
  10426. }
  10427. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10428. const std::string &body,
  10429. const std::string &content_type,
  10430. ContentReceiver content_receiver,
  10431. DownloadProgress progress) {
  10432. Request req;
  10433. req.method = "PATCH";
  10434. req.path = path;
  10435. req.headers = headers;
  10436. req.body = body;
  10437. req.content_receiver =
  10438. [content_receiver](const char *data, size_t data_length,
  10439. size_t /*offset*/, size_t /*total_length*/) {
  10440. return content_receiver(data, data_length);
  10441. };
  10442. req.download_progress = std::move(progress);
  10443. if (max_timeout_msec_ > 0) {
  10444. req.start_time_ = std::chrono::steady_clock::now();
  10445. }
  10446. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10447. return send_(std::move(req));
  10448. }
  10449. inline Result ClientImpl::Delete(const std::string &path,
  10450. DownloadProgress progress) {
  10451. return Delete(path, Headers(), std::string(), std::string(), progress);
  10452. }
  10453. inline Result ClientImpl::Delete(const std::string &path,
  10454. const Headers &headers,
  10455. DownloadProgress progress) {
  10456. return Delete(path, headers, std::string(), std::string(), progress);
  10457. }
  10458. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  10459. size_t content_length,
  10460. const std::string &content_type,
  10461. DownloadProgress progress) {
  10462. return Delete(path, Headers(), body, content_length, content_type, progress);
  10463. }
  10464. inline Result ClientImpl::Delete(const std::string &path,
  10465. const std::string &body,
  10466. const std::string &content_type,
  10467. DownloadProgress progress) {
  10468. return Delete(path, Headers(), body.data(), body.size(), content_type,
  10469. progress);
  10470. }
  10471. inline Result ClientImpl::Delete(const std::string &path,
  10472. const Headers &headers,
  10473. const std::string &body,
  10474. const std::string &content_type,
  10475. DownloadProgress progress) {
  10476. return Delete(path, headers, body.data(), body.size(), content_type,
  10477. progress);
  10478. }
  10479. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  10480. DownloadProgress progress) {
  10481. return Delete(path, Headers(), params, progress);
  10482. }
  10483. inline Result ClientImpl::Delete(const std::string &path,
  10484. const Headers &headers, const Params &params,
  10485. DownloadProgress progress) {
  10486. auto query = detail::params_to_query_str(params);
  10487. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  10488. progress);
  10489. }
  10490. inline Result ClientImpl::Delete(const std::string &path,
  10491. const Headers &headers, const char *body,
  10492. size_t content_length,
  10493. const std::string &content_type,
  10494. DownloadProgress progress) {
  10495. Request req;
  10496. req.method = "DELETE";
  10497. req.headers = headers;
  10498. req.path = path;
  10499. req.download_progress = std::move(progress);
  10500. if (max_timeout_msec_ > 0) {
  10501. req.start_time_ = std::chrono::steady_clock::now();
  10502. }
  10503. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10504. req.body.assign(body, content_length);
  10505. return send_(std::move(req));
  10506. }
  10507. inline Result ClientImpl::Options(const std::string &path) {
  10508. return Options(path, Headers());
  10509. }
  10510. inline Result ClientImpl::Options(const std::string &path,
  10511. const Headers &headers) {
  10512. Request req;
  10513. req.method = "OPTIONS";
  10514. req.headers = headers;
  10515. req.path = path;
  10516. if (max_timeout_msec_ > 0) {
  10517. req.start_time_ = std::chrono::steady_clock::now();
  10518. }
  10519. return send_(std::move(req));
  10520. }
  10521. inline void ClientImpl::stop() {
  10522. std::lock_guard<std::mutex> guard(socket_mutex_);
  10523. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  10524. // do is to shutdown_socket, so that threads using this socket suddenly
  10525. // discover they can't read/write any more and error out. Everything else
  10526. // (closing the socket, shutting ssl down) is unsafe because these actions
  10527. // are not thread-safe.
  10528. if (socket_requests_in_flight_ > 0) {
  10529. shutdown_socket(socket_);
  10530. // Aside from that, we set a flag for the socket to be closed when we're
  10531. // done.
  10532. socket_should_be_closed_when_request_is_done_ = true;
  10533. return;
  10534. }
  10535. // Otherwise, still holding the mutex, we can shut everything down ourselves
  10536. shutdown_ssl(socket_, true);
  10537. shutdown_socket(socket_);
  10538. close_socket(socket_);
  10539. }
  10540. inline std::string ClientImpl::host() const { return host_; }
  10541. inline int ClientImpl::port() const { return port_; }
  10542. inline size_t ClientImpl::is_socket_open() const {
  10543. std::lock_guard<std::mutex> guard(socket_mutex_);
  10544. return socket_.is_open();
  10545. }
  10546. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  10547. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  10548. connection_timeout_sec_ = sec;
  10549. connection_timeout_usec_ = usec;
  10550. }
  10551. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  10552. read_timeout_sec_ = sec;
  10553. read_timeout_usec_ = usec;
  10554. }
  10555. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  10556. write_timeout_sec_ = sec;
  10557. write_timeout_usec_ = usec;
  10558. }
  10559. inline void ClientImpl::set_max_timeout(time_t msec) {
  10560. max_timeout_msec_ = msec;
  10561. }
  10562. inline void ClientImpl::set_basic_auth(const std::string &username,
  10563. const std::string &password) {
  10564. basic_auth_username_ = username;
  10565. basic_auth_password_ = password;
  10566. }
  10567. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  10568. bearer_token_auth_token_ = token;
  10569. }
  10570. #ifdef CPPHTTPLIB_SSL_ENABLED
  10571. inline void ClientImpl::set_digest_auth(const std::string &username,
  10572. const std::string &password) {
  10573. digest_auth_username_ = username;
  10574. digest_auth_password_ = password;
  10575. }
  10576. #endif
  10577. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  10578. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  10579. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  10580. inline void
  10581. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  10582. addr_map_ = std::move(addr_map);
  10583. }
  10584. inline void ClientImpl::set_default_headers(Headers headers) {
  10585. default_headers_ = std::move(headers);
  10586. }
  10587. inline void ClientImpl::set_header_writer(
  10588. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  10589. header_writer_ = writer;
  10590. }
  10591. inline void ClientImpl::set_address_family(int family) {
  10592. address_family_ = family;
  10593. }
  10594. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  10595. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  10596. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  10597. socket_options_ = std::move(socket_options);
  10598. }
  10599. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  10600. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  10601. inline void ClientImpl::set_interface(const std::string &intf) {
  10602. interface_ = intf;
  10603. }
  10604. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  10605. proxy_host_ = host;
  10606. proxy_port_ = port;
  10607. }
  10608. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  10609. const std::string &password) {
  10610. proxy_basic_auth_username_ = username;
  10611. proxy_basic_auth_password_ = password;
  10612. }
  10613. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  10614. proxy_bearer_token_auth_token_ = token;
  10615. }
  10616. #ifdef CPPHTTPLIB_SSL_ENABLED
  10617. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  10618. const std::string &ca_cert_dir_path) {
  10619. ca_cert_file_path_ = ca_cert_file_path;
  10620. ca_cert_dir_path_ = ca_cert_dir_path;
  10621. }
  10622. #endif
  10623. #ifdef CPPHTTPLIB_SSL_ENABLED
  10624. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  10625. const std::string &password) {
  10626. proxy_digest_auth_username_ = username;
  10627. proxy_digest_auth_password_ = password;
  10628. }
  10629. #endif
  10630. // ClientImpl::set_ca_cert_store is defined after TLS namespace (uses helpers)
  10631. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10632. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  10633. std::size_t size) const {
  10634. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  10635. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  10636. if (!mem) { return nullptr; }
  10637. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  10638. if (!inf) { return nullptr; }
  10639. auto cts = X509_STORE_new();
  10640. if (cts) {
  10641. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  10642. auto itmp = sk_X509_INFO_value(inf, i);
  10643. if (!itmp) { continue; }
  10644. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  10645. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  10646. }
  10647. }
  10648. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  10649. return cts;
  10650. }
  10651. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10652. #ifdef CPPHTTPLIB_SSL_ENABLED
  10653. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  10654. server_certificate_verification_ = enabled;
  10655. }
  10656. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  10657. server_hostname_verification_ = enabled;
  10658. }
  10659. #endif
  10660. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10661. inline void ClientImpl::set_server_certificate_verifier(
  10662. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  10663. server_certificate_verifier_ = verifier;
  10664. }
  10665. #endif
  10666. inline void ClientImpl::set_logger(Logger logger) {
  10667. logger_ = std::move(logger);
  10668. }
  10669. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  10670. error_logger_ = std::move(error_logger);
  10671. }
  10672. /*
  10673. * Crypto Abstraction Layer Implementation
  10674. */
  10675. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10676. namespace detail {
  10677. namespace crypto {
  10678. inline size_t hash_size(HashAlgorithm algo) {
  10679. switch (algo) {
  10680. case HashAlgorithm::MD5: return 16;
  10681. case HashAlgorithm::SHA1: return 20;
  10682. case HashAlgorithm::SHA256: return 32;
  10683. case HashAlgorithm::SHA384: return 48;
  10684. case HashAlgorithm::SHA512: return 64;
  10685. default: return 0;
  10686. }
  10687. }
  10688. inline const EVP_MD *get_evp_md(HashAlgorithm algo) {
  10689. switch (algo) {
  10690. case HashAlgorithm::MD5: return EVP_md5();
  10691. case HashAlgorithm::SHA1: return EVP_sha1();
  10692. case HashAlgorithm::SHA256: return EVP_sha256();
  10693. case HashAlgorithm::SHA384: return EVP_sha384();
  10694. case HashAlgorithm::SHA512: return EVP_sha512();
  10695. default: return nullptr;
  10696. }
  10697. }
  10698. inline bool hash_raw(HashAlgorithm algo, const void *data, size_t len,
  10699. std::vector<uint8_t> &digest) {
  10700. auto md = get_evp_md(algo);
  10701. if (!md) { return false; }
  10702. auto ctx = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  10703. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  10704. if (!ctx) { return false; }
  10705. unsigned int hash_len = 0;
  10706. digest.resize(EVP_MAX_MD_SIZE);
  10707. if (EVP_DigestInit_ex(ctx.get(), md, nullptr) != 1) { return false; }
  10708. if (EVP_DigestUpdate(ctx.get(), data, len) != 1) { return false; }
  10709. if (EVP_DigestFinal_ex(ctx.get(), digest.data(), &hash_len) != 1) {
  10710. return false;
  10711. }
  10712. digest.resize(hash_len);
  10713. return true;
  10714. }
  10715. inline std::string hash(HashAlgorithm algo, const void *data, size_t len) {
  10716. std::vector<uint8_t> digest;
  10717. if (!hash_raw(algo, data, len, digest)) { return ""; }
  10718. std::stringstream ss;
  10719. for (auto byte : digest) {
  10720. ss << std::hex << std::setw(2) << std::setfill('0')
  10721. << static_cast<unsigned int>(byte);
  10722. }
  10723. return ss.str();
  10724. }
  10725. inline std::string hash(HashAlgorithm algo, const std::string &data) {
  10726. return hash(algo, data.c_str(), data.size());
  10727. }
  10728. } // namespace crypto
  10729. } // namespace detail
  10730. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10731. /*
  10732. * TLS Abstraction Layer Implementation
  10733. */
  10734. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10735. namespace detail {
  10736. namespace tls {
  10737. // OpenSSL-specific helpers for converting native types to PEM
  10738. inline std::string x509_to_pem(X509 *cert) {
  10739. if (!cert) return {};
  10740. BIO *bio = BIO_new(BIO_s_mem());
  10741. if (!bio) return {};
  10742. if (PEM_write_bio_X509(bio, cert) != 1) {
  10743. BIO_free(bio);
  10744. return {};
  10745. }
  10746. char *data = nullptr;
  10747. long len = BIO_get_mem_data(bio, &data);
  10748. std::string pem(data, static_cast<size_t>(len));
  10749. BIO_free(bio);
  10750. return pem;
  10751. }
  10752. inline std::string evp_pkey_to_pem(EVP_PKEY *key) {
  10753. if (!key) return {};
  10754. BIO *bio = BIO_new(BIO_s_mem());
  10755. if (!bio) return {};
  10756. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr,
  10757. nullptr) != 1) {
  10758. BIO_free(bio);
  10759. return {};
  10760. }
  10761. char *data = nullptr;
  10762. long len = BIO_get_mem_data(bio, &data);
  10763. std::string pem(data, static_cast<size_t>(len));
  10764. BIO_free(bio);
  10765. return pem;
  10766. }
  10767. inline std::string x509_store_to_pem(X509_STORE *store) {
  10768. if (!store) return {};
  10769. std::string pem;
  10770. auto objs = X509_STORE_get0_objects(store);
  10771. if (!objs) return {};
  10772. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  10773. auto obj = sk_X509_OBJECT_value(objs, i);
  10774. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  10775. auto cert = X509_OBJECT_get0_X509(obj);
  10776. if (cert) { pem += x509_to_pem(cert); }
  10777. }
  10778. }
  10779. return pem;
  10780. }
  10781. // Helper to map OpenSSL SSL_get_error to ErrorCode
  10782. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  10783. switch (ssl_error) {
  10784. case SSL_ERROR_NONE: return ErrorCode::Success;
  10785. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  10786. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  10787. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  10788. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  10789. case SSL_ERROR_SSL:
  10790. default: return ErrorCode::Fatal;
  10791. }
  10792. }
  10793. inline bool tls_global_init() {
  10794. // OpenSSL 3.0+: OPENSSL_init_ssl() is called automatically
  10795. return OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS |
  10796. OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  10797. nullptr) == 1;
  10798. }
  10799. inline void tls_global_cleanup() {
  10800. // OpenSSL 3.0+: cleanup is automatic
  10801. }
  10802. inline tls_ctx_t tls_create_client_context() {
  10803. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  10804. if (ctx) {
  10805. // Disable auto-retry to properly handle non-blocking I/O
  10806. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  10807. // Set minimum TLS version
  10808. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  10809. }
  10810. return static_cast<tls_ctx_t>(ctx);
  10811. }
  10812. inline void tls_free_context(tls_ctx_t ctx) {
  10813. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  10814. }
  10815. inline bool tls_set_min_version(tls_ctx_t ctx, int version) {
  10816. if (!ctx) return false;
  10817. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx), version) ==
  10818. 1;
  10819. }
  10820. inline bool tls_load_ca_pem(tls_ctx_t ctx, const char *pem, size_t len) {
  10821. if (!ctx || !pem || len == 0) return false;
  10822. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10823. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  10824. if (!store) return false;
  10825. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  10826. if (!bio) return false;
  10827. bool ok = true;
  10828. X509 *cert = nullptr;
  10829. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  10830. nullptr) {
  10831. if (X509_STORE_add_cert(store, cert) != 1) {
  10832. // Ignore duplicate errors
  10833. auto err = ERR_peek_last_error();
  10834. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  10835. ok = false;
  10836. }
  10837. }
  10838. X509_free(cert);
  10839. if (!ok) break;
  10840. }
  10841. BIO_free(bio);
  10842. // Clear any "no more certificates" errors
  10843. ERR_clear_error();
  10844. return ok;
  10845. }
  10846. inline bool tls_load_ca_file(tls_ctx_t ctx, const char *file_path) {
  10847. if (!ctx || !file_path) return false;
  10848. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  10849. nullptr) == 1;
  10850. }
  10851. inline bool tls_load_ca_dir(tls_ctx_t ctx, const char *dir_path) {
  10852. if (!ctx || !dir_path) return false;
  10853. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  10854. dir_path) == 1;
  10855. }
  10856. inline bool tls_load_system_certs(tls_ctx_t ctx) {
  10857. if (!ctx) return false;
  10858. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10859. #ifdef _WIN32
  10860. // Windows: Load from system certificate store
  10861. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  10862. if (!store) return false;
  10863. auto hStore = CertOpenSystemStoreW(NULL, L"ROOT");
  10864. if (!hStore) return false;
  10865. bool loaded_any = false;
  10866. PCCERT_CONTEXT pContext = nullptr;
  10867. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  10868. nullptr) {
  10869. const unsigned char *data = pContext->pbCertEncoded;
  10870. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  10871. if (x509) {
  10872. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  10873. X509_free(x509);
  10874. }
  10875. }
  10876. CertCloseStore(hStore, 0);
  10877. return loaded_any;
  10878. #elif defined(__APPLE__)
  10879. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  10880. // macOS: Load from Keychain
  10881. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  10882. if (!store) return false;
  10883. CFArrayRef certs = nullptr;
  10884. if (SecTrustCopyAnchorCertificates(&certs) != errSecSuccess || !certs) {
  10885. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10886. }
  10887. bool loaded_any = false;
  10888. auto count = CFArrayGetCount(certs);
  10889. for (CFIndex i = 0; i < count; i++) {
  10890. auto cert = reinterpret_cast<SecCertificateRef>(
  10891. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  10892. CFDataRef der = SecCertificateCopyData(cert);
  10893. if (der) {
  10894. const unsigned char *data = CFDataGetBytePtr(der);
  10895. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  10896. if (x509) {
  10897. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  10898. X509_free(x509);
  10899. }
  10900. CFRelease(der);
  10901. }
  10902. }
  10903. CFRelease(certs);
  10904. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10905. #else
  10906. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10907. #endif
  10908. #else
  10909. // Other Unix: use default verify paths
  10910. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10911. #endif
  10912. }
  10913. inline bool tls_set_client_cert_pem(tls_ctx_t ctx, const char *cert,
  10914. const char *key, const char *password) {
  10915. if (!ctx || !cert || !key) return false;
  10916. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10917. // Load certificate
  10918. auto cert_bio = BIO_new_mem_buf(cert, -1);
  10919. if (!cert_bio) return false;
  10920. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  10921. BIO_free(cert_bio);
  10922. if (!x509) return false;
  10923. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  10924. X509_free(x509);
  10925. if (!cert_ok) return false;
  10926. // Load private key
  10927. auto key_bio = BIO_new_mem_buf(key, -1);
  10928. if (!key_bio) return false;
  10929. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  10930. password ? const_cast<char *>(password)
  10931. : nullptr);
  10932. BIO_free(key_bio);
  10933. if (!pkey) return false;
  10934. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  10935. EVP_PKEY_free(pkey);
  10936. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  10937. }
  10938. inline bool tls_set_client_cert_file(tls_ctx_t ctx, const char *cert_path,
  10939. const char *key_path,
  10940. const char *password) {
  10941. if (!ctx || !cert_path || !key_path) return false;
  10942. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10943. if (password && password[0] != '\0') {
  10944. SSL_CTX_set_default_passwd_cb_userdata(
  10945. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  10946. }
  10947. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  10948. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  10949. }
  10950. inline tls_ctx_t tls_create_server_context() {
  10951. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  10952. if (ctx) {
  10953. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  10954. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  10955. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  10956. }
  10957. return static_cast<tls_ctx_t>(ctx);
  10958. }
  10959. inline bool tls_set_server_cert_pem(tls_ctx_t ctx, const char *cert,
  10960. const char *key, const char *password) {
  10961. // Same implementation as client cert
  10962. return tls_set_client_cert_pem(ctx, cert, key, password);
  10963. }
  10964. inline bool tls_set_server_cert_file(tls_ctx_t ctx, const char *cert_path,
  10965. const char *key_path,
  10966. const char *password) {
  10967. // Same implementation as client cert file
  10968. return tls_set_client_cert_file(ctx, cert_path, key_path, password);
  10969. }
  10970. inline bool tls_set_client_ca_file(tls_ctx_t ctx, const char *ca_file,
  10971. const char *ca_dir) {
  10972. if (!ctx) return false;
  10973. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10974. if (ca_file || ca_dir) {
  10975. if (SSL_CTX_load_verify_locations(ssl_ctx, ca_file, ca_dir) != 1) {
  10976. return false;
  10977. }
  10978. }
  10979. // Set CA list for client certificate request
  10980. if (ca_file) {
  10981. auto list = SSL_load_client_CA_file(ca_file);
  10982. if (list) { SSL_CTX_set_client_CA_list(ssl_ctx, list); }
  10983. }
  10984. return true;
  10985. }
  10986. inline void tls_set_verify_client(tls_ctx_t ctx, bool require) {
  10987. if (!ctx) return;
  10988. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  10989. require
  10990. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  10991. : SSL_VERIFY_NONE,
  10992. nullptr);
  10993. }
  10994. inline tls_session_t tls_create_session(tls_ctx_t ctx, socket_t sock) {
  10995. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  10996. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10997. SSL *ssl = SSL_new(ssl_ctx);
  10998. if (!ssl) return nullptr;
  10999. // Disable auto-retry for proper non-blocking I/O handling
  11000. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  11001. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  11002. if (!bio) {
  11003. SSL_free(ssl);
  11004. return nullptr;
  11005. }
  11006. SSL_set_bio(ssl, bio, bio);
  11007. return static_cast<tls_session_t>(ssl);
  11008. }
  11009. inline void tls_free_session(tls_session_t session) {
  11010. if (session) { SSL_free(static_cast<SSL *>(session)); }
  11011. }
  11012. inline bool tls_set_sni(tls_session_t session, const char *hostname) {
  11013. if (!session || !hostname) return false;
  11014. auto ssl = static_cast<SSL *>(session);
  11015. // Set SNI (Server Name Indication) only - does not enable verification
  11016. #if defined(OPENSSL_IS_BORINGSSL)
  11017. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  11018. #else
  11019. // Direct call instead of macro to suppress -Wold-style-cast warning
  11020. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  11021. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  11022. #endif
  11023. }
  11024. inline bool tls_set_hostname(tls_session_t session, const char *hostname) {
  11025. if (!session || !hostname) return false;
  11026. auto ssl = static_cast<SSL *>(session);
  11027. // Set SNI (Server Name Indication)
  11028. if (!tls_set_sni(session, hostname)) { return false; }
  11029. // Enable hostname verification
  11030. auto param = SSL_get0_param(ssl);
  11031. if (!param) return false;
  11032. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  11033. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  11034. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  11035. return true;
  11036. }
  11037. inline TlsError tls_connect(tls_session_t session) {
  11038. if (!session) { return TlsError(); }
  11039. auto ssl = static_cast<SSL *>(session);
  11040. auto ret = SSL_connect(ssl);
  11041. TlsError err;
  11042. if (ret == 1) {
  11043. err.code = ErrorCode::Success;
  11044. } else {
  11045. auto ssl_err = SSL_get_error(ssl, ret);
  11046. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11047. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11048. }
  11049. return err;
  11050. }
  11051. inline TlsError tls_accept(tls_session_t session) {
  11052. if (!session) { return TlsError(); }
  11053. auto ssl = static_cast<SSL *>(session);
  11054. auto ret = SSL_accept(ssl);
  11055. TlsError err;
  11056. if (ret == 1) {
  11057. err.code = ErrorCode::Success;
  11058. } else {
  11059. auto ssl_err = SSL_get_error(ssl, ret);
  11060. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11061. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11062. }
  11063. return err;
  11064. }
  11065. inline bool tls_connect_nonblocking(tls_session_t session, socket_t sock,
  11066. time_t timeout_sec, time_t timeout_usec,
  11067. TlsError *err) {
  11068. if (!session) {
  11069. if (err) { err->code = ErrorCode::Fatal; }
  11070. return false;
  11071. }
  11072. auto ssl = static_cast<SSL *>(session);
  11073. auto bio = SSL_get_rbio(ssl);
  11074. // Set non-blocking mode for handshake
  11075. set_nonblocking(sock, true);
  11076. if (bio) { BIO_set_nbio(bio, 1); }
  11077. auto cleanup = scope_exit([&]() {
  11078. // Restore blocking mode after handshake
  11079. if (bio) { BIO_set_nbio(bio, 0); }
  11080. set_nonblocking(sock, false);
  11081. });
  11082. auto res = 0;
  11083. while ((res = SSL_connect(ssl)) != 1) {
  11084. auto ssl_err = SSL_get_error(ssl, res);
  11085. switch (ssl_err) {
  11086. case SSL_ERROR_WANT_READ:
  11087. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  11088. break;
  11089. case SSL_ERROR_WANT_WRITE:
  11090. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  11091. break;
  11092. default: break;
  11093. }
  11094. if (err) {
  11095. err->code = map_ssl_error(ssl_err, err->sys_errno);
  11096. if (err->code == ErrorCode::Fatal) {
  11097. err->backend_code = ERR_get_error();
  11098. }
  11099. }
  11100. return false;
  11101. }
  11102. if (err) { err->code = ErrorCode::Success; }
  11103. return true;
  11104. }
  11105. inline bool tls_accept_nonblocking(tls_session_t session, socket_t sock,
  11106. time_t timeout_sec, time_t timeout_usec,
  11107. TlsError *err) {
  11108. if (!session) {
  11109. if (err) { err->code = ErrorCode::Fatal; }
  11110. return false;
  11111. }
  11112. auto ssl = static_cast<SSL *>(session);
  11113. auto bio = SSL_get_rbio(ssl);
  11114. // Set non-blocking mode for handshake
  11115. set_nonblocking(sock, true);
  11116. if (bio) { BIO_set_nbio(bio, 1); }
  11117. auto cleanup = scope_exit([&]() {
  11118. // Restore blocking mode after handshake
  11119. if (bio) { BIO_set_nbio(bio, 0); }
  11120. set_nonblocking(sock, false);
  11121. });
  11122. auto res = 0;
  11123. while ((res = SSL_accept(ssl)) != 1) {
  11124. auto ssl_err = SSL_get_error(ssl, res);
  11125. switch (ssl_err) {
  11126. case SSL_ERROR_WANT_READ:
  11127. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  11128. break;
  11129. case SSL_ERROR_WANT_WRITE:
  11130. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  11131. break;
  11132. default: break;
  11133. }
  11134. if (err) {
  11135. err->code = map_ssl_error(ssl_err, err->sys_errno);
  11136. if (err->code == ErrorCode::Fatal) {
  11137. err->backend_code = ERR_get_error();
  11138. }
  11139. }
  11140. return false;
  11141. }
  11142. if (err) { err->code = ErrorCode::Success; }
  11143. return true;
  11144. }
  11145. inline ssize_t tls_read(tls_session_t session, void *buf, size_t len,
  11146. TlsError &err) {
  11147. if (!session || !buf) {
  11148. err.code = ErrorCode::Fatal;
  11149. return -1;
  11150. }
  11151. auto ssl = static_cast<SSL *>(session);
  11152. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  11153. if (ret > 0) {
  11154. err.code = ErrorCode::Success;
  11155. return ret;
  11156. }
  11157. auto ssl_err = SSL_get_error(ssl, ret);
  11158. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11159. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11160. return -1;
  11161. }
  11162. inline ssize_t tls_write(tls_session_t session, const void *buf, size_t len,
  11163. TlsError &err) {
  11164. if (!session || !buf) {
  11165. err.code = ErrorCode::Fatal;
  11166. return -1;
  11167. }
  11168. auto ssl = static_cast<SSL *>(session);
  11169. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  11170. if (ret > 0) {
  11171. err.code = ErrorCode::Success;
  11172. return ret;
  11173. }
  11174. auto ssl_err = SSL_get_error(ssl, ret);
  11175. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11176. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11177. return -1;
  11178. }
  11179. inline int tls_pending(tls_session_t session) {
  11180. if (!session) return 0;
  11181. return SSL_pending(static_cast<SSL *>(session));
  11182. }
  11183. inline void tls_shutdown(tls_session_t session, bool graceful) {
  11184. if (!session) return;
  11185. auto ssl = static_cast<SSL *>(session);
  11186. if (graceful) {
  11187. // First call sends close_notify
  11188. if (SSL_shutdown(ssl) == 0) {
  11189. // Second call waits for peer's close_notify
  11190. SSL_shutdown(ssl);
  11191. }
  11192. }
  11193. }
  11194. inline bool tls_is_peer_closed(tls_session_t session, socket_t sock) {
  11195. if (!session) return true;
  11196. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  11197. set_nonblocking(sock, true);
  11198. auto se = scope_exit([&]() { set_nonblocking(sock, false); });
  11199. auto ssl = static_cast<SSL *>(session);
  11200. char buf;
  11201. auto ret = SSL_peek(ssl, &buf, 1);
  11202. if (ret > 0) return false;
  11203. auto err = SSL_get_error(ssl, ret);
  11204. return err == SSL_ERROR_ZERO_RETURN;
  11205. }
  11206. inline tls_cert_t tls_get_peer_cert(tls_session_t session) {
  11207. if (!session) return nullptr;
  11208. return static_cast<tls_cert_t>(
  11209. SSL_get1_peer_certificate(static_cast<SSL *>(session)));
  11210. }
  11211. inline void tls_free_cert(tls_cert_t cert) {
  11212. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  11213. }
  11214. inline bool tls_verify_hostname(tls_cert_t cert, const char *hostname) {
  11215. if (!cert || !hostname) return false;
  11216. auto x509 = static_cast<X509 *>(cert);
  11217. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  11218. }
  11219. inline long tls_get_verify_result(tls_session_t session) {
  11220. if (!session) return X509_V_ERR_UNSPECIFIED;
  11221. return SSL_get_verify_result(static_cast<SSL *>(session));
  11222. }
  11223. inline std::string tls_get_cert_subject_cn(tls_cert_t cert) {
  11224. if (!cert) return "";
  11225. auto x509 = static_cast<X509 *>(cert);
  11226. auto subject_name = X509_get_subject_name(x509);
  11227. if (!subject_name) return "";
  11228. char buf[256];
  11229. auto len =
  11230. X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf, sizeof(buf));
  11231. if (len < 0) return "";
  11232. return std::string(buf, static_cast<size_t>(len));
  11233. }
  11234. inline std::string tls_get_cert_issuer_name(tls_cert_t cert) {
  11235. if (!cert) return "";
  11236. auto x509 = static_cast<X509 *>(cert);
  11237. auto issuer_name = X509_get_issuer_name(x509);
  11238. if (!issuer_name) return "";
  11239. char buf[256];
  11240. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  11241. return std::string(buf);
  11242. }
  11243. inline bool tls_get_cert_sans(tls_cert_t cert, std::vector<TlsSanEntry> &sans) {
  11244. sans.clear();
  11245. if (!cert) return false;
  11246. auto x509 = static_cast<X509 *>(cert);
  11247. auto names = static_cast<GENERAL_NAMES *>(
  11248. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  11249. if (!names) return true; // No SANs is valid
  11250. auto count = sk_GENERAL_NAME_num(names);
  11251. for (int i = 0; i < count; i++) {
  11252. auto gen = sk_GENERAL_NAME_value(names, i);
  11253. if (!gen) continue;
  11254. TlsSanEntry entry;
  11255. switch (gen->type) {
  11256. case GEN_DNS:
  11257. entry.type = SanType::DNS;
  11258. if (gen->d.dNSName) {
  11259. entry.value = std::string(
  11260. reinterpret_cast<const char *>(
  11261. ASN1_STRING_get0_data(gen->d.dNSName)),
  11262. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  11263. }
  11264. break;
  11265. case GEN_IPADD:
  11266. entry.type = SanType::IP;
  11267. if (gen->d.iPAddress) {
  11268. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  11269. auto len = ASN1_STRING_length(gen->d.iPAddress);
  11270. if (len == 4) {
  11271. // IPv4
  11272. char buf[INET_ADDRSTRLEN];
  11273. inet_ntop(AF_INET, data, buf, sizeof(buf));
  11274. entry.value = buf;
  11275. } else if (len == 16) {
  11276. // IPv6
  11277. char buf[INET6_ADDRSTRLEN];
  11278. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  11279. entry.value = buf;
  11280. }
  11281. }
  11282. break;
  11283. case GEN_EMAIL:
  11284. entry.type = SanType::EMAIL;
  11285. if (gen->d.rfc822Name) {
  11286. entry.value = std::string(
  11287. reinterpret_cast<const char *>(
  11288. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  11289. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  11290. }
  11291. break;
  11292. case GEN_URI:
  11293. entry.type = SanType::URI;
  11294. if (gen->d.uniformResourceIdentifier) {
  11295. entry.value = std::string(
  11296. reinterpret_cast<const char *>(
  11297. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  11298. static_cast<size_t>(
  11299. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  11300. }
  11301. break;
  11302. default: entry.type = SanType::OTHER; break;
  11303. }
  11304. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  11305. }
  11306. GENERAL_NAMES_free(names);
  11307. return true;
  11308. }
  11309. inline bool tls_get_cert_validity(tls_cert_t cert, time_t &not_before,
  11310. time_t &not_after) {
  11311. if (!cert) return false;
  11312. auto x509 = static_cast<X509 *>(cert);
  11313. auto nb = X509_get0_notBefore(x509);
  11314. auto na = X509_get0_notAfter(x509);
  11315. if (!nb || !na) return false;
  11316. // Convert ASN1_TIME to time_t
  11317. struct tm tm_nb = {}, tm_na = {};
  11318. if (ASN1_TIME_to_tm(nb, &tm_nb) != 1) return false;
  11319. if (ASN1_TIME_to_tm(na, &tm_na) != 1) return false;
  11320. #ifdef _WIN32
  11321. not_before = _mkgmtime(&tm_nb);
  11322. not_after = _mkgmtime(&tm_na);
  11323. #else
  11324. not_before = timegm(&tm_nb);
  11325. not_after = timegm(&tm_na);
  11326. #endif
  11327. return true;
  11328. }
  11329. inline std::string tls_get_cert_serial(tls_cert_t cert) {
  11330. if (!cert) return "";
  11331. auto x509 = static_cast<X509 *>(cert);
  11332. auto serial = X509_get_serialNumber(x509);
  11333. if (!serial) return "";
  11334. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  11335. if (!bn) return "";
  11336. auto hex = BN_bn2hex(bn);
  11337. BN_free(bn);
  11338. if (!hex) return "";
  11339. std::string result(hex);
  11340. OPENSSL_free(hex);
  11341. return result;
  11342. }
  11343. inline const char *tls_get_sni(tls_session_t session) {
  11344. if (!session) return nullptr;
  11345. auto ssl = static_cast<SSL *>(session);
  11346. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  11347. }
  11348. inline uint64_t tls_peek_error() { return ERR_peek_last_error(); }
  11349. inline uint64_t tls_get_error() { return ERR_get_error(); }
  11350. inline std::string tls_error_string(uint64_t code) {
  11351. char buf[256];
  11352. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  11353. return std::string(buf);
  11354. }
  11355. inline tls_ca_store_t tls_create_ca_store(const char *pem, size_t len) {
  11356. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  11357. if (!mem) { return nullptr; }
  11358. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  11359. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  11360. if (!inf) { return nullptr; }
  11361. auto store = X509_STORE_new();
  11362. if (store) {
  11363. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  11364. auto itmp = sk_X509_INFO_value(inf, i);
  11365. if (!itmp) { continue; }
  11366. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  11367. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  11368. }
  11369. }
  11370. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  11371. return static_cast<tls_ca_store_t>(store);
  11372. }
  11373. inline void tls_free_ca_store(tls_ca_store_t store) {
  11374. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  11375. }
  11376. inline bool tls_set_ca_store(tls_ctx_t ctx, tls_ca_store_t store) {
  11377. if (!ctx || !store) { return false; }
  11378. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11379. auto x509_store = static_cast<X509_STORE *>(store);
  11380. // Check if same store is already set
  11381. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  11382. // SSL_CTX_set_cert_store takes ownership and frees the old store
  11383. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  11384. return true;
  11385. }
  11386. inline size_t tls_get_ca_certs(tls_ctx_t ctx, std::vector<tls_cert_t> &certs) {
  11387. certs.clear();
  11388. if (!ctx) { return 0; }
  11389. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11390. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  11391. if (!store) { return 0; }
  11392. auto objs = X509_STORE_get0_objects(store);
  11393. if (!objs) { return 0; }
  11394. int count = sk_X509_OBJECT_num(objs);
  11395. for (int i = 0; i < count; i++) {
  11396. auto obj = sk_X509_OBJECT_value(objs, i);
  11397. if (!obj) { continue; }
  11398. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  11399. auto x509 = X509_OBJECT_get0_X509(obj);
  11400. if (x509) {
  11401. // Increment reference count so caller can free it
  11402. X509_up_ref(x509);
  11403. certs.push_back(static_cast<tls_cert_t>(x509));
  11404. }
  11405. }
  11406. }
  11407. return certs.size();
  11408. }
  11409. inline std::vector<std::string> tls_get_ca_names(tls_ctx_t ctx) {
  11410. std::vector<std::string> names;
  11411. if (!ctx) { return names; }
  11412. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11413. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  11414. if (!store) { return names; }
  11415. auto objs = X509_STORE_get0_objects(store);
  11416. if (!objs) { return names; }
  11417. int count = sk_X509_OBJECT_num(objs);
  11418. for (int i = 0; i < count; i++) {
  11419. auto obj = sk_X509_OBJECT_value(objs, i);
  11420. if (!obj) { continue; }
  11421. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  11422. auto x509 = X509_OBJECT_get0_X509(obj);
  11423. if (x509) {
  11424. auto subject = X509_get_subject_name(x509);
  11425. if (subject) {
  11426. char buf[512];
  11427. X509_NAME_oneline(subject, buf, sizeof(buf));
  11428. names.push_back(buf);
  11429. }
  11430. }
  11431. }
  11432. }
  11433. return names;
  11434. }
  11435. inline bool tls_update_server_cert(tls_ctx_t ctx, const char *cert_pem,
  11436. const char *key_pem, const char *password) {
  11437. if (!ctx || !cert_pem || !key_pem) { return false; }
  11438. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11439. // Load certificate from PEM
  11440. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  11441. if (!cert_bio) { return false; }
  11442. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  11443. BIO_free(cert_bio);
  11444. if (!cert) { return false; }
  11445. // Load private key from PEM
  11446. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  11447. if (!key_bio) {
  11448. X509_free(cert);
  11449. return false;
  11450. }
  11451. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  11452. password ? const_cast<char *>(password)
  11453. : nullptr);
  11454. BIO_free(key_bio);
  11455. if (!key) {
  11456. X509_free(cert);
  11457. return false;
  11458. }
  11459. // Update certificate and key
  11460. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  11461. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  11462. X509_free(cert);
  11463. EVP_PKEY_free(key);
  11464. return ret;
  11465. }
  11466. inline bool tls_update_server_client_ca(tls_ctx_t ctx, const char *ca_pem) {
  11467. if (!ctx || !ca_pem) { return false; }
  11468. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11469. // Create new X509_STORE from PEM
  11470. auto store = tls_create_ca_store(ca_pem, strlen(ca_pem));
  11471. if (!store) { return false; }
  11472. // SSL_CTX_set_cert_store takes ownership
  11473. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  11474. return true;
  11475. }
  11476. // Thread-local storage for verify callback
  11477. inline TlsVerifyCallback &get_verify_callback() {
  11478. static thread_local TlsVerifyCallback callback;
  11479. return callback;
  11480. }
  11481. // OpenSSL verify callback wrapper
  11482. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  11483. auto &callback = get_verify_callback();
  11484. if (!callback) { return preverify_ok; }
  11485. // Get SSL object from X509_STORE_CTX
  11486. auto ssl = static_cast<SSL *>(
  11487. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  11488. if (!ssl) { return preverify_ok; }
  11489. // Get peer certificate
  11490. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  11491. if (!cert) { return preverify_ok; }
  11492. // Call user callback
  11493. return callback(static_cast<tls_session_t>(ssl),
  11494. static_cast<tls_cert_t>(cert))
  11495. ? 1
  11496. : 0;
  11497. }
  11498. inline bool tls_set_verify_callback(tls_ctx_t ctx, TlsVerifyCallback callback) {
  11499. if (!ctx) { return false; }
  11500. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11501. get_verify_callback() = std::move(callback);
  11502. if (get_verify_callback()) {
  11503. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, openssl_verify_callback);
  11504. } else {
  11505. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  11506. }
  11507. return true;
  11508. }
  11509. // Thread-local storage for extended verify callback
  11510. inline TlsVerifyCallbackEx &get_verify_callback_ex() {
  11511. static thread_local TlsVerifyCallbackEx callback;
  11512. return callback;
  11513. }
  11514. // OpenSSL extended verify callback wrapper
  11515. inline int openssl_verify_callback_ex(int preverify_ok, X509_STORE_CTX *ctx) {
  11516. auto &callback = get_verify_callback_ex();
  11517. if (!callback) { return preverify_ok; }
  11518. // Get SSL object from X509_STORE_CTX
  11519. auto ssl = static_cast<SSL *>(
  11520. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  11521. if (!ssl) { return preverify_ok; }
  11522. // Get current certificate and depth
  11523. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  11524. int depth = X509_STORE_CTX_get_error_depth(ctx);
  11525. int error = X509_STORE_CTX_get_error(ctx);
  11526. // Build context
  11527. TlsVerifyContext verify_ctx;
  11528. verify_ctx.session = static_cast<tls_session_t>(ssl);
  11529. verify_ctx.cert = static_cast<tls_cert_t>(cert);
  11530. verify_ctx.depth = depth;
  11531. verify_ctx.preverify_ok = (preverify_ok != 0);
  11532. verify_ctx.error_code = error;
  11533. verify_ctx.error_string =
  11534. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  11535. return callback(verify_ctx) ? 1 : 0;
  11536. }
  11537. inline bool tls_set_verify_callback_ex(tls_ctx_t ctx,
  11538. TlsVerifyCallbackEx callback) {
  11539. if (!ctx) { return false; }
  11540. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11541. get_verify_callback_ex() = std::move(callback);
  11542. if (get_verify_callback_ex()) {
  11543. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, openssl_verify_callback_ex);
  11544. } else {
  11545. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  11546. }
  11547. return true;
  11548. }
  11549. inline long tls_get_verify_error(tls_session_t session) {
  11550. if (!session) { return -1; }
  11551. auto ssl = static_cast<SSL *>(session);
  11552. return SSL_get_verify_result(ssl);
  11553. }
  11554. inline std::string tls_verify_error_string(long error_code) {
  11555. if (error_code == X509_V_OK) { return ""; }
  11556. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  11557. return str ? str : "unknown error";
  11558. }
  11559. // OpenSSL-specific helpers for public API wrappers
  11560. inline tls_ctx_t create_server_context_from_x509(X509 *cert, EVP_PKEY *key,
  11561. X509_STORE *client_ca_store,
  11562. int &out_error) {
  11563. out_error = 0;
  11564. auto cert_pem = x509_to_pem(cert);
  11565. auto key_pem = evp_pkey_to_pem(key);
  11566. if (cert_pem.empty() || key_pem.empty()) {
  11567. out_error = static_cast<int>(ERR_get_error());
  11568. return nullptr;
  11569. }
  11570. auto ctx = tls_create_server_context();
  11571. if (!ctx) {
  11572. out_error = static_cast<int>(tls_get_error());
  11573. return nullptr;
  11574. }
  11575. if (!tls_set_server_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  11576. nullptr)) {
  11577. out_error = static_cast<int>(tls_get_error());
  11578. tls_free_context(ctx);
  11579. return nullptr;
  11580. }
  11581. if (client_ca_store) {
  11582. auto ca_pem = x509_store_to_pem(client_ca_store);
  11583. if (!ca_pem.empty()) {
  11584. auto ca_store = tls_create_ca_store(ca_pem.c_str(), ca_pem.size());
  11585. if (ca_store && tls_set_ca_store(ctx, ca_store)) {
  11586. tls_set_verify_client(ctx, true);
  11587. } else {
  11588. out_error = static_cast<int>(tls_get_error());
  11589. }
  11590. }
  11591. X509_STORE_free(client_ca_store);
  11592. }
  11593. return ctx;
  11594. }
  11595. inline void update_server_certs_from_x509(tls_ctx_t ctx, X509 *cert,
  11596. EVP_PKEY *key,
  11597. X509_STORE *client_ca_store) {
  11598. auto cert_pem = x509_to_pem(cert);
  11599. auto key_pem = evp_pkey_to_pem(key);
  11600. if (!cert_pem.empty() && !key_pem.empty()) {
  11601. tls_update_server_cert(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr);
  11602. }
  11603. if (client_ca_store) {
  11604. auto ca_pem = x509_store_to_pem(client_ca_store);
  11605. if (!ca_pem.empty()) { tls_update_server_client_ca(ctx, ca_pem.c_str()); }
  11606. X509_STORE_free(client_ca_store);
  11607. }
  11608. }
  11609. inline tls_ctx_t create_client_context_from_x509(X509 *cert, EVP_PKEY *key,
  11610. const char *password,
  11611. unsigned long &out_error) {
  11612. out_error = 0;
  11613. auto ctx = tls_create_client_context();
  11614. if (!ctx) {
  11615. out_error = static_cast<unsigned long>(tls_get_error());
  11616. return nullptr;
  11617. }
  11618. if (cert && key) {
  11619. auto cert_pem = x509_to_pem(cert);
  11620. auto key_pem = evp_pkey_to_pem(key);
  11621. if (cert_pem.empty() || key_pem.empty()) {
  11622. out_error = ERR_get_error();
  11623. tls_free_context(ctx);
  11624. return nullptr;
  11625. }
  11626. if (!tls_set_client_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  11627. password)) {
  11628. out_error = static_cast<unsigned long>(tls_get_error());
  11629. tls_free_context(ctx);
  11630. return nullptr;
  11631. }
  11632. }
  11633. return ctx;
  11634. }
  11635. } // namespace tls
  11636. } // namespace detail
  11637. // ClientImpl::set_ca_cert_store - defined here to use tls::x509_store_to_pem
  11638. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  11639. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  11640. ca_cert_pem_ = detail::tls::x509_store_to_pem(ca_cert_store);
  11641. ca_cert_store_ = ca_cert_store;
  11642. }
  11643. }
  11644. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  11645. /*
  11646. * Mbed TLS Crypto Implementation
  11647. */
  11648. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  11649. namespace detail {
  11650. namespace crypto {
  11651. inline size_t hash_size(HashAlgorithm algo) {
  11652. switch (algo) {
  11653. case HashAlgorithm::MD5: return 16;
  11654. case HashAlgorithm::SHA1: return 20;
  11655. case HashAlgorithm::SHA256: return 32;
  11656. case HashAlgorithm::SHA384: return 48;
  11657. case HashAlgorithm::SHA512: return 64;
  11658. default: return 0;
  11659. }
  11660. }
  11661. inline bool hash_raw(HashAlgorithm algo, const void *data, size_t len,
  11662. std::vector<uint8_t> &digest) {
  11663. size_t dsize = hash_size(algo);
  11664. if (dsize == 0) { return false; }
  11665. digest.resize(dsize);
  11666. int ret = 0;
  11667. switch (algo) {
  11668. case HashAlgorithm::MD5:
  11669. #if MBEDTLS_VERSION_MAJOR >= 3
  11670. ret = mbedtls_md5(static_cast<const unsigned char *>(data), len,
  11671. digest.data());
  11672. #else
  11673. ret = mbedtls_md5_ret(static_cast<const unsigned char *>(data), len,
  11674. digest.data());
  11675. #endif
  11676. break;
  11677. case HashAlgorithm::SHA1:
  11678. #if MBEDTLS_VERSION_MAJOR >= 3
  11679. ret = mbedtls_sha1(static_cast<const unsigned char *>(data), len,
  11680. digest.data());
  11681. #else
  11682. ret = mbedtls_sha1_ret(static_cast<const unsigned char *>(data), len,
  11683. digest.data());
  11684. #endif
  11685. break;
  11686. case HashAlgorithm::SHA256:
  11687. #if MBEDTLS_VERSION_MAJOR >= 3
  11688. ret = mbedtls_sha256(static_cast<const unsigned char *>(data), len,
  11689. digest.data(), 0);
  11690. #else
  11691. ret = mbedtls_sha256_ret(static_cast<const unsigned char *>(data), len,
  11692. digest.data(), 0);
  11693. #endif
  11694. break;
  11695. case HashAlgorithm::SHA384:
  11696. #if MBEDTLS_VERSION_MAJOR >= 3
  11697. ret = mbedtls_sha512(static_cast<const unsigned char *>(data), len,
  11698. digest.data(), 1); // is384 = 1
  11699. #else
  11700. ret = mbedtls_sha512_ret(static_cast<const unsigned char *>(data), len,
  11701. digest.data(), 1); // is384 = 1
  11702. #endif
  11703. break;
  11704. case HashAlgorithm::SHA512:
  11705. #if MBEDTLS_VERSION_MAJOR >= 3
  11706. ret = mbedtls_sha512(static_cast<const unsigned char *>(data), len,
  11707. digest.data(), 0);
  11708. #else
  11709. ret = mbedtls_sha512_ret(static_cast<const unsigned char *>(data), len,
  11710. digest.data(), 0);
  11711. #endif
  11712. break;
  11713. }
  11714. return ret == 0;
  11715. }
  11716. inline std::string hash(HashAlgorithm algo, const void *data, size_t len) {
  11717. std::vector<uint8_t> digest;
  11718. if (!hash_raw(algo, data, len, digest)) { return ""; }
  11719. std::stringstream ss;
  11720. for (auto byte : digest) {
  11721. ss << std::hex << std::setw(2) << std::setfill('0')
  11722. << static_cast<unsigned int>(byte);
  11723. }
  11724. return ss.str();
  11725. }
  11726. inline std::string hash(HashAlgorithm algo, const std::string &data) {
  11727. return hash(algo, data.c_str(), data.size());
  11728. }
  11729. } // namespace crypto
  11730. } // namespace detail
  11731. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  11732. /*
  11733. * Mbed TLS Backend Implementation
  11734. */
  11735. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  11736. namespace detail {
  11737. namespace tls {
  11738. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  11739. // cert/key)
  11740. struct MbedTlsContext {
  11741. mbedtls_ssl_config conf;
  11742. mbedtls_entropy_context entropy;
  11743. mbedtls_ctr_drbg_context ctr_drbg;
  11744. mbedtls_x509_crt ca_chain;
  11745. mbedtls_x509_crt own_cert;
  11746. mbedtls_pk_context own_key;
  11747. bool is_server = false;
  11748. bool verify_client = false;
  11749. bool has_verify_callback = false;
  11750. MbedTlsContext() {
  11751. mbedtls_ssl_config_init(&conf);
  11752. mbedtls_entropy_init(&entropy);
  11753. mbedtls_ctr_drbg_init(&ctr_drbg);
  11754. mbedtls_x509_crt_init(&ca_chain);
  11755. mbedtls_x509_crt_init(&own_cert);
  11756. mbedtls_pk_init(&own_key);
  11757. }
  11758. ~MbedTlsContext() {
  11759. mbedtls_pk_free(&own_key);
  11760. mbedtls_x509_crt_free(&own_cert);
  11761. mbedtls_x509_crt_free(&ca_chain);
  11762. mbedtls_ctr_drbg_free(&ctr_drbg);
  11763. mbedtls_entropy_free(&entropy);
  11764. mbedtls_ssl_config_free(&conf);
  11765. }
  11766. // Non-copyable
  11767. MbedTlsContext(const MbedTlsContext &) = delete;
  11768. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  11769. };
  11770. // Mbed TLS session wrapper
  11771. struct MbedTlsSession {
  11772. mbedtls_ssl_context ssl;
  11773. socket_t sock = INVALID_SOCKET;
  11774. std::string hostname; // For client: set via tls_set_sni
  11775. std::string sni_hostname; // For server: received from client via SNI callback
  11776. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  11777. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  11778. // Non-copyable
  11779. MbedTlsSession(const MbedTlsSession &) = delete;
  11780. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  11781. };
  11782. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  11783. // queue)
  11784. inline int &mbedtls_last_error() {
  11785. static thread_local int err = 0;
  11786. return err;
  11787. }
  11788. // Helper to map Mbed TLS error to ErrorCode
  11789. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  11790. if (ret == 0) { return ErrorCode::Success; }
  11791. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  11792. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  11793. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  11794. return ErrorCode::PeerClosed;
  11795. }
  11796. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  11797. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  11798. out_errno = errno;
  11799. return ErrorCode::SyscallError;
  11800. }
  11801. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  11802. return ErrorCode::CertVerifyFailed;
  11803. }
  11804. return ErrorCode::Fatal;
  11805. }
  11806. inline bool tls_global_init() {
  11807. // Mbed TLS doesn't require global initialization
  11808. return true;
  11809. }
  11810. inline void tls_global_cleanup() {
  11811. // Mbed TLS doesn't require global cleanup
  11812. }
  11813. // BIO-like send callback for Mbed TLS
  11814. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  11815. size_t len) {
  11816. auto sock = *static_cast<socket_t *>(ctx);
  11817. #ifdef _WIN32
  11818. auto ret =
  11819. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  11820. if (ret == SOCKET_ERROR) {
  11821. int err = WSAGetLastError();
  11822. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  11823. return MBEDTLS_ERR_NET_SEND_FAILED;
  11824. }
  11825. #else
  11826. auto ret = send(sock, buf, len, 0);
  11827. if (ret < 0) {
  11828. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  11829. return MBEDTLS_ERR_SSL_WANT_WRITE;
  11830. }
  11831. return MBEDTLS_ERR_NET_SEND_FAILED;
  11832. }
  11833. #endif
  11834. return static_cast<int>(ret);
  11835. }
  11836. // BIO-like recv callback for Mbed TLS
  11837. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  11838. auto sock = *static_cast<socket_t *>(ctx);
  11839. #ifdef _WIN32
  11840. auto ret =
  11841. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  11842. if (ret == SOCKET_ERROR) {
  11843. int err = WSAGetLastError();
  11844. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  11845. return MBEDTLS_ERR_NET_RECV_FAILED;
  11846. }
  11847. #else
  11848. auto ret = recv(sock, buf, len, 0);
  11849. if (ret < 0) {
  11850. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  11851. return MBEDTLS_ERR_SSL_WANT_READ;
  11852. }
  11853. return MBEDTLS_ERR_NET_RECV_FAILED;
  11854. }
  11855. #endif
  11856. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  11857. return static_cast<int>(ret);
  11858. }
  11859. inline tls_ctx_t tls_create_client_context() {
  11860. auto ctx = new (std::nothrow) MbedTlsContext();
  11861. if (!ctx) { return nullptr; }
  11862. ctx->is_server = false;
  11863. // Seed the random number generator
  11864. const char *pers = "httplib_client";
  11865. int ret = mbedtls_ctr_drbg_seed(
  11866. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  11867. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  11868. if (ret != 0) {
  11869. mbedtls_last_error() = ret;
  11870. delete ctx;
  11871. return nullptr;
  11872. }
  11873. // Set up SSL config for client
  11874. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  11875. MBEDTLS_SSL_TRANSPORT_STREAM,
  11876. MBEDTLS_SSL_PRESET_DEFAULT);
  11877. if (ret != 0) {
  11878. mbedtls_last_error() = ret;
  11879. delete ctx;
  11880. return nullptr;
  11881. }
  11882. // Set random number generator
  11883. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  11884. // Default: verify peer certificate
  11885. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  11886. // Set minimum TLS version to 1.2
  11887. #if MBEDTLS_VERSION_MAJOR >= 3
  11888. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  11889. #else
  11890. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  11891. MBEDTLS_SSL_MINOR_VERSION_3);
  11892. #endif
  11893. return static_cast<tls_ctx_t>(ctx);
  11894. }
  11895. // Forward declaration for SNI callback (defined later)
  11896. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  11897. const unsigned char *name, size_t name_len);
  11898. inline tls_ctx_t tls_create_server_context() {
  11899. auto ctx = new (std::nothrow) MbedTlsContext();
  11900. if (!ctx) { return nullptr; }
  11901. ctx->is_server = true;
  11902. // Seed the random number generator
  11903. const char *pers = "httplib_server";
  11904. int ret = mbedtls_ctr_drbg_seed(
  11905. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  11906. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  11907. if (ret != 0) {
  11908. mbedtls_last_error() = ret;
  11909. delete ctx;
  11910. return nullptr;
  11911. }
  11912. // Set up SSL config for server
  11913. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  11914. MBEDTLS_SSL_TRANSPORT_STREAM,
  11915. MBEDTLS_SSL_PRESET_DEFAULT);
  11916. if (ret != 0) {
  11917. mbedtls_last_error() = ret;
  11918. delete ctx;
  11919. return nullptr;
  11920. }
  11921. // Set random number generator
  11922. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  11923. // Default: don't verify client
  11924. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  11925. // Set minimum TLS version to 1.2
  11926. #if MBEDTLS_VERSION_MAJOR >= 3
  11927. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  11928. #else
  11929. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  11930. MBEDTLS_SSL_MINOR_VERSION_3);
  11931. #endif
  11932. // Set SNI callback to capture client's SNI hostname
  11933. mbedtls_ssl_conf_sni(&ctx->conf, mbedtls_sni_callback, nullptr);
  11934. return static_cast<tls_ctx_t>(ctx);
  11935. }
  11936. inline void tls_free_context(tls_ctx_t ctx) {
  11937. if (ctx) { delete static_cast<MbedTlsContext *>(ctx); }
  11938. }
  11939. inline bool tls_set_min_version(tls_ctx_t ctx, int version) {
  11940. if (!ctx) { return false; }
  11941. auto mctx = static_cast<MbedTlsContext *>(ctx);
  11942. // Map OpenSSL-style version constants to Mbed TLS
  11943. // TLS1_2_VERSION = 0x0303, TLS1_3_VERSION = 0x0304
  11944. #if MBEDTLS_VERSION_MAJOR >= 3
  11945. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  11946. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  11947. if (version >= 0x0304) {
  11948. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  11949. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  11950. #endif
  11951. }
  11952. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  11953. #else
  11954. // Mbed TLS 2.x uses major/minor version numbers
  11955. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  11956. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  11957. if (version >= 0x0304) {
  11958. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  11959. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  11960. #else
  11961. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  11962. #endif
  11963. }
  11964. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  11965. #endif
  11966. return true;
  11967. }
  11968. inline bool tls_load_ca_pem(tls_ctx_t ctx, const char *pem, size_t len) {
  11969. if (!ctx || !pem) { return false; }
  11970. auto mctx = static_cast<MbedTlsContext *>(ctx);
  11971. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  11972. // Add null terminator if not present
  11973. std::string pem_str(pem, len);
  11974. int ret = mbedtls_x509_crt_parse(
  11975. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  11976. pem_str.size() + 1);
  11977. if (ret != 0) {
  11978. mbedtls_last_error() = ret;
  11979. return false;
  11980. }
  11981. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  11982. return true;
  11983. }
  11984. inline bool tls_load_ca_file(tls_ctx_t ctx, const char *file_path) {
  11985. if (!ctx || !file_path) { return false; }
  11986. auto mctx = static_cast<MbedTlsContext *>(ctx);
  11987. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  11988. if (ret != 0) {
  11989. mbedtls_last_error() = ret;
  11990. return false;
  11991. }
  11992. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  11993. return true;
  11994. }
  11995. inline bool tls_load_ca_dir(tls_ctx_t ctx, const char *dir_path) {
  11996. if (!ctx || !dir_path) { return false; }
  11997. auto mctx = static_cast<MbedTlsContext *>(ctx);
  11998. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  11999. if (ret < 0) { // Returns number of certs on success, negative on error
  12000. mbedtls_last_error() = ret;
  12001. return false;
  12002. }
  12003. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  12004. return true;
  12005. }
  12006. inline bool tls_load_system_certs(tls_ctx_t ctx) {
  12007. if (!ctx) { return false; }
  12008. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12009. bool loaded = false;
  12010. #ifdef _WIN32
  12011. // Load from Windows certificate store
  12012. HCERTSTORE hStore = CertOpenSystemStoreW(0, L"ROOT");
  12013. if (hStore) {
  12014. PCCERT_CONTEXT pContext = nullptr;
  12015. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  12016. nullptr) {
  12017. int ret = mbedtls_x509_crt_parse_der(
  12018. &mctx->ca_chain, pContext->pbCertEncoded, pContext->cbCertEncoded);
  12019. if (ret == 0) { loaded = true; }
  12020. }
  12021. CertCloseStore(hStore, 0);
  12022. }
  12023. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  12024. // Load from macOS Keychain
  12025. CFArrayRef certs = nullptr;
  12026. OSStatus status = SecTrustCopyAnchorCertificates(&certs);
  12027. if (status == errSecSuccess && certs) {
  12028. CFIndex count = CFArrayGetCount(certs);
  12029. for (CFIndex i = 0; i < count; i++) {
  12030. SecCertificateRef cert =
  12031. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  12032. CFDataRef data = SecCertificateCopyData(cert);
  12033. if (data) {
  12034. int ret = mbedtls_x509_crt_parse_der(
  12035. &mctx->ca_chain, CFDataGetBytePtr(data),
  12036. static_cast<size_t>(CFDataGetLength(data)));
  12037. if (ret == 0) { loaded = true; }
  12038. CFRelease(data);
  12039. }
  12040. }
  12041. CFRelease(certs);
  12042. }
  12043. #else
  12044. // Try common CA certificate locations on Linux/Unix
  12045. static const char *ca_paths[] = {
  12046. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  12047. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  12048. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  12049. "/etc/pki/tls/cacert.pem", // OpenELEC
  12050. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  12051. nullptr};
  12052. for (const char **path = ca_paths; *path; ++path) {
  12053. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path);
  12054. if (ret >= 0) {
  12055. loaded = true;
  12056. break;
  12057. }
  12058. }
  12059. // Also try the CA directory
  12060. if (!loaded) {
  12061. static const char *ca_dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  12062. "/etc/pki/tls/certs", // RHEL/CentOS
  12063. "/usr/share/ca-certificates", nullptr};
  12064. for (const char **dir = ca_dirs; *dir; ++dir) {
  12065. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir);
  12066. if (ret >= 0) {
  12067. loaded = true;
  12068. break;
  12069. }
  12070. }
  12071. }
  12072. #endif
  12073. if (loaded) {
  12074. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  12075. }
  12076. return loaded;
  12077. }
  12078. inline bool tls_set_client_cert_pem(tls_ctx_t ctx, const char *cert,
  12079. const char *key, const char *password) {
  12080. if (!ctx || !cert || !key) { return false; }
  12081. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12082. // Parse certificate
  12083. std::string cert_str(cert);
  12084. int ret = mbedtls_x509_crt_parse(
  12085. &mctx->own_cert,
  12086. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  12087. cert_str.size() + 1);
  12088. if (ret != 0) {
  12089. mbedtls_last_error() = ret;
  12090. return false;
  12091. }
  12092. // Parse private key
  12093. std::string key_str(key);
  12094. const unsigned char *pwd =
  12095. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  12096. size_t pwd_len = password ? strlen(password) : 0;
  12097. #if MBEDTLS_VERSION_MAJOR >= 3
  12098. ret = mbedtls_pk_parse_key(
  12099. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  12100. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  12101. &mctx->ctr_drbg);
  12102. #else
  12103. ret = mbedtls_pk_parse_key(
  12104. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  12105. key_str.size() + 1, pwd, pwd_len);
  12106. #endif
  12107. if (ret != 0) {
  12108. mbedtls_last_error() = ret;
  12109. return false;
  12110. }
  12111. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  12112. if (ret != 0) {
  12113. mbedtls_last_error() = ret;
  12114. return false;
  12115. }
  12116. return true;
  12117. }
  12118. inline bool tls_set_client_cert_file(tls_ctx_t ctx, const char *cert_path,
  12119. const char *key_path,
  12120. const char *password) {
  12121. if (!ctx || !cert_path || !key_path) { return false; }
  12122. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12123. // Parse certificate file
  12124. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  12125. if (ret != 0) {
  12126. mbedtls_last_error() = ret;
  12127. return false;
  12128. }
  12129. // Parse private key file
  12130. #if MBEDTLS_VERSION_MAJOR >= 3
  12131. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  12132. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  12133. #else
  12134. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  12135. #endif
  12136. if (ret != 0) {
  12137. mbedtls_last_error() = ret;
  12138. return false;
  12139. }
  12140. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  12141. if (ret != 0) {
  12142. mbedtls_last_error() = ret;
  12143. return false;
  12144. }
  12145. return true;
  12146. }
  12147. inline bool tls_set_server_cert_pem(tls_ctx_t ctx, const char *cert,
  12148. const char *key, const char *password) {
  12149. // Same as client cert for Mbed TLS
  12150. return tls_set_client_cert_pem(ctx, cert, key, password);
  12151. }
  12152. inline bool tls_set_server_cert_file(tls_ctx_t ctx, const char *cert_path,
  12153. const char *key_path,
  12154. const char *password) {
  12155. // Same as client cert for Mbed TLS
  12156. return tls_set_client_cert_file(ctx, cert_path, key_path, password);
  12157. }
  12158. inline bool tls_set_client_ca_file(tls_ctx_t ctx, const char *ca_file,
  12159. const char *ca_dir) {
  12160. if (!ctx) { return false; }
  12161. bool success = true;
  12162. if (ca_file && *ca_file) {
  12163. if (!tls_load_ca_file(ctx, ca_file)) { success = false; }
  12164. }
  12165. if (ca_dir && *ca_dir) {
  12166. if (!tls_load_ca_dir(ctx, ca_dir)) { success = false; }
  12167. }
  12168. return success;
  12169. }
  12170. inline void tls_set_verify_client(tls_ctx_t ctx, bool require) {
  12171. if (!ctx) { return; }
  12172. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12173. mctx->verify_client = require;
  12174. if (require) {
  12175. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  12176. } else {
  12177. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  12178. // is called (matching OpenSSL behavior). Otherwise use NONE.
  12179. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  12180. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  12181. : MBEDTLS_SSL_VERIFY_NONE);
  12182. }
  12183. }
  12184. // Thread-local storage for SNI captured during handshake
  12185. // This is needed because the SNI callback doesn't have a way to pass
  12186. // session-specific data before the session is fully set up
  12187. inline std::string &mbedtls_pending_sni() {
  12188. static thread_local std::string sni;
  12189. return sni;
  12190. }
  12191. // SNI callback for Mbed TLS server to capture client's SNI hostname
  12192. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  12193. const unsigned char *name, size_t name_len) {
  12194. (void)p_ctx;
  12195. (void)ssl;
  12196. // Store SNI name in thread-local storage
  12197. // It will be retrieved and stored in the session after handshake
  12198. if (name && name_len > 0) {
  12199. mbedtls_pending_sni().assign(reinterpret_cast<const char *>(name),
  12200. name_len);
  12201. } else {
  12202. mbedtls_pending_sni().clear();
  12203. }
  12204. return 0; // Accept any SNI
  12205. }
  12206. inline tls_session_t tls_create_session(tls_ctx_t ctx, socket_t sock) {
  12207. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  12208. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12209. auto session = new (std::nothrow) MbedTlsSession();
  12210. if (!session) { return nullptr; }
  12211. session->sock = sock;
  12212. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  12213. if (ret != 0) {
  12214. mbedtls_last_error() = ret;
  12215. delete session;
  12216. return nullptr;
  12217. }
  12218. // Set BIO callbacks
  12219. mbedtls_ssl_set_bio(&session->ssl, &session->sock, mbedtls_net_send_cb,
  12220. mbedtls_net_recv_cb, nullptr);
  12221. return static_cast<tls_session_t>(session);
  12222. }
  12223. inline void tls_free_session(tls_session_t session) {
  12224. if (session) { delete static_cast<MbedTlsSession *>(session); }
  12225. }
  12226. inline bool tls_set_sni(tls_session_t session, const char *hostname) {
  12227. if (!session || !hostname) { return false; }
  12228. auto msession = static_cast<MbedTlsSession *>(session);
  12229. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  12230. if (ret != 0) {
  12231. mbedtls_last_error() = ret;
  12232. return false;
  12233. }
  12234. msession->hostname = hostname;
  12235. return true;
  12236. }
  12237. inline bool tls_set_hostname(tls_session_t session, const char *hostname) {
  12238. // In Mbed TLS, set_hostname also sets up hostname verification
  12239. return tls_set_sni(session, hostname);
  12240. }
  12241. inline TlsError tls_connect(tls_session_t session) {
  12242. TlsError err;
  12243. if (!session) {
  12244. err.code = ErrorCode::Fatal;
  12245. return err;
  12246. }
  12247. auto msession = static_cast<MbedTlsSession *>(session);
  12248. int ret = mbedtls_ssl_handshake(&msession->ssl);
  12249. if (ret == 0) {
  12250. err.code = ErrorCode::Success;
  12251. } else {
  12252. err.code = map_mbedtls_error(ret, err.sys_errno);
  12253. err.backend_code = static_cast<uint64_t>(-ret);
  12254. mbedtls_last_error() = ret;
  12255. }
  12256. return err;
  12257. }
  12258. inline TlsError tls_accept(tls_session_t session) {
  12259. // Same as connect for Mbed TLS - handshake works for both client and server
  12260. auto result = tls_connect(session);
  12261. // After successful handshake, capture SNI from thread-local storage
  12262. if (result.code == ErrorCode::Success && session) {
  12263. auto msession = static_cast<MbedTlsSession *>(session);
  12264. msession->sni_hostname = std::move(mbedtls_pending_sni());
  12265. mbedtls_pending_sni().clear();
  12266. }
  12267. return result;
  12268. }
  12269. inline bool tls_connect_nonblocking(tls_session_t session, socket_t sock,
  12270. time_t timeout_sec, time_t timeout_usec,
  12271. TlsError *err) {
  12272. if (!session) {
  12273. if (err) { err->code = ErrorCode::Fatal; }
  12274. return false;
  12275. }
  12276. auto msession = static_cast<MbedTlsSession *>(session);
  12277. // Set socket to non-blocking mode
  12278. set_nonblocking(sock, true);
  12279. auto cleanup = scope_exit([&]() { set_nonblocking(sock, false); });
  12280. int ret;
  12281. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  12282. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  12283. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  12284. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  12285. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  12286. }
  12287. // Error or timeout
  12288. if (err) {
  12289. err->code = map_mbedtls_error(ret, err->sys_errno);
  12290. err->backend_code = static_cast<uint64_t>(-ret);
  12291. }
  12292. mbedtls_last_error() = ret;
  12293. return false;
  12294. }
  12295. if (err) { err->code = ErrorCode::Success; }
  12296. return true;
  12297. }
  12298. inline bool tls_accept_nonblocking(tls_session_t session, socket_t sock,
  12299. time_t timeout_sec, time_t timeout_usec,
  12300. TlsError *err) {
  12301. // Same implementation as connect for Mbed TLS
  12302. bool result =
  12303. tls_connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  12304. // After successful handshake, capture SNI from thread-local storage
  12305. if (result && session) {
  12306. auto msession = static_cast<MbedTlsSession *>(session);
  12307. msession->sni_hostname = std::move(mbedtls_pending_sni());
  12308. mbedtls_pending_sni().clear();
  12309. }
  12310. return result;
  12311. }
  12312. inline ssize_t tls_read(tls_session_t session, void *buf, size_t len,
  12313. TlsError &err) {
  12314. if (!session || !buf) {
  12315. err.code = ErrorCode::Fatal;
  12316. return -1;
  12317. }
  12318. auto msession = static_cast<MbedTlsSession *>(session);
  12319. int ret =
  12320. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  12321. if (ret > 0) {
  12322. err.code = ErrorCode::Success;
  12323. return static_cast<ssize_t>(ret);
  12324. }
  12325. if (ret == 0) {
  12326. err.code = ErrorCode::PeerClosed;
  12327. return 0;
  12328. }
  12329. err.code = map_mbedtls_error(ret, err.sys_errno);
  12330. err.backend_code = static_cast<uint64_t>(-ret);
  12331. mbedtls_last_error() = ret;
  12332. return -1;
  12333. }
  12334. inline ssize_t tls_write(tls_session_t session, const void *buf, size_t len,
  12335. TlsError &err) {
  12336. if (!session || !buf) {
  12337. err.code = ErrorCode::Fatal;
  12338. return -1;
  12339. }
  12340. auto msession = static_cast<MbedTlsSession *>(session);
  12341. int ret = mbedtls_ssl_write(&msession->ssl,
  12342. static_cast<const unsigned char *>(buf), len);
  12343. if (ret > 0) {
  12344. err.code = ErrorCode::Success;
  12345. return static_cast<ssize_t>(ret);
  12346. }
  12347. if (ret == 0) {
  12348. err.code = ErrorCode::PeerClosed;
  12349. return 0;
  12350. }
  12351. err.code = map_mbedtls_error(ret, err.sys_errno);
  12352. err.backend_code = static_cast<uint64_t>(-ret);
  12353. mbedtls_last_error() = ret;
  12354. return -1;
  12355. }
  12356. inline int tls_pending(tls_session_t session) {
  12357. if (!session) { return 0; }
  12358. auto msession = static_cast<MbedTlsSession *>(session);
  12359. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  12360. }
  12361. inline void tls_shutdown(tls_session_t session, bool graceful) {
  12362. if (!session) { return; }
  12363. auto msession = static_cast<MbedTlsSession *>(session);
  12364. if (graceful) {
  12365. // Try to send close_notify, but don't block forever
  12366. int ret;
  12367. int attempts = 0;
  12368. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  12369. attempts < 3) {
  12370. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  12371. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  12372. break;
  12373. }
  12374. attempts++;
  12375. }
  12376. }
  12377. }
  12378. inline bool tls_is_peer_closed(tls_session_t session, socket_t sock) {
  12379. if (!session || sock == INVALID_SOCKET) { return true; }
  12380. auto msession = static_cast<MbedTlsSession *>(session);
  12381. // Check if there's already decrypted data available in the TLS buffer
  12382. // If so, the connection is definitely alive
  12383. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  12384. // Set socket to non-blocking to avoid blocking on read
  12385. set_nonblocking(sock, true);
  12386. auto cleanup = scope_exit([&]() { set_nonblocking(sock, false); });
  12387. // Try a 1-byte read to check connection status
  12388. // Note: This will consume the byte if data is available, but for the
  12389. // purpose of checking if peer is closed, this should be acceptable
  12390. // since we're only called when we expect the connection might be closing
  12391. unsigned char buf;
  12392. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  12393. // If we got data or WANT_READ (would block), connection is alive
  12394. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  12395. // If we get a peer close notify or a connection reset, the peer is closed
  12396. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  12397. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  12398. }
  12399. inline tls_cert_t tls_get_peer_cert(tls_session_t session) {
  12400. if (!session) { return nullptr; }
  12401. auto msession = static_cast<MbedTlsSession *>(session);
  12402. // Mbed TLS returns a pointer to the peer cert chain, no need to free
  12403. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  12404. return const_cast<mbedtls_x509_crt *>(cert);
  12405. }
  12406. inline void tls_free_cert(tls_cert_t cert) {
  12407. // Mbed TLS: peer certificate is owned by the SSL context, don't free
  12408. (void)cert;
  12409. }
  12410. namespace {
  12411. // Helper function to match hostname with pattern (supports wildcards)
  12412. inline bool match_hostname(const std::string &pattern,
  12413. const std::string &hostname) {
  12414. if (pattern == hostname) { return true; }
  12415. // Wildcard matching: *.example.com matches foo.example.com
  12416. if (pattern.size() > 2 && pattern[0] == '*' && pattern[1] == '.') {
  12417. std::string suffix = pattern.substr(1); // .example.com
  12418. size_t dot_pos = hostname.find('.');
  12419. if (dot_pos != std::string::npos) {
  12420. std::string host_suffix = hostname.substr(dot_pos);
  12421. if (host_suffix == suffix) { return true; }
  12422. }
  12423. }
  12424. return false;
  12425. }
  12426. } // namespace
  12427. // Check if a string is an IPv4 address
  12428. inline bool is_ipv4_address(const std::string &str) {
  12429. int dots = 0;
  12430. for (char c : str) {
  12431. if (c == '.') {
  12432. dots++;
  12433. } else if (!isdigit(static_cast<unsigned char>(c))) {
  12434. return false;
  12435. }
  12436. }
  12437. return dots == 3;
  12438. }
  12439. // Parse IPv4 address string to bytes
  12440. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  12441. int parts[4];
  12442. if (sscanf(str.c_str(), "%d.%d.%d.%d", &parts[0], &parts[1], &parts[2],
  12443. &parts[3]) != 4) {
  12444. return false;
  12445. }
  12446. for (int i = 0; i < 4; i++) {
  12447. if (parts[i] < 0 || parts[i] > 255) return false;
  12448. out[i] = static_cast<unsigned char>(parts[i]);
  12449. }
  12450. return true;
  12451. }
  12452. inline bool tls_verify_hostname(tls_cert_t cert, const char *hostname) {
  12453. if (!cert || !hostname) { return false; }
  12454. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  12455. std::string host_str(hostname);
  12456. // Check if hostname is an IP address
  12457. bool is_ip = is_ipv4_address(host_str);
  12458. unsigned char ip_bytes[4];
  12459. if (is_ip) { parse_ipv4(host_str, ip_bytes); }
  12460. // Check Subject Alternative Names (SAN)
  12461. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  12462. // - DNS names: raw string bytes
  12463. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  12464. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  12465. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  12466. const unsigned char *p = san->buf.p;
  12467. size_t len = san->buf.len;
  12468. if (is_ip) {
  12469. // Check if this SAN is an IPv4 address (4 bytes)
  12470. if (len == 4 && memcmp(p, ip_bytes, 4) == 0) { return true; }
  12471. // Check if this SAN is an IPv6 address (16 bytes) - skip for now
  12472. } else {
  12473. // Check if this SAN is a DNS name (printable ASCII string)
  12474. bool is_dns = len > 0;
  12475. for (size_t i = 0; i < len && is_dns; i++) {
  12476. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  12477. }
  12478. if (is_dns) {
  12479. std::string san_name(reinterpret_cast<const char *>(p), len);
  12480. if (match_hostname(san_name, host_str)) { return true; }
  12481. }
  12482. }
  12483. san = san->next;
  12484. }
  12485. // Fallback: Check Common Name (CN) in subject
  12486. char cn[256];
  12487. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  12488. if (ret > 0) {
  12489. std::string cn_str(cn);
  12490. // Look for "CN=" in the DN string
  12491. size_t cn_pos = cn_str.find("CN=");
  12492. if (cn_pos != std::string::npos) {
  12493. size_t start = cn_pos + 3;
  12494. size_t end = cn_str.find(',', start);
  12495. std::string cn_value =
  12496. cn_str.substr(start, end == std::string::npos ? end : end - start);
  12497. if (match_hostname(cn_value, host_str)) { return true; }
  12498. }
  12499. }
  12500. return false;
  12501. }
  12502. inline long tls_get_verify_result(tls_session_t session) {
  12503. if (!session) { return -1; }
  12504. auto msession = static_cast<MbedTlsSession *>(session);
  12505. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  12506. // Return 0 (X509_V_OK equivalent) if verification passed
  12507. return flags == 0 ? 0 : static_cast<long>(flags);
  12508. }
  12509. inline std::string tls_get_cert_subject_cn(tls_cert_t cert) {
  12510. if (!cert) return "";
  12511. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12512. // Find the CN in the subject
  12513. const mbedtls_x509_name *name = &x509->subject;
  12514. while (name != nullptr) {
  12515. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  12516. return std::string(reinterpret_cast<const char *>(name->val.p),
  12517. name->val.len);
  12518. }
  12519. name = name->next;
  12520. }
  12521. return "";
  12522. }
  12523. inline std::string tls_get_cert_issuer_name(tls_cert_t cert) {
  12524. if (!cert) return "";
  12525. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12526. // Build a human-readable issuer name string
  12527. char buf[512];
  12528. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  12529. if (ret < 0) return "";
  12530. return std::string(buf);
  12531. }
  12532. inline bool tls_get_cert_sans(tls_cert_t cert, std::vector<TlsSanEntry> &sans) {
  12533. sans.clear();
  12534. if (!cert) return false;
  12535. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12536. // Parse the Subject Alternative Name extension
  12537. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  12538. while (cur != nullptr) {
  12539. if (cur->buf.len > 0) {
  12540. // Mbed TLS stores SAN as ASN.1 sequences
  12541. // The tag byte indicates the type
  12542. const unsigned char *p = cur->buf.p;
  12543. size_t len = cur->buf.len;
  12544. // First byte is the tag
  12545. unsigned char tag = *p;
  12546. p++;
  12547. len--;
  12548. // Parse length (simple single-byte length assumed)
  12549. if (len > 0 && *p < 0x80) {
  12550. size_t value_len = *p;
  12551. p++;
  12552. len--;
  12553. if (value_len <= len) {
  12554. TlsSanEntry entry;
  12555. // ASN.1 context tags for GeneralName
  12556. switch (tag & 0x1F) {
  12557. case 2: // dNSName
  12558. entry.type = SanType::DNS;
  12559. entry.value =
  12560. std::string(reinterpret_cast<const char *>(p), value_len);
  12561. break;
  12562. case 7: // iPAddress
  12563. entry.type = SanType::IP;
  12564. if (value_len == 4) {
  12565. // IPv4
  12566. char buf[16];
  12567. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  12568. entry.value = buf;
  12569. } else if (value_len == 16) {
  12570. // IPv6
  12571. char buf[64];
  12572. snprintf(buf, sizeof(buf),
  12573. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  12574. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  12575. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  12576. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  12577. entry.value = buf;
  12578. }
  12579. break;
  12580. case 1: // rfc822Name (email)
  12581. entry.type = SanType::EMAIL;
  12582. entry.value =
  12583. std::string(reinterpret_cast<const char *>(p), value_len);
  12584. break;
  12585. case 6: // uniformResourceIdentifier
  12586. entry.type = SanType::URI;
  12587. entry.value =
  12588. std::string(reinterpret_cast<const char *>(p), value_len);
  12589. break;
  12590. default: entry.type = SanType::OTHER; break;
  12591. }
  12592. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  12593. }
  12594. }
  12595. }
  12596. cur = cur->next;
  12597. }
  12598. return true;
  12599. }
  12600. inline bool tls_get_cert_validity(tls_cert_t cert, time_t &not_before,
  12601. time_t &not_after) {
  12602. if (!cert) return false;
  12603. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12604. // Convert mbedtls_x509_time to time_t
  12605. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  12606. struct tm tm_time = {};
  12607. tm_time.tm_year = t.year - 1900;
  12608. tm_time.tm_mon = t.mon - 1;
  12609. tm_time.tm_mday = t.day;
  12610. tm_time.tm_hour = t.hour;
  12611. tm_time.tm_min = t.min;
  12612. tm_time.tm_sec = t.sec;
  12613. #ifdef _WIN32
  12614. return _mkgmtime(&tm_time);
  12615. #else
  12616. return timegm(&tm_time);
  12617. #endif
  12618. };
  12619. not_before = to_time_t(x509->valid_from);
  12620. not_after = to_time_t(x509->valid_to);
  12621. return true;
  12622. }
  12623. inline std::string tls_get_cert_serial(tls_cert_t cert) {
  12624. if (!cert) return "";
  12625. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12626. // Convert serial number to hex string
  12627. std::string result;
  12628. result.reserve(x509->serial.len * 2);
  12629. for (size_t i = 0; i < x509->serial.len; i++) {
  12630. char hex[3];
  12631. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  12632. result += hex;
  12633. }
  12634. return result;
  12635. }
  12636. inline const char *tls_get_sni(tls_session_t session) {
  12637. if (!session) return nullptr;
  12638. auto msession = static_cast<MbedTlsSession *>(session);
  12639. // For server: return SNI received from client during handshake
  12640. if (!msession->sni_hostname.empty()) {
  12641. return msession->sni_hostname.c_str();
  12642. }
  12643. // For client: return the hostname set via tls_set_sni
  12644. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  12645. return nullptr;
  12646. }
  12647. inline uint64_t tls_peek_error() {
  12648. // Mbed TLS doesn't have an error queue, return the last error
  12649. return static_cast<uint64_t>(-mbedtls_last_error());
  12650. }
  12651. inline uint64_t tls_get_error() {
  12652. // Mbed TLS doesn't have an error queue, return and clear the last error
  12653. uint64_t err = static_cast<uint64_t>(-mbedtls_last_error());
  12654. mbedtls_last_error() = 0;
  12655. return err;
  12656. }
  12657. inline std::string tls_error_string(uint64_t code) {
  12658. char buf[256];
  12659. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  12660. return std::string(buf);
  12661. }
  12662. inline tls_ca_store_t tls_create_ca_store(const char *pem, size_t len) {
  12663. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  12664. if (!ca_chain) { return nullptr; }
  12665. mbedtls_x509_crt_init(ca_chain);
  12666. // mbedtls_x509_crt_parse expects null-terminated PEM
  12667. int ret = mbedtls_x509_crt_parse(ca_chain,
  12668. reinterpret_cast<const unsigned char *>(pem),
  12669. len + 1); // +1 for null terminator
  12670. if (ret != 0) {
  12671. // Try without +1 in case PEM is already null-terminated
  12672. ret = mbedtls_x509_crt_parse(
  12673. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  12674. if (ret != 0) {
  12675. mbedtls_x509_crt_free(ca_chain);
  12676. delete ca_chain;
  12677. return nullptr;
  12678. }
  12679. }
  12680. return static_cast<tls_ca_store_t>(ca_chain);
  12681. }
  12682. inline void tls_free_ca_store(tls_ca_store_t store) {
  12683. if (store) {
  12684. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  12685. mbedtls_x509_crt_free(ca_chain);
  12686. delete ca_chain;
  12687. }
  12688. }
  12689. inline bool tls_set_ca_store(tls_ctx_t ctx, tls_ca_store_t store) {
  12690. if (!ctx || !store) { return false; }
  12691. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  12692. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  12693. // Free existing CA chain
  12694. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  12695. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  12696. // Copy the CA chain (deep copy)
  12697. // Parse from the raw data of the source cert
  12698. mbedtls_x509_crt *src = ca_chain;
  12699. while (src != nullptr) {
  12700. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  12701. src->raw.len);
  12702. if (ret != 0) { return false; }
  12703. src = src->next;
  12704. }
  12705. // Update the SSL config to use the new CA chain
  12706. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  12707. return true;
  12708. }
  12709. inline size_t tls_get_ca_certs(tls_ctx_t ctx, std::vector<tls_cert_t> &certs) {
  12710. certs.clear();
  12711. if (!ctx) { return 0; }
  12712. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  12713. // Iterate through the CA chain
  12714. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  12715. while (cert != nullptr && cert->raw.len > 0) {
  12716. // Create a copy of the certificate for the caller
  12717. auto *copy = new mbedtls_x509_crt;
  12718. mbedtls_x509_crt_init(copy);
  12719. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  12720. if (ret == 0) {
  12721. certs.push_back(static_cast<tls_cert_t>(copy));
  12722. } else {
  12723. mbedtls_x509_crt_free(copy);
  12724. delete copy;
  12725. }
  12726. cert = cert->next;
  12727. }
  12728. return certs.size();
  12729. }
  12730. inline std::vector<std::string> tls_get_ca_names(tls_ctx_t ctx) {
  12731. std::vector<std::string> names;
  12732. if (!ctx) { return names; }
  12733. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  12734. // Iterate through the CA chain
  12735. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  12736. while (cert != nullptr && cert->raw.len > 0) {
  12737. char buf[512];
  12738. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  12739. if (ret > 0) { names.push_back(buf); }
  12740. cert = cert->next;
  12741. }
  12742. return names;
  12743. }
  12744. inline bool tls_update_server_cert(tls_ctx_t ctx, const char *cert_pem,
  12745. const char *key_pem, const char *password) {
  12746. if (!ctx || !cert_pem || !key_pem) { return false; }
  12747. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  12748. // Free existing certificate and key
  12749. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  12750. mbedtls_pk_free(&mbed_ctx->own_key);
  12751. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  12752. mbedtls_pk_init(&mbed_ctx->own_key);
  12753. // Parse certificate PEM
  12754. int ret = mbedtls_x509_crt_parse(
  12755. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  12756. strlen(cert_pem) + 1);
  12757. if (ret != 0) {
  12758. mbedtls_last_error() = ret;
  12759. return false;
  12760. }
  12761. // Parse private key PEM
  12762. #if MBEDTLS_VERSION_MAJOR >= 3
  12763. ret = mbedtls_pk_parse_key(
  12764. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  12765. strlen(key_pem) + 1,
  12766. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  12767. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  12768. &mbed_ctx->ctr_drbg);
  12769. #else
  12770. ret = mbedtls_pk_parse_key(
  12771. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  12772. strlen(key_pem) + 1,
  12773. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  12774. password ? strlen(password) : 0);
  12775. #endif
  12776. if (ret != 0) {
  12777. mbedtls_last_error() = ret;
  12778. return false;
  12779. }
  12780. // Configure SSL to use the new certificate and key
  12781. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  12782. &mbed_ctx->own_key);
  12783. if (ret != 0) {
  12784. mbedtls_last_error() = ret;
  12785. return false;
  12786. }
  12787. return true;
  12788. }
  12789. inline bool tls_update_server_client_ca(tls_ctx_t ctx, const char *ca_pem) {
  12790. if (!ctx || !ca_pem) { return false; }
  12791. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  12792. // Free existing CA chain
  12793. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  12794. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  12795. // Parse CA PEM
  12796. int ret = mbedtls_x509_crt_parse(
  12797. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  12798. strlen(ca_pem) + 1);
  12799. if (ret != 0) {
  12800. mbedtls_last_error() = ret;
  12801. return false;
  12802. }
  12803. // Update SSL config to use new CA chain
  12804. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  12805. return true;
  12806. }
  12807. // Thread-local storage for verify callback (MbedTLS)
  12808. inline TlsVerifyCallback &get_mbedtls_verify_callback() {
  12809. static thread_local TlsVerifyCallback callback;
  12810. return callback;
  12811. }
  12812. // MbedTLS verify callback wrapper
  12813. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt, int depth,
  12814. uint32_t *flags) {
  12815. (void)depth;
  12816. auto &callback = get_mbedtls_verify_callback();
  12817. if (!callback) { return 0; } // Continue with default verification
  12818. // data points to the MbedTlsSession
  12819. auto *session = static_cast<MbedTlsSession *>(data);
  12820. // Call user callback
  12821. bool accepted = callback(static_cast<tls_session_t>(session),
  12822. static_cast<tls_cert_t>(crt));
  12823. if (accepted) {
  12824. *flags = 0; // Clear all error flags
  12825. return 0;
  12826. }
  12827. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  12828. }
  12829. inline bool tls_set_verify_callback(tls_ctx_t ctx, TlsVerifyCallback callback) {
  12830. if (!ctx) { return false; }
  12831. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  12832. get_mbedtls_verify_callback() = std::move(callback);
  12833. mbed_ctx->has_verify_callback =
  12834. static_cast<bool>(get_mbedtls_verify_callback());
  12835. if (mbed_ctx->has_verify_callback) {
  12836. // Set OPTIONAL mode to ensure callback is called even when verification
  12837. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  12838. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  12839. mbedtls_ssl_conf_verify(&mbed_ctx->conf, mbedtls_verify_callback, nullptr);
  12840. } else {
  12841. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  12842. }
  12843. return true;
  12844. }
  12845. // Thread-local storage for extended verify callback
  12846. inline TlsVerifyCallbackEx &get_mbedtls_verify_callback_ex() {
  12847. static thread_local TlsVerifyCallbackEx callback;
  12848. return callback;
  12849. }
  12850. // Thread-local for depth tracking (Mbed TLS doesn't provide depth directly)
  12851. inline int &get_mbedtls_verify_depth() {
  12852. static thread_local int depth = 0;
  12853. return depth;
  12854. }
  12855. // Mbed TLS extended verify callback wrapper
  12856. inline int mbedtls_verify_callback_ex(void *data, mbedtls_x509_crt *crt,
  12857. int cert_depth, uint32_t *flags) {
  12858. auto &callback = get_mbedtls_verify_callback_ex();
  12859. if (!callback) { return 0; }
  12860. auto *session = static_cast<MbedTlsSession *>(data);
  12861. // Build context
  12862. TlsVerifyContext verify_ctx;
  12863. verify_ctx.session = static_cast<tls_session_t>(session);
  12864. verify_ctx.cert = static_cast<tls_cert_t>(crt);
  12865. verify_ctx.depth = cert_depth;
  12866. verify_ctx.preverify_ok = (*flags == 0);
  12867. verify_ctx.error_code = static_cast<long>(*flags);
  12868. // Convert Mbed TLS flags to error string
  12869. static thread_local char error_buf[256];
  12870. if (*flags != 0) {
  12871. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  12872. verify_ctx.error_string = error_buf;
  12873. } else {
  12874. verify_ctx.error_string = nullptr;
  12875. }
  12876. bool accepted = callback(verify_ctx);
  12877. if (accepted) {
  12878. *flags = 0;
  12879. return 0;
  12880. }
  12881. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  12882. }
  12883. inline bool tls_set_verify_callback_ex(tls_ctx_t ctx,
  12884. TlsVerifyCallbackEx callback) {
  12885. if (!ctx) { return false; }
  12886. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  12887. get_mbedtls_verify_callback_ex() = std::move(callback);
  12888. mbed_ctx->has_verify_callback =
  12889. static_cast<bool>(get_mbedtls_verify_callback_ex());
  12890. if (mbed_ctx->has_verify_callback) {
  12891. // Set OPTIONAL mode to ensure callback is called even when verification
  12892. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  12893. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  12894. mbedtls_ssl_conf_verify(&mbed_ctx->conf, mbedtls_verify_callback_ex,
  12895. nullptr);
  12896. } else {
  12897. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  12898. }
  12899. return true;
  12900. }
  12901. inline long tls_get_verify_error(tls_session_t session) {
  12902. if (!session) { return -1; }
  12903. auto *msession = static_cast<MbedTlsSession *>(session);
  12904. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  12905. }
  12906. inline std::string tls_verify_error_string(long error_code) {
  12907. if (error_code == 0) { return ""; }
  12908. char buf[256];
  12909. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  12910. static_cast<uint32_t>(error_code));
  12911. // Remove trailing newline if present
  12912. std::string result(buf);
  12913. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  12914. result.pop_back();
  12915. }
  12916. return result;
  12917. }
  12918. } // namespace tls
  12919. } // namespace detail
  12920. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  12921. // ClientConnection destructor (defined here because tls namespace
  12922. // is now available)
  12923. inline ClientConnection::~ClientConnection() {
  12924. #ifdef CPPHTTPLIB_SSL_ENABLED
  12925. if (session) {
  12926. detail::tls::tls_shutdown(session, true);
  12927. detail::tls::tls_free_session(session);
  12928. session = nullptr;
  12929. }
  12930. #endif
  12931. if (sock != INVALID_SOCKET) {
  12932. detail::close_socket(sock);
  12933. sock = INVALID_SOCKET;
  12934. }
  12935. }
  12936. /*
  12937. * SSL Implementation
  12938. */
  12939. #ifdef CPPHTTPLIB_SSL_ENABLED
  12940. namespace detail {
  12941. inline bool is_ip_address(const std::string &host) {
  12942. struct in_addr addr4;
  12943. struct in6_addr addr6;
  12944. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  12945. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  12946. }
  12947. template <typename T>
  12948. inline bool process_server_socket_ssl(
  12949. const std::atomic<socket_t> &svr_sock, tls::tls_session_t session,
  12950. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  12951. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  12952. time_t write_timeout_usec, T callback) {
  12953. return process_server_socket_core(
  12954. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  12955. [&](bool close_connection, bool &connection_closed) {
  12956. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  12957. write_timeout_sec, write_timeout_usec);
  12958. return callback(strm, close_connection, connection_closed);
  12959. });
  12960. }
  12961. template <typename T>
  12962. inline bool process_client_socket_ssl(
  12963. tls::tls_session_t session, socket_t sock, time_t read_timeout_sec,
  12964. time_t read_timeout_usec, time_t write_timeout_sec,
  12965. time_t write_timeout_usec, time_t max_timeout_msec,
  12966. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  12967. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  12968. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  12969. start_time);
  12970. return callback(strm);
  12971. }
  12972. // SSL socket stream implementation
  12973. inline SSLSocketStream::SSLSocketStream(
  12974. socket_t sock, tls::tls_session_t session, time_t read_timeout_sec,
  12975. time_t read_timeout_usec, time_t write_timeout_sec,
  12976. time_t write_timeout_usec, time_t max_timeout_msec,
  12977. std::chrono::time_point<std::chrono::steady_clock> start_time)
  12978. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  12979. read_timeout_usec_(read_timeout_usec),
  12980. write_timeout_sec_(write_timeout_sec),
  12981. write_timeout_usec_(write_timeout_usec),
  12982. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  12983. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12984. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  12985. // Note: tls_create_session() also clears this, but SSLClient currently
  12986. // uses ssl_new() which does not. Until full TLS API migration is complete,
  12987. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  12988. // SSL session was created.
  12989. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  12990. #endif
  12991. }
  12992. inline SSLSocketStream::~SSLSocketStream() = default;
  12993. inline bool SSLSocketStream::is_readable() const {
  12994. return tls::tls_pending(session_) > 0;
  12995. }
  12996. inline bool SSLSocketStream::wait_readable() const {
  12997. if (max_timeout_msec_ <= 0) {
  12998. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  12999. }
  13000. time_t read_timeout_sec;
  13001. time_t read_timeout_usec;
  13002. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  13003. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  13004. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  13005. }
  13006. inline bool SSLSocketStream::wait_writable() const {
  13007. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  13008. is_socket_alive(sock_) && !tls::tls_is_peer_closed(session_, sock_);
  13009. }
  13010. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  13011. if (tls::tls_pending(session_) > 0) {
  13012. tls::TlsError err;
  13013. auto ret = tls::tls_read(session_, ptr, size, err);
  13014. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  13015. error_ = Error::ConnectionClosed;
  13016. }
  13017. return ret;
  13018. } else if (wait_readable()) {
  13019. tls::TlsError err;
  13020. auto ret = tls::tls_read(session_, ptr, size, err);
  13021. if (ret < 0) {
  13022. auto n = 1000;
  13023. #ifdef _WIN32
  13024. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  13025. (err.code == tls::ErrorCode::SyscallError &&
  13026. WSAGetLastError() == WSAETIMEDOUT))) {
  13027. #else
  13028. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  13029. #endif
  13030. if (tls::tls_pending(session_) > 0) {
  13031. return tls::tls_read(session_, ptr, size, err);
  13032. } else if (wait_readable()) {
  13033. std::this_thread::sleep_for(std::chrono::microseconds{10});
  13034. ret = tls::tls_read(session_, ptr, size, err);
  13035. if (ret >= 0) { return ret; }
  13036. } else {
  13037. break;
  13038. }
  13039. }
  13040. assert(ret < 0);
  13041. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  13042. error_ = Error::ConnectionClosed;
  13043. }
  13044. return ret;
  13045. } else {
  13046. error_ = Error::Timeout;
  13047. return -1;
  13048. }
  13049. }
  13050. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  13051. if (wait_writable()) {
  13052. auto handle_size =
  13053. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  13054. tls::TlsError err;
  13055. auto ret = tls::tls_write(session_, ptr, handle_size, err);
  13056. if (ret < 0) {
  13057. auto n = 1000;
  13058. #ifdef _WIN32
  13059. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  13060. (err.code == tls::ErrorCode::SyscallError &&
  13061. WSAGetLastError() == WSAETIMEDOUT))) {
  13062. #else
  13063. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  13064. #endif
  13065. if (wait_writable()) {
  13066. std::this_thread::sleep_for(std::chrono::microseconds{10});
  13067. ret = tls::tls_write(session_, ptr, handle_size, err);
  13068. if (ret >= 0) { return ret; }
  13069. } else {
  13070. break;
  13071. }
  13072. }
  13073. assert(ret < 0);
  13074. }
  13075. return ret;
  13076. }
  13077. return -1;
  13078. }
  13079. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  13080. int &port) const {
  13081. detail::get_remote_ip_and_port(sock_, ip, port);
  13082. }
  13083. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  13084. int &port) const {
  13085. detail::get_local_ip_and_port(sock_, ip, port);
  13086. }
  13087. inline socket_t SSLSocketStream::socket() const { return sock_; }
  13088. inline time_t SSLSocketStream::duration() const {
  13089. return std::chrono::duration_cast<std::chrono::milliseconds>(
  13090. std::chrono::steady_clock::now() - start_time_)
  13091. .count();
  13092. }
  13093. } // namespace detail
  13094. #ifdef CPPHTTPLIB_SSL_ENABLED
  13095. // SSL HTTP server implementation (common for OpenSSL and Mbed TLS)
  13096. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13097. const char *client_ca_cert_file_path,
  13098. const char *client_ca_cert_dir_path,
  13099. const char *private_key_password) {
  13100. using namespace detail::tls;
  13101. ctx_ = tls_create_server_context();
  13102. if (!ctx_) { return; }
  13103. // Load server certificate and private key
  13104. if (!tls_set_server_cert_file(ctx_, cert_path, private_key_path,
  13105. private_key_password)) {
  13106. last_ssl_error_ = static_cast<int>(tls_get_error());
  13107. tls_free_context(ctx_);
  13108. ctx_ = nullptr;
  13109. return;
  13110. }
  13111. // Load client CA certificates for client authentication
  13112. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13113. if (!tls_set_client_ca_file(ctx_, client_ca_cert_file_path,
  13114. client_ca_cert_dir_path)) {
  13115. last_ssl_error_ = static_cast<int>(tls_get_error());
  13116. tls_free_context(ctx_);
  13117. ctx_ = nullptr;
  13118. return;
  13119. }
  13120. // Enable client certificate verification
  13121. tls_set_verify_client(ctx_, true);
  13122. }
  13123. }
  13124. inline SSLServer::SSLServer(const PemMemory &pem) {
  13125. using namespace detail::tls;
  13126. ctx_ = tls_create_server_context();
  13127. if (ctx_) {
  13128. if (!tls_set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13129. pem.private_key_password)) {
  13130. last_ssl_error_ = static_cast<int>(tls_get_error());
  13131. tls_free_context(ctx_);
  13132. ctx_ = nullptr;
  13133. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13134. if (!tls_load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13135. last_ssl_error_ = static_cast<int>(tls_get_error());
  13136. tls_free_context(ctx_);
  13137. ctx_ = nullptr;
  13138. } else {
  13139. tls_set_verify_client(ctx_, true);
  13140. }
  13141. }
  13142. }
  13143. }
  13144. inline SSLServer::SSLServer(
  13145. const std::function<bool(void *ctx)> &setup_callback) {
  13146. using namespace detail::tls;
  13147. ctx_ = tls_create_server_context();
  13148. if (ctx_) {
  13149. if (!setup_callback(ctx_)) {
  13150. tls_free_context(ctx_);
  13151. ctx_ = nullptr;
  13152. }
  13153. }
  13154. }
  13155. inline SSLServer::~SSLServer() {
  13156. if (ctx_) { detail::tls::tls_free_context(ctx_); }
  13157. }
  13158. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13159. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13160. using namespace detail::tls;
  13161. // Create TLS session with mutex protection
  13162. tls_session_t session = nullptr;
  13163. {
  13164. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13165. session = tls_create_session(static_cast<tls_ctx_t>(ctx_), sock);
  13166. }
  13167. if (!session) {
  13168. last_ssl_error_ = static_cast<int>(tls_get_error());
  13169. detail::shutdown_socket(sock);
  13170. detail::close_socket(sock);
  13171. return false;
  13172. }
  13173. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13174. bool handshake_done = false;
  13175. bool ret = false;
  13176. auto cleanup = detail::scope_exit([&] {
  13177. // Shutdown gracefully if handshake succeeded and processing was successful
  13178. if (handshake_done) { tls_shutdown(session, ret); }
  13179. tls_free_session(session);
  13180. detail::shutdown_socket(sock);
  13181. detail::close_socket(sock);
  13182. });
  13183. // Perform TLS accept handshake with timeout
  13184. TlsError tls_err;
  13185. if (!tls_accept_nonblocking(session, sock, read_timeout_sec_,
  13186. read_timeout_usec_, &tls_err)) {
  13187. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13188. // Map TlsError to legacy ssl_error for backward compatibility
  13189. if (tls_err.code == ErrorCode::WantRead) {
  13190. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13191. } else if (tls_err.code == ErrorCode::WantWrite) {
  13192. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13193. } else {
  13194. last_ssl_error_ = SSL_ERROR_SSL;
  13195. }
  13196. #else
  13197. last_ssl_error_ = static_cast<int>(tls_get_error());
  13198. #endif
  13199. return false;
  13200. }
  13201. handshake_done = true;
  13202. std::string remote_addr;
  13203. int remote_port = 0;
  13204. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13205. std::string local_addr;
  13206. int local_port = 0;
  13207. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13208. ret = detail::process_server_socket_ssl(
  13209. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13210. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13211. write_timeout_usec_,
  13212. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13213. return process_request(strm, remote_addr, remote_port, local_addr,
  13214. local_port, close_connection, connection_closed,
  13215. [&](Request &req) { req.ssl = session; });
  13216. });
  13217. return ret;
  13218. }
  13219. inline SSLClient::~SSLClient() {
  13220. if (ctx_) { detail::tls::tls_free_context(ctx_); }
  13221. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13222. // base function rather than the derived function once we get to the
  13223. // base class destructor, and won't free the SSL (causing a leak).
  13224. shutdown_ssl_impl(socket_, true);
  13225. }
  13226. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13227. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13228. shutdown_ssl_impl(socket, shutdown_gracefully);
  13229. }
  13230. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13231. bool shutdown_gracefully) {
  13232. if (socket.sock == INVALID_SOCKET) {
  13233. assert(socket.ssl == nullptr);
  13234. return;
  13235. }
  13236. if (socket.ssl) {
  13237. detail::tls::tls_shutdown(socket.ssl, shutdown_gracefully);
  13238. {
  13239. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13240. detail::tls::tls_free_session(socket.ssl);
  13241. }
  13242. socket.ssl = nullptr;
  13243. }
  13244. assert(socket.ssl == nullptr);
  13245. }
  13246. inline bool SSLClient::process_socket(
  13247. const Socket &socket,
  13248. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13249. std::function<bool(Stream &strm)> callback) {
  13250. assert(socket.ssl);
  13251. return detail::process_client_socket_ssl(
  13252. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13253. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13254. std::move(callback));
  13255. }
  13256. inline bool SSLClient::is_ssl() const { return true; }
  13257. inline bool SSLClient::check_host_name(const char *pattern,
  13258. size_t pattern_len) const {
  13259. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  13260. // Wildcard match
  13261. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  13262. std::vector<std::string> pattern_components;
  13263. detail::split(&pattern[0], &pattern[pattern_len], '.',
  13264. [&](const char *b, const char *e) {
  13265. pattern_components.emplace_back(b, e);
  13266. });
  13267. if (host_components_.size() != pattern_components.size()) { return false; }
  13268. auto itr = pattern_components.begin();
  13269. for (const auto &h : host_components_) {
  13270. auto &p = *itr;
  13271. if (p != h && p != "*") {
  13272. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  13273. !p.compare(0, p.size() - 1, h));
  13274. if (!partial_match) { return false; }
  13275. }
  13276. ++itr;
  13277. }
  13278. return true;
  13279. }
  13280. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13281. if (!is_valid()) {
  13282. error = Error::SSLConnection;
  13283. return false;
  13284. }
  13285. return ClientImpl::create_and_connect_socket(socket, error);
  13286. }
  13287. // Assumes that socket_mutex_ is locked and that there are no requests in
  13288. // flight
  13289. inline bool SSLClient::connect_with_proxy(
  13290. Socket &socket,
  13291. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13292. Response &res, bool &success, Error &error) {
  13293. success = true;
  13294. Response proxy_res;
  13295. if (!detail::process_client_socket(
  13296. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13297. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13298. start_time, [&](Stream &strm) {
  13299. Request req2;
  13300. req2.method = "CONNECT";
  13301. req2.path =
  13302. detail::make_host_and_port_string_always_port(host_, port_);
  13303. if (max_timeout_msec_ > 0) {
  13304. req2.start_time_ = std::chrono::steady_clock::now();
  13305. }
  13306. return process_request(strm, req2, proxy_res, false, error);
  13307. })) {
  13308. // Thread-safe to close everything because we are assuming there are no
  13309. // requests in flight
  13310. shutdown_ssl(socket, true);
  13311. shutdown_socket(socket);
  13312. close_socket(socket);
  13313. success = false;
  13314. return false;
  13315. }
  13316. #ifdef CPPHTTPLIB_SSL_ENABLED
  13317. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13318. if (!proxy_digest_auth_username_.empty() &&
  13319. !proxy_digest_auth_password_.empty()) {
  13320. std::map<std::string, std::string> auth;
  13321. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13322. // Close the current socket and create a new one for the authenticated
  13323. // request
  13324. shutdown_ssl(socket, true);
  13325. shutdown_socket(socket);
  13326. close_socket(socket);
  13327. // Create a new socket for the authenticated CONNECT request
  13328. if (!ensure_socket_connection(socket, error)) {
  13329. success = false;
  13330. output_error_log(error, nullptr);
  13331. return false;
  13332. }
  13333. proxy_res = Response();
  13334. if (!detail::process_client_socket(
  13335. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13336. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13337. start_time, [&](Stream &strm) {
  13338. Request req3;
  13339. req3.method = "CONNECT";
  13340. req3.path = detail::make_host_and_port_string_always_port(
  13341. host_, port_);
  13342. req3.headers.insert(detail::make_digest_authentication_header(
  13343. req3, auth, 1, detail::random_string(10),
  13344. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13345. true));
  13346. if (max_timeout_msec_ > 0) {
  13347. req3.start_time_ = std::chrono::steady_clock::now();
  13348. }
  13349. return process_request(strm, req3, proxy_res, false, error);
  13350. })) {
  13351. // Thread-safe to close everything because we are assuming there are
  13352. // no requests in flight
  13353. shutdown_ssl(socket, true);
  13354. shutdown_socket(socket);
  13355. close_socket(socket);
  13356. success = false;
  13357. return false;
  13358. }
  13359. }
  13360. }
  13361. }
  13362. #endif
  13363. // If status code is not 200, proxy request is failed.
  13364. // Set error to ProxyConnection and return proxy response
  13365. // as the response of the request
  13366. if (proxy_res.status != StatusCode::OK_200) {
  13367. error = Error::ProxyConnection;
  13368. output_error_log(error, nullptr);
  13369. res = std::move(proxy_res);
  13370. // Thread-safe to close everything because we are assuming there are
  13371. // no requests in flight
  13372. shutdown_ssl(socket, true);
  13373. shutdown_socket(socket);
  13374. close_socket(socket);
  13375. return false;
  13376. }
  13377. return true;
  13378. }
  13379. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13380. const char *key_pem,
  13381. const char *password) {
  13382. if (!ctx_) { return false; }
  13383. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13384. return detail::tls::tls_update_server_cert(ctx_, cert_pem, key_pem, password);
  13385. }
  13386. inline bool SSLServer::update_client_ca_pem(const char *ca_pem) {
  13387. if (!ctx_) { return false; }
  13388. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13389. return detail::tls::tls_update_server_client_ca(ctx_, ca_pem);
  13390. }
  13391. #endif // CPPHTTPLIB_SSL_ENABLED
  13392. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13393. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  13394. X509_STORE *client_ca_cert_store) {
  13395. ctx_ = detail::tls::create_server_context_from_x509(
  13396. cert, private_key, client_ca_cert_store, last_ssl_error_);
  13397. }
  13398. inline SSLServer::SSLServer(
  13399. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  13400. // Use abstract API to create context
  13401. ctx_ = detail::tls::tls_create_server_context();
  13402. if (ctx_) {
  13403. // Pass to OpenSSL-specific callback (ctx_ is SSL_CTX* internally)
  13404. auto ssl_ctx = static_cast<SSL_CTX *>(ctx_);
  13405. if (!setup_ssl_ctx_callback(*ssl_ctx)) {
  13406. detail::tls::tls_free_context(ctx_);
  13407. ctx_ = nullptr;
  13408. }
  13409. }
  13410. }
  13411. inline SSL_CTX *SSLServer::ssl_context() const {
  13412. return static_cast<SSL_CTX *>(ctx_);
  13413. }
  13414. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  13415. X509_STORE *client_ca_cert_store) {
  13416. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13417. detail::tls::update_server_certs_from_x509(ctx_, cert, private_key,
  13418. client_ca_cert_store);
  13419. }
  13420. inline STACK_OF(X509_NAME) * SSLServer::extract_ca_names_from_x509_store(
  13421. X509_STORE *store) {
  13422. if (!store) { return nullptr; }
  13423. auto ca_list = sk_X509_NAME_new_null();
  13424. if (!ca_list) { return nullptr; }
  13425. // Get all objects from the store
  13426. auto objs = X509_STORE_get0_objects(store);
  13427. if (!objs) {
  13428. sk_X509_NAME_free(ca_list);
  13429. return nullptr;
  13430. }
  13431. // Iterate through objects and extract certificate subject names
  13432. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  13433. auto obj = sk_X509_OBJECT_value(objs, i);
  13434. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13435. auto cert = X509_OBJECT_get0_X509(obj);
  13436. if (cert) {
  13437. auto subject = X509_get_subject_name(cert);
  13438. if (subject) {
  13439. auto name_dup = X509_NAME_dup(subject);
  13440. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  13441. }
  13442. }
  13443. }
  13444. }
  13445. // If no names were extracted, free the list and return nullptr
  13446. if (sk_X509_NAME_num(ca_list) == 0) {
  13447. sk_X509_NAME_free(ca_list);
  13448. return nullptr;
  13449. }
  13450. return ca_list;
  13451. }
  13452. // SSL HTTP client implementation
  13453. inline SSLClient::SSLClient(const std::string &host)
  13454. : SSLClient(host, 443, std::string(), std::string()) {}
  13455. inline SSLClient::SSLClient(const std::string &host, int port)
  13456. : SSLClient(host, port, std::string(), std::string()) {}
  13457. inline SSLClient::SSLClient(const std::string &host, int port,
  13458. const std::string &client_cert_path,
  13459. const std::string &client_key_path,
  13460. const std::string &private_key_password)
  13461. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13462. ctx_ = detail::tls::tls_create_client_context();
  13463. // TODO: Add tls_set_min_protocol_version() to TLS abstraction API
  13464. // SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  13465. detail::split(&host_[0], &host_[host_.size()], '.',
  13466. [&](const char *b, const char *e) {
  13467. host_components_.emplace_back(b, e);
  13468. });
  13469. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13470. const char *password =
  13471. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13472. if (!detail::tls::tls_set_client_cert_file(ctx_, client_cert_path.c_str(),
  13473. client_key_path.c_str(),
  13474. password)) {
  13475. last_backend_error_ = ERR_get_error();
  13476. detail::tls::tls_free_context(ctx_);
  13477. ctx_ = nullptr;
  13478. }
  13479. }
  13480. }
  13481. inline SSLClient::SSLClient(const std::string &host, int port,
  13482. X509 *client_cert, EVP_PKEY *client_key,
  13483. const std::string &private_key_password)
  13484. : ClientImpl(host, port) {
  13485. const char *password =
  13486. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13487. ctx_ = detail::tls::create_client_context_from_x509(
  13488. client_cert, client_key, password, last_backend_error_);
  13489. detail::split(&host_[0], &host_[host_.size()], '.',
  13490. [&](const char *b, const char *e) {
  13491. host_components_.emplace_back(b, e);
  13492. });
  13493. }
  13494. inline SSLClient::SSLClient(const std::string &host, int port,
  13495. const PemMemory &pem)
  13496. : ClientImpl(host, port) {
  13497. ctx_ = detail::tls::tls_create_client_context();
  13498. detail::split(&host_[0], &host_[host_.size()], '.',
  13499. [&](const char *b, const char *e) {
  13500. host_components_.emplace_back(b, e);
  13501. });
  13502. if (ctx_ && pem.cert_pem && pem.key_pem) {
  13503. if (!detail::tls::tls_set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13504. pem.private_key_password)) {
  13505. last_backend_error_ = detail::tls::tls_get_error();
  13506. detail::tls::tls_free_context(ctx_);
  13507. ctx_ = nullptr;
  13508. }
  13509. }
  13510. }
  13511. inline void SSLClient::set_ca_cert_store(void *ca_cert_store) {
  13512. if (ca_cert_store && ctx_) {
  13513. // tls_set_ca_store takes ownership of ca_cert_store
  13514. detail::tls::tls_set_ca_store(ctx_, ca_cert_store);
  13515. } else if (ca_cert_store) {
  13516. detail::tls::tls_free_ca_store(ca_cert_store);
  13517. }
  13518. }
  13519. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13520. std::size_t size) {
  13521. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13522. set_ca_cert_store(detail::tls::tls_create_ca_store(ca_cert, size));
  13523. }
  13524. inline void
  13525. SSLClient::set_server_certificate_verifier(TlsVerifyCallback verifier) {
  13526. if (!ctx_) { return; }
  13527. detail::tls::tls_set_verify_callback(
  13528. ctx_, [verifier](detail::tls::tls_session_t session,
  13529. detail::tls::tls_cert_t cert) {
  13530. return verifier(session, cert);
  13531. });
  13532. }
  13533. inline long SSLClient::get_openssl_verify_result() const {
  13534. return verify_result_;
  13535. }
  13536. inline SSL_CTX *SSLClient::ssl_context() const {
  13537. return static_cast<SSL_CTX *>(ctx_);
  13538. }
  13539. inline bool SSLClient::load_certs() {
  13540. auto ret = true;
  13541. std::call_once(initialize_cert_, [&]() {
  13542. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13543. if (!ca_cert_file_path_.empty()) {
  13544. if (!detail::tls::tls_load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  13545. last_backend_error_ = ERR_get_error();
  13546. ret = false;
  13547. }
  13548. } else if (!ca_cert_dir_path_.empty()) {
  13549. if (!detail::tls::tls_load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  13550. last_backend_error_ = ERR_get_error();
  13551. ret = false;
  13552. }
  13553. } else {
  13554. // Load system certificates
  13555. if (!detail::tls::tls_load_system_certs(ctx_)) {
  13556. last_backend_error_ = ERR_get_error();
  13557. // Ignore error and continue - some systems may not have certs
  13558. }
  13559. }
  13560. });
  13561. return ret;
  13562. }
  13563. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13564. using namespace detail::tls;
  13565. // Load CA certificates if server verification is enabled
  13566. if (server_certificate_verification_) {
  13567. if (!load_certs()) {
  13568. error = Error::SSLLoadingCerts;
  13569. output_error_log(error, nullptr);
  13570. return false;
  13571. }
  13572. }
  13573. // Create TLS session (uses ctx_ which has SSL_VERIFY_NONE by default)
  13574. tls_session_t session = nullptr;
  13575. {
  13576. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13577. session = tls_create_session(ctx_, socket.sock);
  13578. }
  13579. if (!session) {
  13580. error = Error::SSLConnection;
  13581. last_backend_error_ = ERR_get_error();
  13582. return false;
  13583. }
  13584. // Use scope_exit to ensure session is freed on error paths
  13585. bool success = false;
  13586. auto session_guard = detail::scope_exit([&] {
  13587. if (!success) { tls_free_session(session); }
  13588. });
  13589. // Set SNI before handshake (only if host is not IP address)
  13590. if (!detail::is_ip_address(host_)) {
  13591. if (!tls_set_sni(session, host_.c_str())) {
  13592. error = Error::SSLConnection;
  13593. last_backend_error_ = ERR_get_error();
  13594. return false;
  13595. }
  13596. }
  13597. // Perform non-blocking TLS handshake with timeout
  13598. TlsError tls_err;
  13599. if (!tls_connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13600. connection_timeout_usec_, &tls_err)) {
  13601. // Map TlsError to legacy ssl_error for backward compatibility
  13602. if (tls_err.code == ErrorCode::WantRead) {
  13603. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13604. } else if (tls_err.code == ErrorCode::WantWrite) {
  13605. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13606. } else {
  13607. last_ssl_error_ = SSL_ERROR_SSL;
  13608. }
  13609. error = Error::SSLConnection;
  13610. output_error_log(error, nullptr);
  13611. return false;
  13612. }
  13613. // Server certificate verification
  13614. if (server_certificate_verification_) {
  13615. // Cast to SSL* for backward compatibility with verifier callback
  13616. auto ssl = static_cast<SSL *>(session);
  13617. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13618. if (server_certificate_verifier_) {
  13619. verification_status = server_certificate_verifier_(ssl);
  13620. }
  13621. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13622. last_backend_error_ = ERR_get_error();
  13623. error = Error::SSLServerVerification;
  13624. output_error_log(error, nullptr);
  13625. return false;
  13626. }
  13627. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  13628. verify_result_ = tls_get_verify_result(session);
  13629. if (verify_result_ != X509_V_OK) {
  13630. last_backend_error_ = static_cast<unsigned long>(verify_result_);
  13631. error = Error::SSLServerVerification;
  13632. output_error_log(error, nullptr);
  13633. return false;
  13634. }
  13635. auto server_cert = tls_get_peer_cert(session);
  13636. if (!server_cert) {
  13637. last_backend_error_ = ERR_get_error();
  13638. error = Error::SSLServerVerification;
  13639. output_error_log(error, nullptr);
  13640. return false;
  13641. }
  13642. auto cert_guard = detail::scope_exit([&] { tls_free_cert(server_cert); });
  13643. if (server_hostname_verification_) {
  13644. // verify_host() expects X509*, so cast from tls_cert_t
  13645. if (!verify_host(static_cast<X509 *>(server_cert))) {
  13646. last_backend_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  13647. error = Error::SSLServerHostnameVerification;
  13648. output_error_log(error, nullptr);
  13649. return false;
  13650. }
  13651. }
  13652. }
  13653. }
  13654. success = true;
  13655. socket.ssl = session;
  13656. return true;
  13657. }
  13658. inline bool SSLClient::verify_host(X509 *server_cert) const {
  13659. /* Quote from RFC2818 section 3.1 "Server Identity"
  13660. If a subjectAltName extension of type dNSName is present, that MUST
  13661. be used as the identity. Otherwise, the (most specific) Common Name
  13662. field in the Subject field of the certificate MUST be used. Although
  13663. the use of the Common Name is existing practice, it is deprecated and
  13664. Certification Authorities are encouraged to use the dNSName instead.
  13665. Matching is performed using the matching rules specified by
  13666. [RFC2459]. If more than one identity of a given type is present in
  13667. the certificate (e.g., more than one dNSName name, a match in any one
  13668. of the set is considered acceptable.) Names may contain the wildcard
  13669. character * which is considered to match any single domain name
  13670. component or component fragment. E.g., *.a.com matches foo.a.com but
  13671. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  13672. In some cases, the URI is specified as an IP address rather than a
  13673. hostname. In this case, the iPAddress subjectAltName must be present
  13674. in the certificate and must exactly match the IP in the URI.
  13675. */
  13676. return verify_host_with_subject_alt_name(server_cert) ||
  13677. verify_host_with_common_name(server_cert);
  13678. }
  13679. inline bool
  13680. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  13681. auto ret = false;
  13682. auto type = GEN_DNS;
  13683. struct in6_addr addr6 = {};
  13684. struct in_addr addr = {};
  13685. size_t addr_len = 0;
  13686. #ifndef __MINGW32__
  13687. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  13688. type = GEN_IPADD;
  13689. addr_len = sizeof(struct in6_addr);
  13690. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  13691. type = GEN_IPADD;
  13692. addr_len = sizeof(struct in_addr);
  13693. }
  13694. #endif
  13695. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  13696. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  13697. if (alt_names) {
  13698. auto dsn_matched = false;
  13699. auto ip_matched = false;
  13700. auto count = sk_GENERAL_NAME_num(alt_names);
  13701. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  13702. auto val = sk_GENERAL_NAME_value(alt_names, i);
  13703. if (!val || val->type != type) { continue; }
  13704. auto name =
  13705. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  13706. if (name == nullptr) { continue; }
  13707. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  13708. switch (type) {
  13709. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  13710. case GEN_IPADD:
  13711. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  13712. ip_matched = true;
  13713. }
  13714. break;
  13715. }
  13716. }
  13717. if (dsn_matched || ip_matched) { ret = true; }
  13718. }
  13719. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  13720. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  13721. return ret;
  13722. }
  13723. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  13724. const auto subject_name = X509_get_subject_name(server_cert);
  13725. if (subject_name != nullptr) {
  13726. char name[BUFSIZ];
  13727. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  13728. name, sizeof(name));
  13729. if (name_len != -1) {
  13730. return check_host_name(name, static_cast<size_t>(name_len));
  13731. }
  13732. }
  13733. return false;
  13734. }
  13735. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  13736. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13737. // SSL HTTP client implementation (Mbed TLS)
  13738. inline SSLClient::SSLClient(const std::string &host)
  13739. : SSLClient(host, 443, std::string(), std::string()) {}
  13740. inline SSLClient::SSLClient(const std::string &host, int port)
  13741. : SSLClient(host, port, std::string(), std::string()) {}
  13742. inline SSLClient::SSLClient(const std::string &host, int port,
  13743. const std::string &client_cert_path,
  13744. const std::string &client_key_path,
  13745. const std::string &private_key_password)
  13746. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13747. using namespace detail::tls;
  13748. ctx_ = tls_create_client_context();
  13749. if (!ctx_) { return; }
  13750. // Set minimum TLS version to 1.2
  13751. tls_set_min_version(ctx_, 0x0303); // TLS 1.2
  13752. detail::split(&host_[0], &host_[host_.size()], '.',
  13753. [&](const char *b, const char *e) {
  13754. host_components_.emplace_back(b, e);
  13755. });
  13756. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13757. const char *password =
  13758. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13759. if (!tls_set_client_cert_file(ctx_, client_cert_path.c_str(),
  13760. client_key_path.c_str(), password)) {
  13761. last_backend_error_ = tls_get_error();
  13762. tls_free_context(ctx_);
  13763. ctx_ = nullptr;
  13764. }
  13765. }
  13766. }
  13767. inline SSLClient::SSLClient(const std::string &host, int port,
  13768. const PemMemory &pem)
  13769. : ClientImpl(host, port) {
  13770. using namespace detail::tls;
  13771. ctx_ = tls_create_client_context();
  13772. if (!ctx_) { return; }
  13773. // Set minimum TLS version to 1.2
  13774. tls_set_min_version(ctx_, 0x0303); // TLS 1.2
  13775. detail::split(&host_[0], &host_[host_.size()], '.',
  13776. [&](const char *b, const char *e) {
  13777. host_components_.emplace_back(b, e);
  13778. });
  13779. if (pem.cert_pem && pem.key_pem) {
  13780. if (!tls_set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13781. pem.private_key_password)) {
  13782. last_backend_error_ = tls_get_error();
  13783. tls_free_context(ctx_);
  13784. ctx_ = nullptr;
  13785. }
  13786. }
  13787. }
  13788. inline void SSLClient::set_ca_cert_store(void *ca_cert_store) {
  13789. if (ca_cert_store && ctx_) {
  13790. // tls_set_ca_store takes ownership of ca_cert_store
  13791. detail::tls::tls_set_ca_store(ctx_, ca_cert_store);
  13792. } else if (ca_cert_store) {
  13793. detail::tls::tls_free_ca_store(ca_cert_store);
  13794. }
  13795. }
  13796. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13797. std::size_t size) {
  13798. if (ctx_ && ca_cert && size > 0) {
  13799. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13800. detail::tls::tls_load_ca_pem(ctx_, ca_cert, size);
  13801. }
  13802. }
  13803. inline void
  13804. SSLClient::set_server_certificate_verifier(TlsVerifyCallback verifier) {
  13805. if (!ctx_) { return; }
  13806. detail::tls::tls_set_verify_callback(
  13807. ctx_, [verifier](detail::tls::tls_session_t session,
  13808. detail::tls::tls_cert_t cert) {
  13809. return verifier(session, cert);
  13810. });
  13811. }
  13812. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13813. using namespace detail::tls;
  13814. // Load system certificates if no CA certs were explicitly set
  13815. if (ca_cert_file_path_.empty() && ca_cert_dir_path_.empty()) {
  13816. tls_load_system_certs(ctx_);
  13817. }
  13818. // Load CA certificates from file/dir if specified
  13819. if (!ca_cert_file_path_.empty()) {
  13820. if (!tls_load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  13821. last_backend_error_ = tls_get_error();
  13822. error = Error::SSLLoadingCerts;
  13823. return false;
  13824. }
  13825. }
  13826. if (!ca_cert_dir_path_.empty()) {
  13827. if (!tls_load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  13828. last_backend_error_ = tls_get_error();
  13829. error = Error::SSLLoadingCerts;
  13830. return false;
  13831. }
  13832. }
  13833. // For IP addresses, we need special handling in mbedTLS:
  13834. // - RFC 6066 prohibits sending IP addresses in SNI
  13835. // - mbedTLS 3.x requires hostname for cert verification (VERIFY_REQUIRED)
  13836. // - Solution: Use VERIFY_OPTIONAL for IP addresses and verify manually
  13837. bool is_ip = detail::is_ip_address(host_);
  13838. if (is_ip && server_certificate_verification_) {
  13839. // Use OPTIONAL mode so mbedTLS doesn't require hostname
  13840. tls_set_verify_client(ctx_, false);
  13841. } else {
  13842. tls_set_verify_client(ctx_, server_certificate_verification_);
  13843. }
  13844. auto session = tls_create_session(ctx_, socket.sock);
  13845. if (!session) {
  13846. last_backend_error_ = tls_get_error();
  13847. error = Error::SSLConnection;
  13848. return false;
  13849. }
  13850. // Use scope_exit to ensure session is freed on error paths
  13851. bool success = false;
  13852. auto session_guard = detail::scope_exit([&] {
  13853. if (!success) { tls_free_session(session); }
  13854. });
  13855. // Set hostname for SNI (only for non-IP addresses per RFC 6066)
  13856. if (!is_ip) {
  13857. if (!tls_set_hostname(session, host_.c_str())) {
  13858. last_backend_error_ = tls_get_error();
  13859. error = Error::SSLConnection;
  13860. return false;
  13861. }
  13862. }
  13863. // Perform TLS handshake
  13864. TlsError tls_err;
  13865. if (!tls_connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13866. connection_timeout_usec_, &tls_err)) {
  13867. last_ssl_error_ = static_cast<int>(tls_err.code);
  13868. last_backend_error_ = tls_err.backend_code;
  13869. // Map TLS error codes to appropriate Error types
  13870. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13871. error = Error::SSLServerVerification;
  13872. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13873. error = Error::SSLServerHostnameVerification;
  13874. } else {
  13875. error = Error::SSLConnection;
  13876. }
  13877. return false;
  13878. }
  13879. // Verify server certificate
  13880. if (server_certificate_verification_) {
  13881. auto verify_result = tls_get_verify_result(session);
  13882. if (verify_result != 0) {
  13883. last_backend_error_ = static_cast<unsigned long>(verify_result);
  13884. error = Error::SSLServerVerification;
  13885. return false;
  13886. }
  13887. auto cert = tls_get_peer_cert(session);
  13888. if (!cert) {
  13889. last_backend_error_ = tls_get_error();
  13890. error = Error::SSLServerVerification;
  13891. return false;
  13892. }
  13893. auto cert_guard = detail::scope_exit([&] { tls_free_cert(cert); });
  13894. if (server_hostname_verification_) {
  13895. if (!tls_verify_hostname(cert, host_.c_str())) {
  13896. // Use a well-known error code for hostname mismatch
  13897. last_backend_error_ = 0x4000A000; // Custom code for hostname mismatch
  13898. error = Error::SSLServerHostnameVerification;
  13899. return false;
  13900. }
  13901. }
  13902. }
  13903. success = true;
  13904. socket.ssl = session;
  13905. return true;
  13906. }
  13907. inline mbedtls_ssl_config *SSLServer::ssl_config() const {
  13908. auto ctx = static_cast<detail::tls::MbedTlsContext *>(ctx_);
  13909. return ctx ? &ctx->conf : nullptr;
  13910. }
  13911. inline SSLServer::SSLServer(
  13912. const std::function<bool(mbedtls_ssl_config &conf)> &setup_callback) {
  13913. using namespace detail::tls;
  13914. ctx_ = tls_create_server_context();
  13915. if (ctx_) {
  13916. auto mbedtls_ctx = static_cast<MbedTlsContext *>(ctx_);
  13917. if (!setup_callback(mbedtls_ctx->conf)) {
  13918. tls_free_context(ctx_);
  13919. ctx_ = nullptr;
  13920. }
  13921. }
  13922. }
  13923. inline mbedtls_ssl_config *SSLClient::ssl_config() const {
  13924. auto ctx = static_cast<detail::tls::MbedTlsContext *>(ctx_);
  13925. return ctx ? &ctx->conf : nullptr;
  13926. }
  13927. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  13928. #endif // CPPHTTPLIB_SSL_ENABLED
  13929. // Universal client implementation
  13930. inline Client::Client(const std::string &scheme_host_port)
  13931. : Client(scheme_host_port, std::string(), std::string()) {}
  13932. inline Client::Client(const std::string &scheme_host_port,
  13933. const std::string &client_cert_path,
  13934. const std::string &client_key_path) {
  13935. const static std::regex re(
  13936. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  13937. std::smatch m;
  13938. if (std::regex_match(scheme_host_port, m, re)) {
  13939. auto scheme = m[1].str();
  13940. #ifdef CPPHTTPLIB_SSL_ENABLED
  13941. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  13942. #else
  13943. if (!scheme.empty() && scheme != "http") {
  13944. #endif
  13945. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13946. std::string msg = "'" + scheme + "' scheme is not supported.";
  13947. throw std::invalid_argument(msg);
  13948. #endif
  13949. return;
  13950. }
  13951. auto is_ssl = scheme == "https";
  13952. auto host = m[2].str();
  13953. if (host.empty()) { host = m[3].str(); }
  13954. auto port_str = m[4].str();
  13955. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  13956. if (is_ssl) {
  13957. #ifdef CPPHTTPLIB_SSL_ENABLED
  13958. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  13959. client_key_path);
  13960. is_ssl_ = is_ssl;
  13961. #endif
  13962. } else {
  13963. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  13964. client_key_path);
  13965. }
  13966. } else {
  13967. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  13968. // if port param below changes.
  13969. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  13970. client_cert_path, client_key_path);
  13971. }
  13972. } // namespace detail
  13973. inline Client::Client(const std::string &host, int port)
  13974. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  13975. inline Client::Client(const std::string &host, int port,
  13976. const std::string &client_cert_path,
  13977. const std::string &client_key_path)
  13978. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  13979. client_key_path)) {}
  13980. inline Client::~Client() = default;
  13981. inline bool Client::is_valid() const {
  13982. return cli_ != nullptr && cli_->is_valid();
  13983. }
  13984. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  13985. return cli_->Get(path, std::move(progress));
  13986. }
  13987. inline Result Client::Get(const std::string &path, const Headers &headers,
  13988. DownloadProgress progress) {
  13989. return cli_->Get(path, headers, std::move(progress));
  13990. }
  13991. inline Result Client::Get(const std::string &path,
  13992. ContentReceiver content_receiver,
  13993. DownloadProgress progress) {
  13994. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  13995. }
  13996. inline Result Client::Get(const std::string &path, const Headers &headers,
  13997. ContentReceiver content_receiver,
  13998. DownloadProgress progress) {
  13999. return cli_->Get(path, headers, std::move(content_receiver),
  14000. std::move(progress));
  14001. }
  14002. inline Result Client::Get(const std::string &path,
  14003. ResponseHandler response_handler,
  14004. ContentReceiver content_receiver,
  14005. DownloadProgress progress) {
  14006. return cli_->Get(path, std::move(response_handler),
  14007. std::move(content_receiver), std::move(progress));
  14008. }
  14009. inline Result Client::Get(const std::string &path, const Headers &headers,
  14010. ResponseHandler response_handler,
  14011. ContentReceiver content_receiver,
  14012. DownloadProgress progress) {
  14013. return cli_->Get(path, headers, std::move(response_handler),
  14014. std::move(content_receiver), std::move(progress));
  14015. }
  14016. inline Result Client::Get(const std::string &path, const Params &params,
  14017. const Headers &headers, DownloadProgress progress) {
  14018. return cli_->Get(path, params, headers, std::move(progress));
  14019. }
  14020. inline Result Client::Get(const std::string &path, const Params &params,
  14021. const Headers &headers,
  14022. ContentReceiver content_receiver,
  14023. DownloadProgress progress) {
  14024. return cli_->Get(path, params, headers, std::move(content_receiver),
  14025. std::move(progress));
  14026. }
  14027. inline Result Client::Get(const std::string &path, const Params &params,
  14028. const Headers &headers,
  14029. ResponseHandler response_handler,
  14030. ContentReceiver content_receiver,
  14031. DownloadProgress progress) {
  14032. return cli_->Get(path, params, headers, std::move(response_handler),
  14033. std::move(content_receiver), std::move(progress));
  14034. }
  14035. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  14036. inline Result Client::Head(const std::string &path, const Headers &headers) {
  14037. return cli_->Head(path, headers);
  14038. }
  14039. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  14040. inline Result Client::Post(const std::string &path, const Headers &headers) {
  14041. return cli_->Post(path, headers);
  14042. }
  14043. inline Result Client::Post(const std::string &path, const char *body,
  14044. size_t content_length,
  14045. const std::string &content_type,
  14046. UploadProgress progress) {
  14047. return cli_->Post(path, body, content_length, content_type, progress);
  14048. }
  14049. inline Result Client::Post(const std::string &path, const Headers &headers,
  14050. const char *body, size_t content_length,
  14051. const std::string &content_type,
  14052. UploadProgress progress) {
  14053. return cli_->Post(path, headers, body, content_length, content_type,
  14054. progress);
  14055. }
  14056. inline Result Client::Post(const std::string &path, const std::string &body,
  14057. const std::string &content_type,
  14058. UploadProgress progress) {
  14059. return cli_->Post(path, body, content_type, progress);
  14060. }
  14061. inline Result Client::Post(const std::string &path, const Headers &headers,
  14062. const std::string &body,
  14063. const std::string &content_type,
  14064. UploadProgress progress) {
  14065. return cli_->Post(path, headers, body, content_type, progress);
  14066. }
  14067. inline Result Client::Post(const std::string &path, size_t content_length,
  14068. ContentProvider content_provider,
  14069. const std::string &content_type,
  14070. UploadProgress progress) {
  14071. return cli_->Post(path, content_length, std::move(content_provider),
  14072. content_type, progress);
  14073. }
  14074. inline Result Client::Post(const std::string &path, size_t content_length,
  14075. ContentProvider content_provider,
  14076. const std::string &content_type,
  14077. ContentReceiver content_receiver,
  14078. UploadProgress progress) {
  14079. return cli_->Post(path, content_length, std::move(content_provider),
  14080. content_type, std::move(content_receiver), progress);
  14081. }
  14082. inline Result Client::Post(const std::string &path,
  14083. ContentProviderWithoutLength content_provider,
  14084. const std::string &content_type,
  14085. UploadProgress progress) {
  14086. return cli_->Post(path, std::move(content_provider), content_type, progress);
  14087. }
  14088. inline Result Client::Post(const std::string &path,
  14089. ContentProviderWithoutLength content_provider,
  14090. const std::string &content_type,
  14091. ContentReceiver content_receiver,
  14092. UploadProgress progress) {
  14093. return cli_->Post(path, std::move(content_provider), content_type,
  14094. std::move(content_receiver), progress);
  14095. }
  14096. inline Result Client::Post(const std::string &path, const Headers &headers,
  14097. size_t content_length,
  14098. ContentProvider content_provider,
  14099. const std::string &content_type,
  14100. UploadProgress progress) {
  14101. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14102. content_type, progress);
  14103. }
  14104. inline Result Client::Post(const std::string &path, const Headers &headers,
  14105. size_t content_length,
  14106. ContentProvider content_provider,
  14107. const std::string &content_type,
  14108. ContentReceiver content_receiver,
  14109. DownloadProgress progress) {
  14110. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14111. content_type, std::move(content_receiver), progress);
  14112. }
  14113. inline Result Client::Post(const std::string &path, const Headers &headers,
  14114. ContentProviderWithoutLength content_provider,
  14115. const std::string &content_type,
  14116. UploadProgress progress) {
  14117. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14118. progress);
  14119. }
  14120. inline Result Client::Post(const std::string &path, const Headers &headers,
  14121. ContentProviderWithoutLength content_provider,
  14122. const std::string &content_type,
  14123. ContentReceiver content_receiver,
  14124. DownloadProgress progress) {
  14125. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14126. std::move(content_receiver), progress);
  14127. }
  14128. inline Result Client::Post(const std::string &path, const Params &params) {
  14129. return cli_->Post(path, params);
  14130. }
  14131. inline Result Client::Post(const std::string &path, const Headers &headers,
  14132. const Params &params) {
  14133. return cli_->Post(path, headers, params);
  14134. }
  14135. inline Result Client::Post(const std::string &path,
  14136. const UploadFormDataItems &items,
  14137. UploadProgress progress) {
  14138. return cli_->Post(path, items, progress);
  14139. }
  14140. inline Result Client::Post(const std::string &path, const Headers &headers,
  14141. const UploadFormDataItems &items,
  14142. UploadProgress progress) {
  14143. return cli_->Post(path, headers, items, progress);
  14144. }
  14145. inline Result Client::Post(const std::string &path, const Headers &headers,
  14146. const UploadFormDataItems &items,
  14147. const std::string &boundary,
  14148. UploadProgress progress) {
  14149. return cli_->Post(path, headers, items, boundary, progress);
  14150. }
  14151. inline Result Client::Post(const std::string &path, const Headers &headers,
  14152. const UploadFormDataItems &items,
  14153. const FormDataProviderItems &provider_items,
  14154. UploadProgress progress) {
  14155. return cli_->Post(path, headers, items, provider_items, progress);
  14156. }
  14157. inline Result Client::Post(const std::string &path, const Headers &headers,
  14158. const std::string &body,
  14159. const std::string &content_type,
  14160. ContentReceiver content_receiver,
  14161. DownloadProgress progress) {
  14162. return cli_->Post(path, headers, body, content_type,
  14163. std::move(content_receiver), progress);
  14164. }
  14165. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  14166. inline Result Client::Put(const std::string &path, const Headers &headers) {
  14167. return cli_->Put(path, headers);
  14168. }
  14169. inline Result Client::Put(const std::string &path, const char *body,
  14170. size_t content_length,
  14171. const std::string &content_type,
  14172. UploadProgress progress) {
  14173. return cli_->Put(path, body, content_length, content_type, progress);
  14174. }
  14175. inline Result Client::Put(const std::string &path, const Headers &headers,
  14176. const char *body, size_t content_length,
  14177. const std::string &content_type,
  14178. UploadProgress progress) {
  14179. return cli_->Put(path, headers, body, content_length, content_type, progress);
  14180. }
  14181. inline Result Client::Put(const std::string &path, const std::string &body,
  14182. const std::string &content_type,
  14183. UploadProgress progress) {
  14184. return cli_->Put(path, body, content_type, progress);
  14185. }
  14186. inline Result Client::Put(const std::string &path, const Headers &headers,
  14187. const std::string &body,
  14188. const std::string &content_type,
  14189. UploadProgress progress) {
  14190. return cli_->Put(path, headers, body, content_type, progress);
  14191. }
  14192. inline Result Client::Put(const std::string &path, size_t content_length,
  14193. ContentProvider content_provider,
  14194. const std::string &content_type,
  14195. UploadProgress progress) {
  14196. return cli_->Put(path, content_length, std::move(content_provider),
  14197. content_type, progress);
  14198. }
  14199. inline Result Client::Put(const std::string &path, size_t content_length,
  14200. ContentProvider content_provider,
  14201. const std::string &content_type,
  14202. ContentReceiver content_receiver,
  14203. UploadProgress progress) {
  14204. return cli_->Put(path, content_length, std::move(content_provider),
  14205. content_type, std::move(content_receiver), progress);
  14206. }
  14207. inline Result Client::Put(const std::string &path,
  14208. ContentProviderWithoutLength content_provider,
  14209. const std::string &content_type,
  14210. UploadProgress progress) {
  14211. return cli_->Put(path, std::move(content_provider), content_type, progress);
  14212. }
  14213. inline Result Client::Put(const std::string &path,
  14214. ContentProviderWithoutLength content_provider,
  14215. const std::string &content_type,
  14216. ContentReceiver content_receiver,
  14217. UploadProgress progress) {
  14218. return cli_->Put(path, std::move(content_provider), content_type,
  14219. std::move(content_receiver), progress);
  14220. }
  14221. inline Result Client::Put(const std::string &path, const Headers &headers,
  14222. size_t content_length,
  14223. ContentProvider content_provider,
  14224. const std::string &content_type,
  14225. UploadProgress progress) {
  14226. return cli_->Put(path, headers, content_length, std::move(content_provider),
  14227. content_type, progress);
  14228. }
  14229. inline Result Client::Put(const std::string &path, const Headers &headers,
  14230. size_t content_length,
  14231. ContentProvider content_provider,
  14232. const std::string &content_type,
  14233. ContentReceiver content_receiver,
  14234. UploadProgress progress) {
  14235. return cli_->Put(path, headers, content_length, std::move(content_provider),
  14236. content_type, std::move(content_receiver), progress);
  14237. }
  14238. inline Result Client::Put(const std::string &path, const Headers &headers,
  14239. ContentProviderWithoutLength content_provider,
  14240. const std::string &content_type,
  14241. UploadProgress progress) {
  14242. return cli_->Put(path, headers, std::move(content_provider), content_type,
  14243. progress);
  14244. }
  14245. inline Result Client::Put(const std::string &path, const Headers &headers,
  14246. ContentProviderWithoutLength content_provider,
  14247. const std::string &content_type,
  14248. ContentReceiver content_receiver,
  14249. UploadProgress progress) {
  14250. return cli_->Put(path, headers, std::move(content_provider), content_type,
  14251. std::move(content_receiver), progress);
  14252. }
  14253. inline Result Client::Put(const std::string &path, const Params &params) {
  14254. return cli_->Put(path, params);
  14255. }
  14256. inline Result Client::Put(const std::string &path, const Headers &headers,
  14257. const Params &params) {
  14258. return cli_->Put(path, headers, params);
  14259. }
  14260. inline Result Client::Put(const std::string &path,
  14261. const UploadFormDataItems &items,
  14262. UploadProgress progress) {
  14263. return cli_->Put(path, items, progress);
  14264. }
  14265. inline Result Client::Put(const std::string &path, const Headers &headers,
  14266. const UploadFormDataItems &items,
  14267. UploadProgress progress) {
  14268. return cli_->Put(path, headers, items, progress);
  14269. }
  14270. inline Result Client::Put(const std::string &path, const Headers &headers,
  14271. const UploadFormDataItems &items,
  14272. const std::string &boundary,
  14273. UploadProgress progress) {
  14274. return cli_->Put(path, headers, items, boundary, progress);
  14275. }
  14276. inline Result Client::Put(const std::string &path, const Headers &headers,
  14277. const UploadFormDataItems &items,
  14278. const FormDataProviderItems &provider_items,
  14279. UploadProgress progress) {
  14280. return cli_->Put(path, headers, items, provider_items, progress);
  14281. }
  14282. inline Result Client::Put(const std::string &path, const Headers &headers,
  14283. const std::string &body,
  14284. const std::string &content_type,
  14285. ContentReceiver content_receiver,
  14286. DownloadProgress progress) {
  14287. return cli_->Put(path, headers, body, content_type, content_receiver,
  14288. progress);
  14289. }
  14290. inline Result Client::Patch(const std::string &path) {
  14291. return cli_->Patch(path);
  14292. }
  14293. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  14294. return cli_->Patch(path, headers);
  14295. }
  14296. inline Result Client::Patch(const std::string &path, const char *body,
  14297. size_t content_length,
  14298. const std::string &content_type,
  14299. UploadProgress progress) {
  14300. return cli_->Patch(path, body, content_length, content_type, progress);
  14301. }
  14302. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14303. const char *body, size_t content_length,
  14304. const std::string &content_type,
  14305. UploadProgress progress) {
  14306. return cli_->Patch(path, headers, body, content_length, content_type,
  14307. progress);
  14308. }
  14309. inline Result Client::Patch(const std::string &path, const std::string &body,
  14310. const std::string &content_type,
  14311. UploadProgress progress) {
  14312. return cli_->Patch(path, body, content_type, progress);
  14313. }
  14314. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14315. const std::string &body,
  14316. const std::string &content_type,
  14317. UploadProgress progress) {
  14318. return cli_->Patch(path, headers, body, content_type, progress);
  14319. }
  14320. inline Result Client::Patch(const std::string &path, size_t content_length,
  14321. ContentProvider content_provider,
  14322. const std::string &content_type,
  14323. UploadProgress progress) {
  14324. return cli_->Patch(path, content_length, std::move(content_provider),
  14325. content_type, progress);
  14326. }
  14327. inline Result Client::Patch(const std::string &path, size_t content_length,
  14328. ContentProvider content_provider,
  14329. const std::string &content_type,
  14330. ContentReceiver content_receiver,
  14331. UploadProgress progress) {
  14332. return cli_->Patch(path, content_length, std::move(content_provider),
  14333. content_type, std::move(content_receiver), progress);
  14334. }
  14335. inline Result Client::Patch(const std::string &path,
  14336. ContentProviderWithoutLength content_provider,
  14337. const std::string &content_type,
  14338. UploadProgress progress) {
  14339. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  14340. }
  14341. inline Result Client::Patch(const std::string &path,
  14342. ContentProviderWithoutLength content_provider,
  14343. const std::string &content_type,
  14344. ContentReceiver content_receiver,
  14345. UploadProgress progress) {
  14346. return cli_->Patch(path, std::move(content_provider), content_type,
  14347. std::move(content_receiver), progress);
  14348. }
  14349. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14350. size_t content_length,
  14351. ContentProvider content_provider,
  14352. const std::string &content_type,
  14353. UploadProgress progress) {
  14354. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  14355. content_type, progress);
  14356. }
  14357. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14358. size_t content_length,
  14359. ContentProvider content_provider,
  14360. const std::string &content_type,
  14361. ContentReceiver content_receiver,
  14362. UploadProgress progress) {
  14363. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  14364. content_type, std::move(content_receiver), progress);
  14365. }
  14366. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14367. ContentProviderWithoutLength content_provider,
  14368. const std::string &content_type,
  14369. UploadProgress progress) {
  14370. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  14371. progress);
  14372. }
  14373. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14374. ContentProviderWithoutLength content_provider,
  14375. const std::string &content_type,
  14376. ContentReceiver content_receiver,
  14377. UploadProgress progress) {
  14378. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  14379. std::move(content_receiver), progress);
  14380. }
  14381. inline Result Client::Patch(const std::string &path, const Params &params) {
  14382. return cli_->Patch(path, params);
  14383. }
  14384. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14385. const Params &params) {
  14386. return cli_->Patch(path, headers, params);
  14387. }
  14388. inline Result Client::Patch(const std::string &path,
  14389. const UploadFormDataItems &items,
  14390. UploadProgress progress) {
  14391. return cli_->Patch(path, items, progress);
  14392. }
  14393. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14394. const UploadFormDataItems &items,
  14395. UploadProgress progress) {
  14396. return cli_->Patch(path, headers, items, progress);
  14397. }
  14398. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14399. const UploadFormDataItems &items,
  14400. const std::string &boundary,
  14401. UploadProgress progress) {
  14402. return cli_->Patch(path, headers, items, boundary, progress);
  14403. }
  14404. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14405. const UploadFormDataItems &items,
  14406. const FormDataProviderItems &provider_items,
  14407. UploadProgress progress) {
  14408. return cli_->Patch(path, headers, items, provider_items, progress);
  14409. }
  14410. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14411. const std::string &body,
  14412. const std::string &content_type,
  14413. ContentReceiver content_receiver,
  14414. DownloadProgress progress) {
  14415. return cli_->Patch(path, headers, body, content_type, content_receiver,
  14416. progress);
  14417. }
  14418. inline Result Client::Delete(const std::string &path,
  14419. DownloadProgress progress) {
  14420. return cli_->Delete(path, progress);
  14421. }
  14422. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14423. DownloadProgress progress) {
  14424. return cli_->Delete(path, headers, progress);
  14425. }
  14426. inline Result Client::Delete(const std::string &path, const char *body,
  14427. size_t content_length,
  14428. const std::string &content_type,
  14429. DownloadProgress progress) {
  14430. return cli_->Delete(path, body, content_length, content_type, progress);
  14431. }
  14432. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14433. const char *body, size_t content_length,
  14434. const std::string &content_type,
  14435. DownloadProgress progress) {
  14436. return cli_->Delete(path, headers, body, content_length, content_type,
  14437. progress);
  14438. }
  14439. inline Result Client::Delete(const std::string &path, const std::string &body,
  14440. const std::string &content_type,
  14441. DownloadProgress progress) {
  14442. return cli_->Delete(path, body, content_type, progress);
  14443. }
  14444. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14445. const std::string &body,
  14446. const std::string &content_type,
  14447. DownloadProgress progress) {
  14448. return cli_->Delete(path, headers, body, content_type, progress);
  14449. }
  14450. inline Result Client::Delete(const std::string &path, const Params &params,
  14451. DownloadProgress progress) {
  14452. return cli_->Delete(path, params, progress);
  14453. }
  14454. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14455. const Params &params, DownloadProgress progress) {
  14456. return cli_->Delete(path, headers, params, progress);
  14457. }
  14458. inline Result Client::Options(const std::string &path) {
  14459. return cli_->Options(path);
  14460. }
  14461. inline Result Client::Options(const std::string &path, const Headers &headers) {
  14462. return cli_->Options(path, headers);
  14463. }
  14464. inline ClientImpl::StreamHandle
  14465. Client::open_stream(const std::string &method, const std::string &path,
  14466. const Params &params, const Headers &headers,
  14467. const std::string &body, const std::string &content_type) {
  14468. return cli_->open_stream(method, path, params, headers, body, content_type);
  14469. }
  14470. inline bool Client::send(Request &req, Response &res, Error &error) {
  14471. return cli_->send(req, res, error);
  14472. }
  14473. inline Result Client::send(const Request &req) { return cli_->send(req); }
  14474. inline void Client::stop() { cli_->stop(); }
  14475. inline std::string Client::host() const { return cli_->host(); }
  14476. inline int Client::port() const { return cli_->port(); }
  14477. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  14478. inline socket_t Client::socket() const { return cli_->socket(); }
  14479. inline void
  14480. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  14481. cli_->set_hostname_addr_map(std::move(addr_map));
  14482. }
  14483. inline void Client::set_default_headers(Headers headers) {
  14484. cli_->set_default_headers(std::move(headers));
  14485. }
  14486. inline void Client::set_header_writer(
  14487. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  14488. cli_->set_header_writer(writer);
  14489. }
  14490. inline void Client::set_address_family(int family) {
  14491. cli_->set_address_family(family);
  14492. }
  14493. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  14494. inline void Client::set_socket_options(SocketOptions socket_options) {
  14495. cli_->set_socket_options(std::move(socket_options));
  14496. }
  14497. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  14498. cli_->set_connection_timeout(sec, usec);
  14499. }
  14500. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  14501. cli_->set_read_timeout(sec, usec);
  14502. }
  14503. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  14504. cli_->set_write_timeout(sec, usec);
  14505. }
  14506. inline void Client::set_basic_auth(const std::string &username,
  14507. const std::string &password) {
  14508. cli_->set_basic_auth(username, password);
  14509. }
  14510. inline void Client::set_bearer_token_auth(const std::string &token) {
  14511. cli_->set_bearer_token_auth(token);
  14512. }
  14513. #ifdef CPPHTTPLIB_SSL_ENABLED
  14514. inline void Client::set_digest_auth(const std::string &username,
  14515. const std::string &password) {
  14516. cli_->set_digest_auth(username, password);
  14517. }
  14518. #endif
  14519. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  14520. inline void Client::set_follow_location(bool on) {
  14521. cli_->set_follow_location(on);
  14522. }
  14523. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  14524. [[deprecated("Use set_path_encode instead")]]
  14525. inline void Client::set_url_encode(bool on) {
  14526. cli_->set_path_encode(on);
  14527. }
  14528. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  14529. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  14530. inline void Client::set_interface(const std::string &intf) {
  14531. cli_->set_interface(intf);
  14532. }
  14533. inline void Client::set_proxy(const std::string &host, int port) {
  14534. cli_->set_proxy(host, port);
  14535. }
  14536. inline void Client::set_proxy_basic_auth(const std::string &username,
  14537. const std::string &password) {
  14538. cli_->set_proxy_basic_auth(username, password);
  14539. }
  14540. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  14541. cli_->set_proxy_bearer_token_auth(token);
  14542. }
  14543. #ifdef CPPHTTPLIB_SSL_ENABLED
  14544. inline void Client::set_proxy_digest_auth(const std::string &username,
  14545. const std::string &password) {
  14546. cli_->set_proxy_digest_auth(username, password);
  14547. }
  14548. inline void Client::enable_server_certificate_verification(bool enabled) {
  14549. cli_->enable_server_certificate_verification(enabled);
  14550. }
  14551. inline void Client::enable_server_hostname_verification(bool enabled) {
  14552. cli_->enable_server_hostname_verification(enabled);
  14553. }
  14554. #endif
  14555. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14556. inline void Client::set_server_certificate_verifier(
  14557. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  14558. cli_->set_server_certificate_verifier(verifier);
  14559. }
  14560. #endif
  14561. inline void Client::set_logger(Logger logger) {
  14562. cli_->set_logger(std::move(logger));
  14563. }
  14564. inline void Client::set_error_logger(ErrorLogger error_logger) {
  14565. cli_->set_error_logger(std::move(error_logger));
  14566. }
  14567. #ifdef CPPHTTPLIB_SSL_ENABLED
  14568. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14569. const std::string &ca_cert_dir_path) {
  14570. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14571. }
  14572. #endif
  14573. #ifdef CPPHTTPLIB_SSL_ENABLED
  14574. inline void Client::set_ca_cert_store(void *ca_cert_store) {
  14575. if (is_ssl_) {
  14576. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14577. } else if (ca_cert_store) {
  14578. detail::tls::tls_free_ca_store(ca_cert_store);
  14579. }
  14580. }
  14581. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14582. set_ca_cert_store(detail::tls::tls_create_ca_store(ca_cert, size));
  14583. }
  14584. inline void
  14585. Client::set_server_certificate_verifier(TlsVerifyCallback verifier) {
  14586. if (is_ssl_) {
  14587. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14588. std::move(verifier));
  14589. }
  14590. }
  14591. inline void *Client::tls_context() const {
  14592. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14593. return nullptr;
  14594. }
  14595. #endif
  14596. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14597. inline long Client::get_openssl_verify_result() const {
  14598. if (is_ssl_) {
  14599. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  14600. }
  14601. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  14602. }
  14603. inline SSL_CTX *Client::ssl_context() const {
  14604. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  14605. return nullptr;
  14606. }
  14607. #endif
  14608. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14609. inline mbedtls_ssl_config *Client::ssl_config() const {
  14610. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_config(); }
  14611. return nullptr;
  14612. }
  14613. #endif
  14614. // ----------------------------------------------------------------------------
  14615. } // namespace httplib
  14616. #endif // CPPHTTPLIB_HTTPLIB_H