httplib.h 572 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266
  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. void set_server_certificate_verifier(
  1443. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1444. #endif
  1445. void set_logger(Logger logger);
  1446. void set_error_logger(ErrorLogger error_logger);
  1447. protected:
  1448. struct Socket {
  1449. socket_t sock = INVALID_SOCKET;
  1450. #ifdef CPPHTTPLIB_SSL_ENABLED
  1451. // Use void* directly since tls::tls_session_t is not yet defined here
  1452. void *ssl = nullptr;
  1453. #endif
  1454. // For Mbed TLS compatibility: start_time for request timeout tracking
  1455. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1456. bool is_open() const { return sock != INVALID_SOCKET; }
  1457. };
  1458. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1459. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1460. // All of:
  1461. // shutdown_ssl
  1462. // shutdown_socket
  1463. // close_socket
  1464. // should ONLY be called when socket_mutex_ is locked.
  1465. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1466. // with a DIFFERENT thread sending requests using that socket.
  1467. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1468. void shutdown_socket(Socket &socket) const;
  1469. void close_socket(Socket &socket);
  1470. bool process_request(Stream &strm, Request &req, Response &res,
  1471. bool close_connection, Error &error);
  1472. bool write_content_with_provider(Stream &strm, const Request &req,
  1473. Error &error) const;
  1474. void copy_settings(const ClientImpl &rhs);
  1475. void output_log(const Request &req, const Response &res) const;
  1476. void output_error_log(const Error &err, const Request *req) const;
  1477. // Socket endpoint information
  1478. const std::string host_;
  1479. const int port_;
  1480. // Current open socket
  1481. Socket socket_;
  1482. mutable std::mutex socket_mutex_;
  1483. std::recursive_mutex request_mutex_;
  1484. // These are all protected under socket_mutex
  1485. size_t socket_requests_in_flight_ = 0;
  1486. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1487. bool socket_should_be_closed_when_request_is_done_ = false;
  1488. // Hostname-IP map
  1489. std::map<std::string, std::string> addr_map_;
  1490. // Default headers
  1491. Headers default_headers_;
  1492. // Header writer
  1493. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1494. detail::write_headers;
  1495. // Settings
  1496. std::string client_cert_path_;
  1497. std::string client_key_path_;
  1498. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1499. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1500. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1501. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1502. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1503. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1504. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1505. std::string basic_auth_username_;
  1506. std::string basic_auth_password_;
  1507. std::string bearer_token_auth_token_;
  1508. #ifdef CPPHTTPLIB_SSL_ENABLED
  1509. std::string digest_auth_username_;
  1510. std::string digest_auth_password_;
  1511. #endif
  1512. bool keep_alive_ = false;
  1513. bool follow_location_ = false;
  1514. bool path_encode_ = true;
  1515. int address_family_ = AF_UNSPEC;
  1516. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1517. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1518. SocketOptions socket_options_ = nullptr;
  1519. bool compress_ = false;
  1520. bool decompress_ = true;
  1521. std::string interface_;
  1522. std::string proxy_host_;
  1523. int proxy_port_ = -1;
  1524. std::string proxy_basic_auth_username_;
  1525. std::string proxy_basic_auth_password_;
  1526. std::string proxy_bearer_token_auth_token_;
  1527. #ifdef CPPHTTPLIB_SSL_ENABLED
  1528. std::string proxy_digest_auth_username_;
  1529. std::string proxy_digest_auth_password_;
  1530. #endif
  1531. #ifdef CPPHTTPLIB_SSL_ENABLED
  1532. std::string ca_cert_file_path_;
  1533. std::string ca_cert_dir_path_;
  1534. #endif
  1535. #ifdef CPPHTTPLIB_SSL_ENABLED
  1536. bool server_certificate_verification_ = true;
  1537. bool server_hostname_verification_ = true;
  1538. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  1539. #endif
  1540. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1541. X509_STORE *ca_cert_store_ = nullptr;
  1542. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1543. #endif
  1544. mutable std::mutex logger_mutex_;
  1545. Logger logger_;
  1546. ErrorLogger error_logger_;
  1547. #ifdef CPPHTTPLIB_SSL_ENABLED
  1548. int last_ssl_error_ = 0;
  1549. unsigned long last_backend_error_ = 0;
  1550. #endif
  1551. private:
  1552. bool send_(Request &req, Response &res, Error &error);
  1553. Result send_(Request &&req);
  1554. socket_t create_client_socket(Error &error) const;
  1555. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1556. bool skip_100_continue = true) const;
  1557. bool write_request(Stream &strm, Request &req, bool close_connection,
  1558. Error &error, bool skip_body = false);
  1559. bool write_request_body(Stream &strm, Request &req, Error &error);
  1560. void prepare_default_headers(Request &r, bool for_stream,
  1561. const std::string &ct);
  1562. bool redirect(Request &req, Response &res, Error &error);
  1563. bool create_redirect_client(const std::string &scheme,
  1564. const std::string &host, int port, Request &req,
  1565. Response &res, const std::string &path,
  1566. const std::string &location, Error &error);
  1567. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1568. bool handle_request(Stream &strm, Request &req, Response &res,
  1569. bool close_connection, Error &error);
  1570. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1571. Request &req, const char *body, size_t content_length,
  1572. ContentProvider content_provider,
  1573. ContentProviderWithoutLength content_provider_without_length,
  1574. const std::string &content_type, ContentReceiver content_receiver,
  1575. Error &error);
  1576. Result send_with_content_provider_and_receiver(
  1577. const std::string &method, const std::string &path,
  1578. const Headers &headers, const char *body, size_t content_length,
  1579. ContentProvider content_provider,
  1580. ContentProviderWithoutLength content_provider_without_length,
  1581. const std::string &content_type, ContentReceiver content_receiver,
  1582. UploadProgress progress);
  1583. ContentProviderWithoutLength get_multipart_content_provider(
  1584. const std::string &boundary, const UploadFormDataItems &items,
  1585. const FormDataProviderItems &provider_items) const;
  1586. virtual bool
  1587. process_socket(const Socket &socket,
  1588. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1589. std::function<bool(Stream &strm)> callback);
  1590. virtual bool is_ssl() const;
  1591. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1592. };
  1593. class Client {
  1594. public:
  1595. // Universal interface
  1596. explicit Client(const std::string &scheme_host_port);
  1597. explicit Client(const std::string &scheme_host_port,
  1598. const std::string &client_cert_path,
  1599. const std::string &client_key_path);
  1600. // HTTP only interface
  1601. explicit Client(const std::string &host, int port);
  1602. explicit Client(const std::string &host, int port,
  1603. const std::string &client_cert_path,
  1604. const std::string &client_key_path);
  1605. Client(Client &&) = default;
  1606. Client &operator=(Client &&) = default;
  1607. ~Client();
  1608. bool is_valid() const;
  1609. // clang-format off
  1610. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1611. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1612. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1613. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1614. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1615. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1616. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1617. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1618. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1619. Result Head(const std::string &path);
  1620. Result Head(const std::string &path, const Headers &headers);
  1621. Result Post(const std::string &path);
  1622. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1623. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1624. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1625. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1626. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1627. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1628. Result Post(const std::string &path, const Params &params);
  1629. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1630. Result Post(const std::string &path, const Headers &headers);
  1631. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1632. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1633. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1634. 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);
  1635. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1636. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1637. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1638. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1639. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1640. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1641. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1642. Result Put(const std::string &path);
  1643. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1644. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1645. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1646. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1647. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1648. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1649. Result Put(const std::string &path, const Params &params);
  1650. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1651. Result Put(const std::string &path, const Headers &headers);
  1652. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1653. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1654. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1655. 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);
  1656. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1657. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1658. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1659. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1660. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1661. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1662. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1663. Result Patch(const std::string &path);
  1664. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1665. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1666. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1667. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1668. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1669. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1670. Result Patch(const std::string &path, const Params &params);
  1671. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1672. Result Patch(const std::string &path, const Headers &headers);
  1673. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1674. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1675. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1676. 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);
  1677. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1678. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1679. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1680. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1681. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1682. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1683. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1684. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1685. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1686. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1687. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1688. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1689. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1690. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1691. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1692. Result Options(const std::string &path);
  1693. Result Options(const std::string &path, const Headers &headers);
  1694. // clang-format on
  1695. // Streaming API: Open a stream for reading response body incrementally
  1696. // Socket ownership is transferred to StreamHandle for true streaming
  1697. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1698. ClientImpl::StreamHandle open_stream(const std::string &method,
  1699. const std::string &path,
  1700. const Params &params = {},
  1701. const Headers &headers = {},
  1702. const std::string &body = {},
  1703. const std::string &content_type = {});
  1704. bool send(Request &req, Response &res, Error &error);
  1705. Result send(const Request &req);
  1706. void stop();
  1707. std::string host() const;
  1708. int port() const;
  1709. size_t is_socket_open() const;
  1710. socket_t socket() const;
  1711. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1712. void set_default_headers(Headers headers);
  1713. void
  1714. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1715. void set_address_family(int family);
  1716. void set_tcp_nodelay(bool on);
  1717. void set_socket_options(SocketOptions socket_options);
  1718. void set_connection_timeout(time_t sec, time_t usec = 0);
  1719. template <class Rep, class Period>
  1720. void
  1721. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1722. void set_read_timeout(time_t sec, time_t usec = 0);
  1723. template <class Rep, class Period>
  1724. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1725. void set_write_timeout(time_t sec, time_t usec = 0);
  1726. template <class Rep, class Period>
  1727. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1728. void set_max_timeout(time_t msec);
  1729. template <class Rep, class Period>
  1730. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1731. void set_basic_auth(const std::string &username, const std::string &password);
  1732. void set_bearer_token_auth(const std::string &token);
  1733. #ifdef CPPHTTPLIB_SSL_ENABLED
  1734. void set_digest_auth(const std::string &username,
  1735. const std::string &password);
  1736. #endif
  1737. void set_keep_alive(bool on);
  1738. void set_follow_location(bool on);
  1739. void set_path_encode(bool on);
  1740. void set_url_encode(bool on);
  1741. void set_compress(bool on);
  1742. void set_decompress(bool on);
  1743. void set_interface(const std::string &intf);
  1744. void set_proxy(const std::string &host, int port);
  1745. void set_proxy_basic_auth(const std::string &username,
  1746. const std::string &password);
  1747. void set_proxy_bearer_token_auth(const std::string &token);
  1748. #ifdef CPPHTTPLIB_SSL_ENABLED
  1749. void set_proxy_digest_auth(const std::string &username,
  1750. const std::string &password);
  1751. #endif
  1752. #ifdef CPPHTTPLIB_SSL_ENABLED
  1753. void enable_server_certificate_verification(bool enabled);
  1754. void enable_server_hostname_verification(bool enabled);
  1755. #endif
  1756. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1757. void set_server_certificate_verifier(
  1758. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1759. #endif
  1760. void set_logger(Logger logger);
  1761. void set_error_logger(ErrorLogger error_logger);
  1762. // SSL
  1763. #ifdef CPPHTTPLIB_SSL_ENABLED
  1764. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1765. const std::string &ca_cert_dir_path = std::string());
  1766. // Use void* directly since tls::tls_ca_store_t is not yet defined here
  1767. void set_ca_cert_store(void *ca_cert_store);
  1768. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1769. // Custom certificate verification callback (works with all TLS backends)
  1770. // Callback receives session and peer certificate, returns true to accept
  1771. using TlsVerifyCallback = std::function<bool(void *session, void *peer_cert)>;
  1772. void set_server_certificate_verifier(TlsVerifyCallback verifier);
  1773. #endif
  1774. // Backend-agnostic TLS context accessor
  1775. void *tls_context() const;
  1776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1777. long get_openssl_verify_result() const;
  1778. SSL_CTX *ssl_context() const;
  1779. #endif
  1780. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  1781. mbedtls_ssl_config *ssl_config() const;
  1782. #endif
  1783. private:
  1784. std::unique_ptr<ClientImpl> cli_;
  1785. #ifdef CPPHTTPLIB_SSL_ENABLED
  1786. bool is_ssl_ = false;
  1787. #endif
  1788. };
  1789. /*
  1790. * SSL/TLS Server and Client Classes
  1791. */
  1792. #ifdef CPPHTTPLIB_SSL_ENABLED
  1793. class SSLServer : public Server {
  1794. public:
  1795. SSLServer(const char *cert_path, const char *private_key_path,
  1796. const char *client_ca_cert_file_path = nullptr,
  1797. const char *client_ca_cert_dir_path = nullptr,
  1798. const char *private_key_password = nullptr);
  1799. // PEM memory-based constructor (works with all TLS backends)
  1800. struct PemMemory {
  1801. const char *cert_pem;
  1802. size_t cert_pem_len;
  1803. const char *key_pem;
  1804. size_t key_pem_len;
  1805. const char *client_ca_pem;
  1806. size_t client_ca_pem_len;
  1807. const char *private_key_password;
  1808. };
  1809. explicit SSLServer(const PemMemory &pem);
  1810. // Backend-agnostic callback constructor
  1811. // The callback receives the opaque tls_ctx_t handle (void*) which can be
  1812. // cast to the appropriate backend type (SSL_CTX* for OpenSSL, MbedTlsContext*
  1813. // for mbedTLS)
  1814. explicit SSLServer(const std::function<bool(void *ctx)> &setup_callback);
  1815. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1816. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1817. X509_STORE *client_ca_cert_store = nullptr);
  1818. // OpenSSL-specific callback constructor for full API access
  1819. SSLServer(
  1820. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1821. #endif
  1822. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  1823. // mbedTLS-specific callback constructor for full API access
  1824. // Provides direct access to mbedtls_ssl_config for advanced configuration
  1825. SSLServer(
  1826. const std::function<bool(mbedtls_ssl_config &conf)> &setup_callback);
  1827. #endif
  1828. ~SSLServer() override;
  1829. bool is_valid() const override;
  1830. // Update certificates from PEM strings (works with all TLS backends)
  1831. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  1832. const char *password = nullptr);
  1833. bool update_client_ca_pem(const char *ca_pem);
  1834. // Backend-agnostic TLS context accessor
  1835. void *tls_context() const { return ctx_; }
  1836. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1837. SSL_CTX *ssl_context() const;
  1838. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1839. X509_STORE *client_ca_cert_store = nullptr);
  1840. #endif
  1841. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  1842. mbedtls_ssl_config *ssl_config() const;
  1843. #endif
  1844. int ssl_last_error() const { return last_ssl_error_; }
  1845. private:
  1846. bool process_and_close_socket(socket_t sock) override;
  1847. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1848. STACK_OF(X509_NAME) * extract_ca_names_from_x509_store(X509_STORE *store);
  1849. #endif
  1850. // Use void* for tls_ctx_t to support all backends
  1851. void *ctx_ = nullptr;
  1852. std::mutex ctx_mutex_;
  1853. int last_ssl_error_ = 0;
  1854. };
  1855. class SSLClient final : public ClientImpl {
  1856. public:
  1857. explicit SSLClient(const std::string &host);
  1858. explicit SSLClient(const std::string &host, int port);
  1859. explicit SSLClient(const std::string &host, int port,
  1860. const std::string &client_cert_path,
  1861. const std::string &client_key_path,
  1862. const std::string &private_key_password = std::string());
  1863. // PEM memory-based constructor (works with all TLS backends)
  1864. struct PemMemory {
  1865. const char *cert_pem;
  1866. size_t cert_pem_len;
  1867. const char *key_pem;
  1868. size_t key_pem_len;
  1869. const char *private_key_password;
  1870. };
  1871. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  1872. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1873. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1874. EVP_PKEY *client_key,
  1875. const std::string &private_key_password = std::string());
  1876. #endif
  1877. ~SSLClient() override;
  1878. bool is_valid() const override;
  1879. // Use void* directly since tls::tls_ca_store_t is not yet defined here
  1880. void set_ca_cert_store(void *ca_cert_store);
  1881. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1882. // Custom certificate verification callback (works with all TLS backends)
  1883. // Callback receives session and peer certificate, returns true to accept
  1884. using TlsVerifyCallback = std::function<bool(void *session, void *peer_cert)>;
  1885. void set_server_certificate_verifier(TlsVerifyCallback verifier);
  1886. // Backend-agnostic TLS context accessor
  1887. void *tls_context() const { return ctx_; }
  1888. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1889. long get_openssl_verify_result() const;
  1890. SSL_CTX *ssl_context() const;
  1891. #endif
  1892. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  1893. mbedtls_ssl_config *ssl_config() const;
  1894. #endif
  1895. private:
  1896. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1897. bool ensure_socket_connection(Socket &socket, Error &error) override;
  1898. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1899. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1900. bool
  1901. process_socket(const Socket &socket,
  1902. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1903. std::function<bool(Stream &strm)> callback) override;
  1904. bool is_ssl() const override;
  1905. bool connect_with_proxy(
  1906. Socket &sock,
  1907. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1908. Response &res, bool &success, Error &error);
  1909. bool initialize_ssl(Socket &socket, Error &error);
  1910. bool load_certs();
  1911. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1912. bool verify_host(X509 *server_cert) const;
  1913. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1914. bool verify_host_with_common_name(X509 *server_cert) const;
  1915. #endif
  1916. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1917. // Use void* directly since tls::tls_ctx_t is not yet defined here
  1918. void *ctx_;
  1919. std::mutex ctx_mutex_;
  1920. std::once_flag initialize_cert_;
  1921. std::vector<std::string> host_components_;
  1922. long verify_result_ = 0;
  1923. friend class ClientImpl;
  1924. };
  1925. #endif // CPPHTTPLIB_SSL_ENABLED
  1926. /*
  1927. * Implementation of template methods.
  1928. */
  1929. namespace detail {
  1930. template <typename T, typename U>
  1931. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1932. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1933. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1934. duration - std::chrono::seconds(sec))
  1935. .count();
  1936. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1937. }
  1938. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1939. return N - 1;
  1940. }
  1941. inline bool is_numeric(const std::string &str) {
  1942. return !str.empty() &&
  1943. std::all_of(str.cbegin(), str.cend(),
  1944. [](unsigned char c) { return std::isdigit(c); });
  1945. }
  1946. inline size_t get_header_value_u64(const Headers &headers,
  1947. const std::string &key, size_t def,
  1948. size_t id, bool &is_invalid_value) {
  1949. is_invalid_value = false;
  1950. auto rng = headers.equal_range(key);
  1951. auto it = rng.first;
  1952. std::advance(it, static_cast<ssize_t>(id));
  1953. if (it != rng.second) {
  1954. if (is_numeric(it->second)) {
  1955. return std::strtoull(it->second.data(), nullptr, 10);
  1956. } else {
  1957. is_invalid_value = true;
  1958. }
  1959. }
  1960. return def;
  1961. }
  1962. inline size_t get_header_value_u64(const Headers &headers,
  1963. const std::string &key, size_t def,
  1964. size_t id) {
  1965. auto dummy = false;
  1966. return get_header_value_u64(headers, key, def, id, dummy);
  1967. }
  1968. } // namespace detail
  1969. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  1970. size_t id) const {
  1971. return detail::get_header_value_u64(headers, key, def, id);
  1972. }
  1973. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  1974. size_t id) const {
  1975. return detail::get_header_value_u64(headers, key, def, id);
  1976. }
  1977. namespace detail {
  1978. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1979. const void *optval, socklen_t optlen) {
  1980. return setsockopt(sock, level, optname,
  1981. #ifdef _WIN32
  1982. reinterpret_cast<const char *>(optval),
  1983. #else
  1984. optval,
  1985. #endif
  1986. optlen) == 0;
  1987. }
  1988. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1989. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1990. }
  1991. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1992. time_t sec, time_t usec) {
  1993. #ifdef _WIN32
  1994. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1995. #else
  1996. timeval timeout;
  1997. timeout.tv_sec = static_cast<long>(sec);
  1998. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1999. #endif
  2000. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  2001. }
  2002. } // namespace detail
  2003. inline void default_socket_options(socket_t sock) {
  2004. detail::set_socket_opt(sock, SOL_SOCKET,
  2005. #ifdef SO_REUSEPORT
  2006. SO_REUSEPORT,
  2007. #else
  2008. SO_REUSEADDR,
  2009. #endif
  2010. 1);
  2011. }
  2012. inline std::string get_bearer_token_auth(const Request &req) {
  2013. if (req.has_header("Authorization")) {
  2014. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  2015. return req.get_header_value("Authorization")
  2016. .substr(bearer_header_prefix_len);
  2017. }
  2018. return "";
  2019. }
  2020. template <class Rep, class Period>
  2021. inline Server &
  2022. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2023. detail::duration_to_sec_and_usec(
  2024. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2025. return *this;
  2026. }
  2027. template <class Rep, class Period>
  2028. inline Server &
  2029. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2030. detail::duration_to_sec_and_usec(
  2031. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2032. return *this;
  2033. }
  2034. template <class Rep, class Period>
  2035. inline Server &
  2036. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2037. detail::duration_to_sec_and_usec(
  2038. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2039. return *this;
  2040. }
  2041. inline size_t Result::get_request_header_value_u64(const std::string &key,
  2042. size_t def,
  2043. size_t id) const {
  2044. return detail::get_header_value_u64(request_headers_, key, def, id);
  2045. }
  2046. template <class Rep, class Period>
  2047. inline void ClientImpl::set_connection_timeout(
  2048. const std::chrono::duration<Rep, Period> &duration) {
  2049. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2050. set_connection_timeout(sec, usec);
  2051. });
  2052. }
  2053. template <class Rep, class Period>
  2054. inline void ClientImpl::set_read_timeout(
  2055. const std::chrono::duration<Rep, Period> &duration) {
  2056. detail::duration_to_sec_and_usec(
  2057. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2058. }
  2059. template <class Rep, class Period>
  2060. inline void ClientImpl::set_write_timeout(
  2061. const std::chrono::duration<Rep, Period> &duration) {
  2062. detail::duration_to_sec_and_usec(
  2063. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2064. }
  2065. template <class Rep, class Period>
  2066. inline void ClientImpl::set_max_timeout(
  2067. const std::chrono::duration<Rep, Period> &duration) {
  2068. auto msec =
  2069. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2070. set_max_timeout(msec);
  2071. }
  2072. template <class Rep, class Period>
  2073. inline void Client::set_connection_timeout(
  2074. const std::chrono::duration<Rep, Period> &duration) {
  2075. cli_->set_connection_timeout(duration);
  2076. }
  2077. template <class Rep, class Period>
  2078. inline void
  2079. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2080. cli_->set_read_timeout(duration);
  2081. }
  2082. template <class Rep, class Period>
  2083. inline void
  2084. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2085. cli_->set_write_timeout(duration);
  2086. }
  2087. inline void Client::set_max_timeout(time_t msec) {
  2088. cli_->set_max_timeout(msec);
  2089. }
  2090. template <class Rep, class Period>
  2091. inline void
  2092. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2093. cli_->set_max_timeout(duration);
  2094. }
  2095. /*
  2096. * Forward declarations and types that will be part of the .h file if split into
  2097. * .h + .cc.
  2098. */
  2099. std::string hosted_at(const std::string &hostname);
  2100. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2101. // JavaScript-style URL encoding/decoding functions
  2102. std::string encode_uri_component(const std::string &value);
  2103. std::string encode_uri(const std::string &value);
  2104. std::string decode_uri_component(const std::string &value);
  2105. std::string decode_uri(const std::string &value);
  2106. // RFC 3986 compliant URL component encoding/decoding functions
  2107. std::string encode_path_component(const std::string &component);
  2108. std::string decode_path_component(const std::string &component);
  2109. std::string encode_query_component(const std::string &component,
  2110. bool space_as_plus = true);
  2111. std::string decode_query_component(const std::string &component,
  2112. bool plus_as_space = true);
  2113. std::string append_query_params(const std::string &path, const Params &params);
  2114. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2115. std::pair<std::string, std::string>
  2116. make_basic_authentication_header(const std::string &username,
  2117. const std::string &password,
  2118. bool is_proxy = false);
  2119. namespace detail {
  2120. #if defined(_WIN32)
  2121. inline std::wstring u8string_to_wstring(const char *s) {
  2122. if (!s) { return std::wstring(); }
  2123. auto len = static_cast<int>(strlen(s));
  2124. if (!len) { return std::wstring(); }
  2125. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2126. if (!wlen) { return std::wstring(); }
  2127. std::wstring ws;
  2128. ws.resize(wlen);
  2129. wlen = ::MultiByteToWideChar(
  2130. CP_UTF8, 0, s, len,
  2131. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2132. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2133. return ws;
  2134. }
  2135. #endif
  2136. struct FileStat {
  2137. FileStat(const std::string &path);
  2138. bool is_file() const;
  2139. bool is_dir() const;
  2140. time_t mtime() const;
  2141. size_t size() const;
  2142. private:
  2143. #if defined(_WIN32)
  2144. struct _stat st_;
  2145. #else
  2146. struct stat st_;
  2147. #endif
  2148. int ret_ = -1;
  2149. };
  2150. std::string make_host_and_port_string(const std::string &host, int port,
  2151. bool is_ssl);
  2152. std::string trim_copy(const std::string &s);
  2153. void divide(
  2154. const char *data, std::size_t size, char d,
  2155. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2156. fn);
  2157. void divide(
  2158. const std::string &str, char d,
  2159. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2160. fn);
  2161. void split(const char *b, const char *e, char d,
  2162. std::function<void(const char *, const char *)> fn);
  2163. void split(const char *b, const char *e, char d, size_t m,
  2164. std::function<void(const char *, const char *)> fn);
  2165. bool process_client_socket(
  2166. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2167. time_t write_timeout_sec, time_t write_timeout_usec,
  2168. time_t max_timeout_msec,
  2169. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2170. std::function<bool(Stream &)> callback);
  2171. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2172. int port, int address_family, bool tcp_nodelay,
  2173. bool ipv6_v6only, SocketOptions socket_options,
  2174. time_t connection_timeout_sec,
  2175. time_t connection_timeout_usec,
  2176. time_t read_timeout_sec, time_t read_timeout_usec,
  2177. time_t write_timeout_sec,
  2178. time_t write_timeout_usec,
  2179. const std::string &intf, Error &error);
  2180. const char *get_header_value(const Headers &headers, const std::string &key,
  2181. const char *def, size_t id);
  2182. std::string params_to_query_str(const Params &params);
  2183. void parse_query_text(const char *data, std::size_t size, Params &params);
  2184. void parse_query_text(const std::string &s, Params &params);
  2185. bool parse_multipart_boundary(const std::string &content_type,
  2186. std::string &boundary);
  2187. bool parse_range_header(const std::string &s, Ranges &ranges);
  2188. bool parse_accept_header(const std::string &s,
  2189. std::vector<std::string> &content_types);
  2190. int close_socket(socket_t sock);
  2191. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2192. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2193. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2194. EncodingType encoding_type(const Request &req, const Response &res);
  2195. class BufferStream final : public Stream {
  2196. public:
  2197. BufferStream() = default;
  2198. ~BufferStream() override = default;
  2199. bool is_readable() const override;
  2200. bool wait_readable() const override;
  2201. bool wait_writable() const override;
  2202. ssize_t read(char *ptr, size_t size) override;
  2203. ssize_t write(const char *ptr, size_t size) override;
  2204. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2205. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2206. socket_t socket() const override;
  2207. time_t duration() const override;
  2208. const std::string &get_buffer() const;
  2209. private:
  2210. std::string buffer;
  2211. size_t position = 0;
  2212. };
  2213. class compressor {
  2214. public:
  2215. virtual ~compressor() = default;
  2216. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2217. virtual bool compress(const char *data, size_t data_length, bool last,
  2218. Callback callback) = 0;
  2219. };
  2220. class decompressor {
  2221. public:
  2222. virtual ~decompressor() = default;
  2223. virtual bool is_valid() const = 0;
  2224. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2225. virtual bool decompress(const char *data, size_t data_length,
  2226. Callback callback) = 0;
  2227. };
  2228. class nocompressor final : public compressor {
  2229. public:
  2230. ~nocompressor() override = default;
  2231. bool compress(const char *data, size_t data_length, bool /*last*/,
  2232. Callback callback) override;
  2233. };
  2234. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2235. class gzip_compressor final : public compressor {
  2236. public:
  2237. gzip_compressor();
  2238. ~gzip_compressor() override;
  2239. bool compress(const char *data, size_t data_length, bool last,
  2240. Callback callback) override;
  2241. private:
  2242. bool is_valid_ = false;
  2243. z_stream strm_;
  2244. };
  2245. class gzip_decompressor final : public decompressor {
  2246. public:
  2247. gzip_decompressor();
  2248. ~gzip_decompressor() override;
  2249. bool is_valid() const override;
  2250. bool decompress(const char *data, size_t data_length,
  2251. Callback callback) override;
  2252. private:
  2253. bool is_valid_ = false;
  2254. z_stream strm_;
  2255. };
  2256. #endif
  2257. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2258. class brotli_compressor final : public compressor {
  2259. public:
  2260. brotli_compressor();
  2261. ~brotli_compressor();
  2262. bool compress(const char *data, size_t data_length, bool last,
  2263. Callback callback) override;
  2264. private:
  2265. BrotliEncoderState *state_ = nullptr;
  2266. };
  2267. class brotli_decompressor final : public decompressor {
  2268. public:
  2269. brotli_decompressor();
  2270. ~brotli_decompressor();
  2271. bool is_valid() const override;
  2272. bool decompress(const char *data, size_t data_length,
  2273. Callback callback) override;
  2274. private:
  2275. BrotliDecoderResult decoder_r;
  2276. BrotliDecoderState *decoder_s = nullptr;
  2277. };
  2278. #endif
  2279. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2280. class zstd_compressor : public compressor {
  2281. public:
  2282. zstd_compressor();
  2283. ~zstd_compressor();
  2284. bool compress(const char *data, size_t data_length, bool last,
  2285. Callback callback) override;
  2286. private:
  2287. ZSTD_CCtx *ctx_ = nullptr;
  2288. };
  2289. class zstd_decompressor : public decompressor {
  2290. public:
  2291. zstd_decompressor();
  2292. ~zstd_decompressor();
  2293. bool is_valid() const override;
  2294. bool decompress(const char *data, size_t data_length,
  2295. Callback callback) override;
  2296. private:
  2297. ZSTD_DCtx *ctx_ = nullptr;
  2298. };
  2299. #endif
  2300. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2301. // to store data. The call can set memory on stack for performance.
  2302. class stream_line_reader {
  2303. public:
  2304. stream_line_reader(Stream &strm, char *fixed_buffer,
  2305. size_t fixed_buffer_size);
  2306. const char *ptr() const;
  2307. size_t size() const;
  2308. bool end_with_crlf() const;
  2309. bool getline();
  2310. private:
  2311. void append(char c);
  2312. Stream &strm_;
  2313. char *fixed_buffer_;
  2314. const size_t fixed_buffer_size_;
  2315. size_t fixed_buffer_used_size_ = 0;
  2316. std::string growable_buffer_;
  2317. };
  2318. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2319. const Headers &src_headers);
  2320. struct ChunkedDecoder {
  2321. Stream &strm;
  2322. size_t chunk_remaining = 0;
  2323. bool finished = false;
  2324. char line_buf[64];
  2325. size_t last_chunk_total = 0;
  2326. size_t last_chunk_offset = 0;
  2327. explicit ChunkedDecoder(Stream &s);
  2328. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2329. size_t &out_chunk_total);
  2330. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2331. };
  2332. class mmap {
  2333. public:
  2334. mmap(const char *path);
  2335. ~mmap();
  2336. bool open(const char *path);
  2337. void close();
  2338. bool is_open() const;
  2339. size_t size() const;
  2340. const char *data() const;
  2341. private:
  2342. #if defined(_WIN32)
  2343. HANDLE hFile_ = NULL;
  2344. HANDLE hMapping_ = NULL;
  2345. #else
  2346. int fd_ = -1;
  2347. #endif
  2348. size_t size_ = 0;
  2349. void *addr_ = nullptr;
  2350. bool is_open_empty_file = false;
  2351. };
  2352. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2353. namespace fields {
  2354. bool is_token_char(char c);
  2355. bool is_token(const std::string &s);
  2356. bool is_field_name(const std::string &s);
  2357. bool is_vchar(char c);
  2358. bool is_obs_text(char c);
  2359. bool is_field_vchar(char c);
  2360. bool is_field_content(const std::string &s);
  2361. bool is_field_value(const std::string &s);
  2362. } // namespace fields
  2363. /*
  2364. * TLS Abstraction Layer Declarations
  2365. */
  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. // Utility function for SSL implementation
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. bool is_ip_address(const std::string &host);
  2522. #endif
  2523. } // namespace detail
  2524. namespace stream {
  2525. class Result {
  2526. public:
  2527. Result() : chunk_size_(8192) {}
  2528. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192)
  2529. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  2530. Result(Result &&other) noexcept
  2531. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  2532. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  2533. finished_(other.finished_) {
  2534. other.current_size_ = 0;
  2535. other.finished_ = true;
  2536. }
  2537. Result &operator=(Result &&other) noexcept {
  2538. if (this != &other) {
  2539. handle_ = std::move(other.handle_);
  2540. buffer_ = std::move(other.buffer_);
  2541. current_size_ = other.current_size_;
  2542. chunk_size_ = other.chunk_size_;
  2543. finished_ = other.finished_;
  2544. other.current_size_ = 0;
  2545. other.finished_ = true;
  2546. }
  2547. return *this;
  2548. }
  2549. Result(const Result &) = delete;
  2550. Result &operator=(const Result &) = delete;
  2551. // Check if the result is valid (connection succeeded and response received)
  2552. bool is_valid() const { return handle_.is_valid(); }
  2553. explicit operator bool() const { return is_valid(); }
  2554. // Response status code
  2555. int status() const {
  2556. return handle_.response ? handle_.response->status : -1;
  2557. }
  2558. // Response headers
  2559. const Headers &headers() const {
  2560. static const Headers empty_headers;
  2561. return handle_.response ? handle_.response->headers : empty_headers;
  2562. }
  2563. std::string get_header_value(const std::string &key,
  2564. const char *def = "") const {
  2565. return handle_.response ? handle_.response->get_header_value(key, def)
  2566. : def;
  2567. }
  2568. bool has_header(const std::string &key) const {
  2569. return handle_.response ? handle_.response->has_header(key) : false;
  2570. }
  2571. // Error information
  2572. Error error() const { return handle_.error; }
  2573. Error read_error() const { return handle_.get_read_error(); }
  2574. bool has_read_error() const { return handle_.has_read_error(); }
  2575. // Streaming iteration API
  2576. // Call next() to read the next chunk, then access data via data()/size()
  2577. // Returns true if data was read, false when stream is exhausted
  2578. bool next() {
  2579. if (!handle_.is_valid() || finished_) { return false; }
  2580. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  2581. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  2582. if (n > 0) {
  2583. current_size_ = static_cast<size_t>(n);
  2584. return true;
  2585. }
  2586. current_size_ = 0;
  2587. finished_ = true;
  2588. return false;
  2589. }
  2590. // Pointer to current chunk data (valid after next() returns true)
  2591. const char *data() const { return buffer_.data(); }
  2592. // Size of current chunk (valid after next() returns true)
  2593. size_t size() const { return current_size_; }
  2594. // Convenience method: read all remaining data into a string
  2595. std::string read_all() {
  2596. std::string result;
  2597. while (next()) {
  2598. result.append(data(), size());
  2599. }
  2600. return result;
  2601. }
  2602. private:
  2603. ClientImpl::StreamHandle handle_;
  2604. std::string buffer_;
  2605. size_t current_size_ = 0;
  2606. size_t chunk_size_;
  2607. bool finished_ = false;
  2608. };
  2609. // GET
  2610. template <typename ClientType>
  2611. inline Result Get(ClientType &cli, const std::string &path,
  2612. size_t chunk_size = 8192) {
  2613. return Result{cli.open_stream("GET", path), chunk_size};
  2614. }
  2615. template <typename ClientType>
  2616. inline Result Get(ClientType &cli, const std::string &path,
  2617. const Headers &headers, size_t chunk_size = 8192) {
  2618. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2619. }
  2620. template <typename ClientType>
  2621. inline Result Get(ClientType &cli, const std::string &path,
  2622. const Params &params, size_t chunk_size = 8192) {
  2623. return Result{cli.open_stream("GET", path, params), chunk_size};
  2624. }
  2625. template <typename ClientType>
  2626. inline Result Get(ClientType &cli, const std::string &path,
  2627. const Params &params, const Headers &headers,
  2628. size_t chunk_size = 8192) {
  2629. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2630. }
  2631. // POST
  2632. template <typename ClientType>
  2633. inline Result Post(ClientType &cli, const std::string &path,
  2634. const std::string &body, const std::string &content_type,
  2635. size_t chunk_size = 8192) {
  2636. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2637. chunk_size};
  2638. }
  2639. template <typename ClientType>
  2640. inline Result Post(ClientType &cli, const std::string &path,
  2641. const Headers &headers, const std::string &body,
  2642. const std::string &content_type, size_t chunk_size = 8192) {
  2643. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2644. chunk_size};
  2645. }
  2646. template <typename ClientType>
  2647. inline Result Post(ClientType &cli, const std::string &path,
  2648. const Params &params, const std::string &body,
  2649. const std::string &content_type, size_t chunk_size = 8192) {
  2650. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2651. chunk_size};
  2652. }
  2653. template <typename ClientType>
  2654. inline Result Post(ClientType &cli, const std::string &path,
  2655. const Params &params, const Headers &headers,
  2656. const std::string &body, const std::string &content_type,
  2657. size_t chunk_size = 8192) {
  2658. return Result{
  2659. cli.open_stream("POST", path, params, headers, body, content_type),
  2660. chunk_size};
  2661. }
  2662. // PUT
  2663. template <typename ClientType>
  2664. inline Result Put(ClientType &cli, const std::string &path,
  2665. const std::string &body, const std::string &content_type,
  2666. size_t chunk_size = 8192) {
  2667. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2668. chunk_size};
  2669. }
  2670. template <typename ClientType>
  2671. inline Result Put(ClientType &cli, const std::string &path,
  2672. const Headers &headers, const std::string &body,
  2673. const std::string &content_type, size_t chunk_size = 8192) {
  2674. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2675. chunk_size};
  2676. }
  2677. template <typename ClientType>
  2678. inline Result Put(ClientType &cli, const std::string &path,
  2679. const Params &params, const std::string &body,
  2680. const std::string &content_type, size_t chunk_size = 8192) {
  2681. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2682. chunk_size};
  2683. }
  2684. template <typename ClientType>
  2685. inline Result Put(ClientType &cli, const std::string &path,
  2686. const Params &params, const Headers &headers,
  2687. const std::string &body, const std::string &content_type,
  2688. size_t chunk_size = 8192) {
  2689. return Result{
  2690. cli.open_stream("PUT", path, params, headers, body, content_type),
  2691. chunk_size};
  2692. }
  2693. // PATCH
  2694. template <typename ClientType>
  2695. inline Result Patch(ClientType &cli, const std::string &path,
  2696. const std::string &body, const std::string &content_type,
  2697. size_t chunk_size = 8192) {
  2698. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2699. chunk_size};
  2700. }
  2701. template <typename ClientType>
  2702. inline Result Patch(ClientType &cli, const std::string &path,
  2703. const Headers &headers, const std::string &body,
  2704. const std::string &content_type, size_t chunk_size = 8192) {
  2705. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2706. chunk_size};
  2707. }
  2708. template <typename ClientType>
  2709. inline Result Patch(ClientType &cli, const std::string &path,
  2710. const Params &params, const std::string &body,
  2711. const std::string &content_type, size_t chunk_size = 8192) {
  2712. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2713. chunk_size};
  2714. }
  2715. template <typename ClientType>
  2716. inline Result Patch(ClientType &cli, const std::string &path,
  2717. const Params &params, const Headers &headers,
  2718. const std::string &body, const std::string &content_type,
  2719. size_t chunk_size = 8192) {
  2720. return Result{
  2721. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2722. chunk_size};
  2723. }
  2724. // DELETE
  2725. template <typename ClientType>
  2726. inline Result Delete(ClientType &cli, const std::string &path,
  2727. size_t chunk_size = 8192) {
  2728. return Result{cli.open_stream("DELETE", path), chunk_size};
  2729. }
  2730. template <typename ClientType>
  2731. inline Result Delete(ClientType &cli, const std::string &path,
  2732. const Headers &headers, size_t chunk_size = 8192) {
  2733. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2734. }
  2735. template <typename ClientType>
  2736. inline Result Delete(ClientType &cli, const std::string &path,
  2737. const std::string &body, const std::string &content_type,
  2738. size_t chunk_size = 8192) {
  2739. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2740. chunk_size};
  2741. }
  2742. template <typename ClientType>
  2743. inline Result Delete(ClientType &cli, const std::string &path,
  2744. const Headers &headers, const std::string &body,
  2745. const std::string &content_type,
  2746. size_t chunk_size = 8192) {
  2747. return Result{
  2748. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2749. chunk_size};
  2750. }
  2751. template <typename ClientType>
  2752. inline Result Delete(ClientType &cli, const std::string &path,
  2753. const Params &params, size_t chunk_size = 8192) {
  2754. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2755. }
  2756. template <typename ClientType>
  2757. inline Result Delete(ClientType &cli, const std::string &path,
  2758. const Params &params, const Headers &headers,
  2759. size_t chunk_size = 8192) {
  2760. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2761. }
  2762. template <typename ClientType>
  2763. inline Result Delete(ClientType &cli, const std::string &path,
  2764. const Params &params, const std::string &body,
  2765. const std::string &content_type,
  2766. size_t chunk_size = 8192) {
  2767. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2768. chunk_size};
  2769. }
  2770. template <typename ClientType>
  2771. inline Result Delete(ClientType &cli, const std::string &path,
  2772. const Params &params, const Headers &headers,
  2773. const std::string &body, const std::string &content_type,
  2774. size_t chunk_size = 8192) {
  2775. return Result{
  2776. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2777. chunk_size};
  2778. }
  2779. // HEAD
  2780. template <typename ClientType>
  2781. inline Result Head(ClientType &cli, const std::string &path,
  2782. size_t chunk_size = 8192) {
  2783. return Result{cli.open_stream("HEAD", path), chunk_size};
  2784. }
  2785. template <typename ClientType>
  2786. inline Result Head(ClientType &cli, const std::string &path,
  2787. const Headers &headers, size_t chunk_size = 8192) {
  2788. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2789. }
  2790. template <typename ClientType>
  2791. inline Result Head(ClientType &cli, const std::string &path,
  2792. const Params &params, size_t chunk_size = 8192) {
  2793. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2794. }
  2795. template <typename ClientType>
  2796. inline Result Head(ClientType &cli, const std::string &path,
  2797. const Params &params, const Headers &headers,
  2798. size_t chunk_size = 8192) {
  2799. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2800. }
  2801. // OPTIONS
  2802. template <typename ClientType>
  2803. inline Result Options(ClientType &cli, const std::string &path,
  2804. size_t chunk_size = 8192) {
  2805. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2806. }
  2807. template <typename ClientType>
  2808. inline Result Options(ClientType &cli, const std::string &path,
  2809. const Headers &headers, size_t chunk_size = 8192) {
  2810. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2811. }
  2812. template <typename ClientType>
  2813. inline Result Options(ClientType &cli, const std::string &path,
  2814. const Params &params, size_t chunk_size = 8192) {
  2815. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2816. }
  2817. template <typename ClientType>
  2818. inline Result Options(ClientType &cli, const std::string &path,
  2819. const Params &params, const Headers &headers,
  2820. size_t chunk_size = 8192) {
  2821. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2822. }
  2823. } // namespace stream
  2824. namespace sse {
  2825. struct SSEMessage {
  2826. std::string event; // Event type (default: "message")
  2827. std::string data; // Event payload
  2828. std::string id; // Event ID for Last-Event-ID header
  2829. SSEMessage() : event("message") {}
  2830. void clear() {
  2831. event = "message";
  2832. data.clear();
  2833. id.clear();
  2834. }
  2835. };
  2836. class SSEClient {
  2837. public:
  2838. using MessageHandler = std::function<void(const SSEMessage &)>;
  2839. using ErrorHandler = std::function<void(Error)>;
  2840. using OpenHandler = std::function<void()>;
  2841. SSEClient(Client &client, const std::string &path)
  2842. : client_(client), path_(path) {}
  2843. SSEClient(Client &client, const std::string &path, const Headers &headers)
  2844. : client_(client), path_(path), headers_(headers) {}
  2845. ~SSEClient() { stop(); }
  2846. SSEClient(const SSEClient &) = delete;
  2847. SSEClient &operator=(const SSEClient &) = delete;
  2848. // Event handlers
  2849. SSEClient &on_message(MessageHandler handler) {
  2850. on_message_ = std::move(handler);
  2851. return *this;
  2852. }
  2853. SSEClient &on_event(const std::string &type, MessageHandler handler) {
  2854. event_handlers_[type] = std::move(handler);
  2855. return *this;
  2856. }
  2857. SSEClient &on_open(OpenHandler handler) {
  2858. on_open_ = std::move(handler);
  2859. return *this;
  2860. }
  2861. SSEClient &on_error(ErrorHandler handler) {
  2862. on_error_ = std::move(handler);
  2863. return *this;
  2864. }
  2865. SSEClient &set_reconnect_interval(int ms) {
  2866. reconnect_interval_ms_ = ms;
  2867. return *this;
  2868. }
  2869. SSEClient &set_max_reconnect_attempts(int n) {
  2870. max_reconnect_attempts_ = n;
  2871. return *this;
  2872. }
  2873. // State accessors
  2874. bool is_connected() const { return connected_.load(); }
  2875. const std::string &last_event_id() const { return last_event_id_; }
  2876. // Blocking start - runs event loop with auto-reconnect
  2877. void start() {
  2878. running_.store(true);
  2879. run_event_loop();
  2880. }
  2881. // Non-blocking start - runs in background thread
  2882. void start_async() {
  2883. running_.store(true);
  2884. async_thread_ = std::thread([this]() { run_event_loop(); });
  2885. }
  2886. // Stop the client (thread-safe)
  2887. void stop() {
  2888. running_.store(false);
  2889. client_.stop(); // Cancel any pending operations
  2890. if (async_thread_.joinable()) { async_thread_.join(); }
  2891. }
  2892. private:
  2893. // Parse a single SSE field line
  2894. // Returns true if this line ends an event (blank line)
  2895. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms) {
  2896. // Blank line signals end of event
  2897. if (line.empty() || line == "\r") { return true; }
  2898. // Lines starting with ':' are comments (ignored)
  2899. if (!line.empty() && line[0] == ':') { return false; }
  2900. // Find the colon separator
  2901. auto colon_pos = line.find(':');
  2902. if (colon_pos == std::string::npos) {
  2903. // Line with no colon is treated as field name with empty value
  2904. return false;
  2905. }
  2906. auto field = line.substr(0, colon_pos);
  2907. std::string value;
  2908. // Value starts after colon, skip optional single space
  2909. if (colon_pos + 1 < line.size()) {
  2910. auto value_start = colon_pos + 1;
  2911. if (line[value_start] == ' ') { value_start++; }
  2912. value = line.substr(value_start);
  2913. // Remove trailing \r if present
  2914. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  2915. }
  2916. // Handle known fields
  2917. if (field == "event") {
  2918. msg.event = value;
  2919. } else if (field == "data") {
  2920. // Multiple data lines are concatenated with newlines
  2921. if (!msg.data.empty()) { msg.data += "\n"; }
  2922. msg.data += value;
  2923. } else if (field == "id") {
  2924. // Empty id is valid (clears the last event ID)
  2925. msg.id = value;
  2926. } else if (field == "retry") {
  2927. // Parse retry interval in milliseconds
  2928. try {
  2929. retry_ms = std::stoi(value);
  2930. } catch (...) {
  2931. // Invalid retry value, ignore
  2932. }
  2933. }
  2934. // Unknown fields are ignored per SSE spec
  2935. return false;
  2936. }
  2937. // Main event loop with auto-reconnect
  2938. void run_event_loop() {
  2939. auto reconnect_count = 0;
  2940. while (running_.load()) {
  2941. // Build headers, including Last-Event-ID if we have one
  2942. auto request_headers = headers_;
  2943. if (!last_event_id_.empty()) {
  2944. request_headers.emplace("Last-Event-ID", last_event_id_);
  2945. }
  2946. // Open streaming connection
  2947. auto result = stream::Get(client_, path_, request_headers);
  2948. // Connection error handling
  2949. if (!result) {
  2950. connected_.store(false);
  2951. if (on_error_) { on_error_(result.error()); }
  2952. if (!should_reconnect(reconnect_count)) { break; }
  2953. wait_for_reconnect();
  2954. reconnect_count++;
  2955. continue;
  2956. }
  2957. if (result.status() != 200) {
  2958. connected_.store(false);
  2959. // For certain errors, don't reconnect
  2960. if (result.status() == 204 || // No Content - server wants us to stop
  2961. result.status() == 404 || // Not Found
  2962. result.status() == 401 || // Unauthorized
  2963. result.status() == 403) { // Forbidden
  2964. if (on_error_) { on_error_(Error::Connection); }
  2965. break;
  2966. }
  2967. if (on_error_) { on_error_(Error::Connection); }
  2968. if (!should_reconnect(reconnect_count)) { break; }
  2969. wait_for_reconnect();
  2970. reconnect_count++;
  2971. continue;
  2972. }
  2973. // Connection successful
  2974. connected_.store(true);
  2975. reconnect_count = 0;
  2976. if (on_open_) { on_open_(); }
  2977. // Event receiving loop
  2978. std::string buffer;
  2979. SSEMessage current_msg;
  2980. while (running_.load() && result.next()) {
  2981. buffer.append(result.data(), result.size());
  2982. // Process complete lines in the buffer
  2983. size_t line_start = 0;
  2984. size_t newline_pos;
  2985. while ((newline_pos = buffer.find('\n', line_start)) !=
  2986. std::string::npos) {
  2987. auto line = buffer.substr(line_start, newline_pos - line_start);
  2988. line_start = newline_pos + 1;
  2989. // Parse the line and check if event is complete
  2990. auto event_complete =
  2991. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  2992. if (event_complete && !current_msg.data.empty()) {
  2993. // Update last_event_id for reconnection
  2994. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  2995. // Dispatch event to appropriate handler
  2996. dispatch_event(current_msg);
  2997. current_msg.clear();
  2998. }
  2999. }
  3000. // Keep unprocessed data in buffer
  3001. buffer.erase(0, line_start);
  3002. }
  3003. // Connection ended
  3004. connected_.store(false);
  3005. if (!running_.load()) { break; }
  3006. // Check for read errors
  3007. if (result.has_read_error()) {
  3008. if (on_error_) { on_error_(result.read_error()); }
  3009. }
  3010. if (!should_reconnect(reconnect_count)) { break; }
  3011. wait_for_reconnect();
  3012. reconnect_count++;
  3013. }
  3014. connected_.store(false);
  3015. }
  3016. // Dispatch event to appropriate handler
  3017. void dispatch_event(const SSEMessage &msg) {
  3018. // Check for specific event type handler first
  3019. auto it = event_handlers_.find(msg.event);
  3020. if (it != event_handlers_.end()) {
  3021. it->second(msg);
  3022. return;
  3023. }
  3024. // Fall back to generic message handler
  3025. if (on_message_) { on_message_(msg); }
  3026. }
  3027. // Check if we should attempt to reconnect
  3028. bool should_reconnect(int count) const {
  3029. if (!running_.load()) { return false; }
  3030. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3031. return count < max_reconnect_attempts_;
  3032. }
  3033. // Wait for reconnect interval
  3034. void wait_for_reconnect() {
  3035. // Use small increments to check running_ flag frequently
  3036. auto waited = 0;
  3037. while (running_.load() && waited < reconnect_interval_ms_) {
  3038. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3039. waited += 100;
  3040. }
  3041. }
  3042. // Client and path
  3043. Client &client_;
  3044. std::string path_;
  3045. Headers headers_;
  3046. // Callbacks
  3047. MessageHandler on_message_;
  3048. std::map<std::string, MessageHandler> event_handlers_;
  3049. OpenHandler on_open_;
  3050. ErrorHandler on_error_;
  3051. // Configuration
  3052. int reconnect_interval_ms_ = 3000;
  3053. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3054. // State
  3055. std::atomic<bool> running_{false};
  3056. std::atomic<bool> connected_{false};
  3057. std::string last_event_id_;
  3058. // Async support
  3059. std::thread async_thread_;
  3060. };
  3061. } // namespace sse
  3062. // ----------------------------------------------------------------------------
  3063. /*
  3064. * Implementation that will be part of the .cc file if split into .h + .cc.
  3065. */
  3066. namespace detail {
  3067. inline bool is_hex(char c, int &v) {
  3068. if (isdigit(c)) {
  3069. v = c - '0';
  3070. return true;
  3071. } else if ('A' <= c && c <= 'F') {
  3072. v = c - 'A' + 10;
  3073. return true;
  3074. } else if ('a' <= c && c <= 'f') {
  3075. v = c - 'a' + 10;
  3076. return true;
  3077. }
  3078. return false;
  3079. }
  3080. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3081. int &val) {
  3082. if (i >= s.size()) { return false; }
  3083. val = 0;
  3084. for (; cnt; i++, cnt--) {
  3085. if (!s[i]) { return false; }
  3086. auto v = 0;
  3087. if (is_hex(s[i], v)) {
  3088. val = val * 16 + v;
  3089. } else {
  3090. return false;
  3091. }
  3092. }
  3093. return true;
  3094. }
  3095. inline std::string from_i_to_hex(size_t n) {
  3096. static const auto charset = "0123456789abcdef";
  3097. std::string ret;
  3098. do {
  3099. ret = charset[n & 15] + ret;
  3100. n >>= 4;
  3101. } while (n > 0);
  3102. return ret;
  3103. }
  3104. inline std::string compute_etag(const FileStat &fs) {
  3105. if (!fs.is_file()) { return std::string(); }
  3106. // If mtime cannot be determined (negative value indicates an error
  3107. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3108. // value like 0 could collide with a real file that legitimately has
  3109. // mtime == 0 (epoch) and lead to misleading validators.
  3110. auto mtime_raw = fs.mtime();
  3111. if (mtime_raw < 0) { return std::string(); }
  3112. auto mtime = static_cast<size_t>(mtime_raw);
  3113. auto size = fs.size();
  3114. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3115. from_i_to_hex(size) + "\"";
  3116. }
  3117. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3118. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3119. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3120. inline std::string file_mtime_to_http_date(time_t mtime) {
  3121. if (mtime < 0) { return std::string(); }
  3122. struct tm tm_buf;
  3123. #ifdef _WIN32
  3124. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3125. #else
  3126. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3127. #endif
  3128. char buf[64];
  3129. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3130. return std::string();
  3131. }
  3132. return std::string(buf);
  3133. }
  3134. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3135. inline time_t parse_http_date(const std::string &date_str) {
  3136. struct tm tm_buf;
  3137. // Create a classic locale object once for all parsing attempts
  3138. const std::locale classic_locale = std::locale::classic();
  3139. // Try to parse using std::get_time (C++11, cross-platform)
  3140. auto try_parse = [&](const char *fmt) -> bool {
  3141. std::istringstream ss(date_str);
  3142. ss.imbue(classic_locale);
  3143. memset(&tm_buf, 0, sizeof(tm_buf));
  3144. ss >> std::get_time(&tm_buf, fmt);
  3145. return !ss.fail();
  3146. };
  3147. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3148. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3149. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3150. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3151. // asctime format: "Sun Nov 6 08:49:37 1994"
  3152. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3153. return static_cast<time_t>(-1);
  3154. }
  3155. }
  3156. }
  3157. #ifdef _WIN32
  3158. return _mkgmtime(&tm_buf);
  3159. #else
  3160. return timegm(&tm_buf);
  3161. #endif
  3162. }
  3163. inline bool is_weak_etag(const std::string &s) {
  3164. // Check if the string is a weak ETag (starts with 'W/"')
  3165. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3166. }
  3167. inline bool is_strong_etag(const std::string &s) {
  3168. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3169. // chars)
  3170. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3171. }
  3172. inline size_t to_utf8(int code, char *buff) {
  3173. if (code < 0x0080) {
  3174. buff[0] = static_cast<char>(code & 0x7F);
  3175. return 1;
  3176. } else if (code < 0x0800) {
  3177. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3178. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3179. return 2;
  3180. } else if (code < 0xD800) {
  3181. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3182. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3183. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3184. return 3;
  3185. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3186. return 0;
  3187. } else if (code < 0x10000) {
  3188. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3189. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3190. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3191. return 3;
  3192. } else if (code < 0x110000) {
  3193. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3194. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3195. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3196. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3197. return 4;
  3198. }
  3199. // NOTREACHED
  3200. return 0;
  3201. }
  3202. // NOTE: This code came up with the following stackoverflow post:
  3203. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3204. inline std::string base64_encode(const std::string &in) {
  3205. static const auto lookup =
  3206. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3207. std::string out;
  3208. out.reserve(in.size());
  3209. auto val = 0;
  3210. auto valb = -6;
  3211. for (auto c : in) {
  3212. val = (val << 8) + static_cast<uint8_t>(c);
  3213. valb += 8;
  3214. while (valb >= 0) {
  3215. out.push_back(lookup[(val >> valb) & 0x3F]);
  3216. valb -= 6;
  3217. }
  3218. }
  3219. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3220. while (out.size() % 4) {
  3221. out.push_back('=');
  3222. }
  3223. return out;
  3224. }
  3225. inline bool is_valid_path(const std::string &path) {
  3226. size_t level = 0;
  3227. size_t i = 0;
  3228. // Skip slash
  3229. while (i < path.size() && path[i] == '/') {
  3230. i++;
  3231. }
  3232. while (i < path.size()) {
  3233. // Read component
  3234. auto beg = i;
  3235. while (i < path.size() && path[i] != '/') {
  3236. if (path[i] == '\0') {
  3237. return false;
  3238. } else if (path[i] == '\\') {
  3239. return false;
  3240. }
  3241. i++;
  3242. }
  3243. auto len = i - beg;
  3244. assert(len > 0);
  3245. if (!path.compare(beg, len, ".")) {
  3246. ;
  3247. } else if (!path.compare(beg, len, "..")) {
  3248. if (level == 0) { return false; }
  3249. level--;
  3250. } else {
  3251. level++;
  3252. }
  3253. // Skip slash
  3254. while (i < path.size() && path[i] == '/') {
  3255. i++;
  3256. }
  3257. }
  3258. return true;
  3259. }
  3260. inline FileStat::FileStat(const std::string &path) {
  3261. #if defined(_WIN32)
  3262. auto wpath = u8string_to_wstring(path.c_str());
  3263. ret_ = _wstat(wpath.c_str(), &st_);
  3264. #else
  3265. ret_ = stat(path.c_str(), &st_);
  3266. #endif
  3267. }
  3268. inline bool FileStat::is_file() const {
  3269. return ret_ >= 0 && S_ISREG(st_.st_mode);
  3270. }
  3271. inline bool FileStat::is_dir() const {
  3272. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  3273. }
  3274. inline time_t FileStat::mtime() const {
  3275. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  3276. : static_cast<time_t>(-1);
  3277. }
  3278. inline size_t FileStat::size() const {
  3279. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  3280. }
  3281. inline std::string encode_path(const std::string &s) {
  3282. std::string result;
  3283. result.reserve(s.size());
  3284. for (size_t i = 0; s[i]; i++) {
  3285. switch (s[i]) {
  3286. case ' ': result += "%20"; break;
  3287. case '+': result += "%2B"; break;
  3288. case '\r': result += "%0D"; break;
  3289. case '\n': result += "%0A"; break;
  3290. case '\'': result += "%27"; break;
  3291. case ',': result += "%2C"; break;
  3292. // case ':': result += "%3A"; break; // ok? probably...
  3293. case ';': result += "%3B"; break;
  3294. default:
  3295. auto c = static_cast<uint8_t>(s[i]);
  3296. if (c >= 0x80) {
  3297. result += '%';
  3298. char hex[4];
  3299. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  3300. assert(len == 2);
  3301. result.append(hex, static_cast<size_t>(len));
  3302. } else {
  3303. result += s[i];
  3304. }
  3305. break;
  3306. }
  3307. }
  3308. return result;
  3309. }
  3310. inline std::string file_extension(const std::string &path) {
  3311. std::smatch m;
  3312. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  3313. if (std::regex_search(path, m, re)) { return m[1].str(); }
  3314. return std::string();
  3315. }
  3316. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  3317. template <typename T>
  3318. inline bool parse_header(const char *beg, const char *end, T fn);
  3319. template <typename T>
  3320. inline bool parse_header(const char *beg, const char *end, T fn) {
  3321. // Skip trailing spaces and tabs.
  3322. while (beg < end && is_space_or_tab(end[-1])) {
  3323. end--;
  3324. }
  3325. auto p = beg;
  3326. while (p < end && *p != ':') {
  3327. p++;
  3328. }
  3329. auto name = std::string(beg, p);
  3330. if (!detail::fields::is_field_name(name)) { return false; }
  3331. if (p == end) { return false; }
  3332. auto key_end = p;
  3333. if (*p++ != ':') { return false; }
  3334. while (p < end && is_space_or_tab(*p)) {
  3335. p++;
  3336. }
  3337. if (p <= end) {
  3338. auto key_len = key_end - beg;
  3339. if (!key_len) { return false; }
  3340. auto key = std::string(beg, key_end);
  3341. auto val = std::string(p, end);
  3342. if (!detail::fields::is_field_value(val)) { return false; }
  3343. if (case_ignore::equal(key, "Location") ||
  3344. case_ignore::equal(key, "Referer")) {
  3345. fn(key, val);
  3346. } else {
  3347. fn(key, decode_path_component(val));
  3348. }
  3349. return true;
  3350. }
  3351. return false;
  3352. }
  3353. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3354. const Headers &src_headers) {
  3355. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3356. // transfer coding is complete when a chunk with a chunk-size of zero is
  3357. // received, possibly followed by a trailer section, and finally terminated by
  3358. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3359. //
  3360. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3361. // doesn't care for the existence of the final CRLF. In other words, it seems
  3362. // to be ok whether the final CRLF exists or not in the chunked data.
  3363. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3364. //
  3365. // According to the reference code in RFC 9112, cpp-httplib now allows
  3366. // chunked transfer coding data without the final CRLF.
  3367. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3368. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3369. "transfer-encoding",
  3370. "content-length",
  3371. "host",
  3372. "authorization",
  3373. "www-authenticate",
  3374. "proxy-authenticate",
  3375. "proxy-authorization",
  3376. "cookie",
  3377. "set-cookie",
  3378. "cache-control",
  3379. "expect",
  3380. "max-forwards",
  3381. "pragma",
  3382. "range",
  3383. "te",
  3384. "age",
  3385. "expires",
  3386. "date",
  3387. "location",
  3388. "retry-after",
  3389. "vary",
  3390. "warning",
  3391. "content-encoding",
  3392. "content-type",
  3393. "content-range",
  3394. "trailer"};
  3395. case_ignore::unordered_set<std::string> declared_trailers;
  3396. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  3397. if (trailer_header && std::strlen(trailer_header)) {
  3398. auto len = std::strlen(trailer_header);
  3399. split(trailer_header, trailer_header + len, ',',
  3400. [&](const char *b, const char *e) {
  3401. const char *kbeg = b;
  3402. const char *kend = e;
  3403. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  3404. ++kbeg;
  3405. }
  3406. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  3407. --kend;
  3408. }
  3409. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  3410. if (!key.empty() &&
  3411. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  3412. declared_trailers.insert(key);
  3413. }
  3414. });
  3415. }
  3416. size_t trailer_header_count = 0;
  3417. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3418. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3419. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3420. constexpr auto line_terminator_len = 2;
  3421. auto line_beg = line_reader.ptr();
  3422. auto line_end =
  3423. line_reader.ptr() + line_reader.size() - line_terminator_len;
  3424. if (!parse_header(line_beg, line_end,
  3425. [&](const std::string &key, const std::string &val) {
  3426. if (declared_trailers.find(key) !=
  3427. declared_trailers.end()) {
  3428. dest.emplace(key, val);
  3429. trailer_header_count++;
  3430. }
  3431. })) {
  3432. return false;
  3433. }
  3434. if (!line_reader.getline()) { return false; }
  3435. }
  3436. return true;
  3437. }
  3438. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  3439. size_t right) {
  3440. while (b + left < e && is_space_or_tab(b[left])) {
  3441. left++;
  3442. }
  3443. while (right > 0 && is_space_or_tab(b[right - 1])) {
  3444. right--;
  3445. }
  3446. return std::make_pair(left, right);
  3447. }
  3448. inline std::string trim_copy(const std::string &s) {
  3449. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  3450. return s.substr(r.first, r.second - r.first);
  3451. }
  3452. inline std::string trim_double_quotes_copy(const std::string &s) {
  3453. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  3454. return s.substr(1, s.size() - 2);
  3455. }
  3456. return s;
  3457. }
  3458. inline void
  3459. divide(const char *data, std::size_t size, char d,
  3460. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3461. fn) {
  3462. const auto it = std::find(data, data + size, d);
  3463. const auto found = static_cast<std::size_t>(it != data + size);
  3464. const auto lhs_data = data;
  3465. const auto lhs_size = static_cast<std::size_t>(it - data);
  3466. const auto rhs_data = it + found;
  3467. const auto rhs_size = size - lhs_size - found;
  3468. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  3469. }
  3470. inline void
  3471. divide(const std::string &str, char d,
  3472. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3473. fn) {
  3474. divide(str.data(), str.size(), d, std::move(fn));
  3475. }
  3476. inline void split(const char *b, const char *e, char d,
  3477. std::function<void(const char *, const char *)> fn) {
  3478. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  3479. }
  3480. inline void split(const char *b, const char *e, char d, size_t m,
  3481. std::function<void(const char *, const char *)> fn) {
  3482. size_t i = 0;
  3483. size_t beg = 0;
  3484. size_t count = 1;
  3485. while (e ? (b + i < e) : (b[i] != '\0')) {
  3486. if (b[i] == d && count < m) {
  3487. auto r = trim(b, e, beg, i);
  3488. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3489. beg = i + 1;
  3490. count++;
  3491. }
  3492. i++;
  3493. }
  3494. if (i) {
  3495. auto r = trim(b, e, beg, i);
  3496. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3497. }
  3498. }
  3499. inline bool split_find(const char *b, const char *e, char d, size_t m,
  3500. std::function<bool(const char *, const char *)> fn) {
  3501. size_t i = 0;
  3502. size_t beg = 0;
  3503. size_t count = 1;
  3504. while (e ? (b + i < e) : (b[i] != '\0')) {
  3505. if (b[i] == d && count < m) {
  3506. auto r = trim(b, e, beg, i);
  3507. if (r.first < r.second) {
  3508. auto found = fn(&b[r.first], &b[r.second]);
  3509. if (found) { return true; }
  3510. }
  3511. beg = i + 1;
  3512. count++;
  3513. }
  3514. i++;
  3515. }
  3516. if (i) {
  3517. auto r = trim(b, e, beg, i);
  3518. if (r.first < r.second) {
  3519. auto found = fn(&b[r.first], &b[r.second]);
  3520. if (found) { return true; }
  3521. }
  3522. }
  3523. return false;
  3524. }
  3525. inline bool split_find(const char *b, const char *e, char d,
  3526. std::function<bool(const char *, const char *)> fn) {
  3527. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  3528. std::move(fn));
  3529. }
  3530. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  3531. size_t fixed_buffer_size)
  3532. : strm_(strm), fixed_buffer_(fixed_buffer),
  3533. fixed_buffer_size_(fixed_buffer_size) {}
  3534. inline const char *stream_line_reader::ptr() const {
  3535. if (growable_buffer_.empty()) {
  3536. return fixed_buffer_;
  3537. } else {
  3538. return growable_buffer_.data();
  3539. }
  3540. }
  3541. inline size_t stream_line_reader::size() const {
  3542. if (growable_buffer_.empty()) {
  3543. return fixed_buffer_used_size_;
  3544. } else {
  3545. return growable_buffer_.size();
  3546. }
  3547. }
  3548. inline bool stream_line_reader::end_with_crlf() const {
  3549. auto end = ptr() + size();
  3550. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  3551. }
  3552. inline bool stream_line_reader::getline() {
  3553. fixed_buffer_used_size_ = 0;
  3554. growable_buffer_.clear();
  3555. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3556. char prev_byte = 0;
  3557. #endif
  3558. for (size_t i = 0;; i++) {
  3559. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  3560. // Treat exceptionally long lines as an error to
  3561. // prevent infinite loops/memory exhaustion
  3562. return false;
  3563. }
  3564. char byte;
  3565. auto n = strm_.read(&byte, 1);
  3566. if (n < 0) {
  3567. return false;
  3568. } else if (n == 0) {
  3569. if (i == 0) {
  3570. return false;
  3571. } else {
  3572. break;
  3573. }
  3574. }
  3575. append(byte);
  3576. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3577. if (byte == '\n') { break; }
  3578. #else
  3579. if (prev_byte == '\r' && byte == '\n') { break; }
  3580. prev_byte = byte;
  3581. #endif
  3582. }
  3583. return true;
  3584. }
  3585. inline void stream_line_reader::append(char c) {
  3586. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  3587. fixed_buffer_[fixed_buffer_used_size_++] = c;
  3588. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  3589. } else {
  3590. if (growable_buffer_.empty()) {
  3591. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  3592. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  3593. }
  3594. growable_buffer_ += c;
  3595. }
  3596. }
  3597. inline mmap::mmap(const char *path) { open(path); }
  3598. inline mmap::~mmap() { close(); }
  3599. inline bool mmap::open(const char *path) {
  3600. close();
  3601. #if defined(_WIN32)
  3602. auto wpath = u8string_to_wstring(path);
  3603. if (wpath.empty()) { return false; }
  3604. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  3605. OPEN_EXISTING, NULL);
  3606. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  3607. LARGE_INTEGER size{};
  3608. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  3609. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  3610. // See:
  3611. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  3612. if (static_cast<ULONGLONG>(size.QuadPart) >
  3613. (std::numeric_limits<decltype(size_)>::max)()) {
  3614. // `size_t` might be 32-bits, on 32-bits Windows.
  3615. return false;
  3616. }
  3617. size_ = static_cast<size_t>(size.QuadPart);
  3618. hMapping_ =
  3619. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  3620. // Special treatment for an empty file...
  3621. if (hMapping_ == NULL && size_ == 0) {
  3622. close();
  3623. is_open_empty_file = true;
  3624. return true;
  3625. }
  3626. if (hMapping_ == NULL) {
  3627. close();
  3628. return false;
  3629. }
  3630. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  3631. if (addr_ == nullptr) {
  3632. close();
  3633. return false;
  3634. }
  3635. #else
  3636. fd_ = ::open(path, O_RDONLY);
  3637. if (fd_ == -1) { return false; }
  3638. struct stat sb;
  3639. if (fstat(fd_, &sb) == -1) {
  3640. close();
  3641. return false;
  3642. }
  3643. size_ = static_cast<size_t>(sb.st_size);
  3644. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  3645. // Special treatment for an empty file...
  3646. if (addr_ == MAP_FAILED && size_ == 0) {
  3647. close();
  3648. is_open_empty_file = true;
  3649. return false;
  3650. }
  3651. #endif
  3652. return true;
  3653. }
  3654. inline bool mmap::is_open() const {
  3655. return is_open_empty_file ? true : addr_ != nullptr;
  3656. }
  3657. inline size_t mmap::size() const { return size_; }
  3658. inline const char *mmap::data() const {
  3659. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  3660. }
  3661. inline void mmap::close() {
  3662. #if defined(_WIN32)
  3663. if (addr_) {
  3664. ::UnmapViewOfFile(addr_);
  3665. addr_ = nullptr;
  3666. }
  3667. if (hMapping_) {
  3668. ::CloseHandle(hMapping_);
  3669. hMapping_ = NULL;
  3670. }
  3671. if (hFile_ != INVALID_HANDLE_VALUE) {
  3672. ::CloseHandle(hFile_);
  3673. hFile_ = INVALID_HANDLE_VALUE;
  3674. }
  3675. is_open_empty_file = false;
  3676. #else
  3677. if (addr_ != nullptr) {
  3678. munmap(addr_, size_);
  3679. addr_ = nullptr;
  3680. }
  3681. if (fd_ != -1) {
  3682. ::close(fd_);
  3683. fd_ = -1;
  3684. }
  3685. #endif
  3686. size_ = 0;
  3687. }
  3688. inline int close_socket(socket_t sock) {
  3689. #ifdef _WIN32
  3690. return closesocket(sock);
  3691. #else
  3692. return close(sock);
  3693. #endif
  3694. }
  3695. template <typename T> inline ssize_t handle_EINTR(T fn) {
  3696. ssize_t res = 0;
  3697. while (true) {
  3698. res = fn();
  3699. if (res < 0 && errno == EINTR) {
  3700. std::this_thread::sleep_for(std::chrono::microseconds{1});
  3701. continue;
  3702. }
  3703. break;
  3704. }
  3705. return res;
  3706. }
  3707. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  3708. return handle_EINTR([&]() {
  3709. return recv(sock,
  3710. #ifdef _WIN32
  3711. static_cast<char *>(ptr), static_cast<int>(size),
  3712. #else
  3713. ptr, size,
  3714. #endif
  3715. flags);
  3716. });
  3717. }
  3718. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  3719. int flags) {
  3720. return handle_EINTR([&]() {
  3721. return send(sock,
  3722. #ifdef _WIN32
  3723. static_cast<const char *>(ptr), static_cast<int>(size),
  3724. #else
  3725. ptr, size,
  3726. #endif
  3727. flags);
  3728. });
  3729. }
  3730. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  3731. #ifdef _WIN32
  3732. return ::WSAPoll(fds, nfds, timeout);
  3733. #else
  3734. return ::poll(fds, nfds, timeout);
  3735. #endif
  3736. }
  3737. template <bool Read>
  3738. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  3739. #ifdef __APPLE__
  3740. if (sock >= FD_SETSIZE) { return -1; }
  3741. fd_set fds, *rfds, *wfds;
  3742. FD_ZERO(&fds);
  3743. FD_SET(sock, &fds);
  3744. rfds = (Read ? &fds : nullptr);
  3745. wfds = (Read ? nullptr : &fds);
  3746. timeval tv;
  3747. tv.tv_sec = static_cast<long>(sec);
  3748. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3749. return handle_EINTR([&]() {
  3750. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  3751. });
  3752. #else
  3753. struct pollfd pfd;
  3754. pfd.fd = sock;
  3755. pfd.events = (Read ? POLLIN : POLLOUT);
  3756. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3757. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  3758. #endif
  3759. }
  3760. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  3761. return select_impl<true>(sock, sec, usec);
  3762. }
  3763. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  3764. return select_impl<false>(sock, sec, usec);
  3765. }
  3766. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  3767. time_t usec) {
  3768. #ifdef __APPLE__
  3769. if (sock >= FD_SETSIZE) { return Error::Connection; }
  3770. fd_set fdsr, fdsw;
  3771. FD_ZERO(&fdsr);
  3772. FD_ZERO(&fdsw);
  3773. FD_SET(sock, &fdsr);
  3774. FD_SET(sock, &fdsw);
  3775. timeval tv;
  3776. tv.tv_sec = static_cast<long>(sec);
  3777. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3778. auto ret = handle_EINTR([&]() {
  3779. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  3780. });
  3781. if (ret == 0) { return Error::ConnectionTimeout; }
  3782. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  3783. auto error = 0;
  3784. socklen_t len = sizeof(error);
  3785. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3786. reinterpret_cast<char *>(&error), &len);
  3787. auto successful = res >= 0 && !error;
  3788. return successful ? Error::Success : Error::Connection;
  3789. }
  3790. return Error::Connection;
  3791. #else
  3792. struct pollfd pfd_read;
  3793. pfd_read.fd = sock;
  3794. pfd_read.events = POLLIN | POLLOUT;
  3795. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3796. auto poll_res =
  3797. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  3798. if (poll_res == 0) { return Error::ConnectionTimeout; }
  3799. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  3800. auto error = 0;
  3801. socklen_t len = sizeof(error);
  3802. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3803. reinterpret_cast<char *>(&error), &len);
  3804. auto successful = res >= 0 && !error;
  3805. return successful ? Error::Success : Error::Connection;
  3806. }
  3807. return Error::Connection;
  3808. #endif
  3809. }
  3810. inline bool is_socket_alive(socket_t sock) {
  3811. const auto val = detail::select_read(sock, 0, 0);
  3812. if (val == 0) {
  3813. return true;
  3814. } else if (val < 0 && errno == EBADF) {
  3815. return false;
  3816. }
  3817. char buf[1];
  3818. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  3819. }
  3820. class SocketStream final : public Stream {
  3821. public:
  3822. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3823. time_t write_timeout_sec, time_t write_timeout_usec,
  3824. time_t max_timeout_msec = 0,
  3825. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3826. (std::chrono::steady_clock::time_point::min)());
  3827. ~SocketStream() override;
  3828. bool is_readable() const override;
  3829. bool wait_readable() const override;
  3830. bool wait_writable() const override;
  3831. ssize_t read(char *ptr, size_t size) override;
  3832. ssize_t write(const char *ptr, size_t size) override;
  3833. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3834. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3835. socket_t socket() const override;
  3836. time_t duration() const override;
  3837. private:
  3838. socket_t sock_;
  3839. time_t read_timeout_sec_;
  3840. time_t read_timeout_usec_;
  3841. time_t write_timeout_sec_;
  3842. time_t write_timeout_usec_;
  3843. time_t max_timeout_msec_;
  3844. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3845. std::vector<char> read_buff_;
  3846. size_t read_buff_off_ = 0;
  3847. size_t read_buff_content_size_ = 0;
  3848. static const size_t read_buff_size_ = 1024l * 4;
  3849. };
  3850. #ifdef CPPHTTPLIB_SSL_ENABLED
  3851. class SSLSocketStream final : public Stream {
  3852. public:
  3853. SSLSocketStream(
  3854. socket_t sock, tls::tls_session_t session, time_t read_timeout_sec,
  3855. time_t read_timeout_usec, time_t write_timeout_sec,
  3856. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  3857. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3858. (std::chrono::steady_clock::time_point::min)());
  3859. ~SSLSocketStream() override;
  3860. bool is_readable() const override;
  3861. bool wait_readable() const override;
  3862. bool wait_writable() const override;
  3863. ssize_t read(char *ptr, size_t size) override;
  3864. ssize_t write(const char *ptr, size_t size) override;
  3865. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3866. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3867. socket_t socket() const override;
  3868. time_t duration() const override;
  3869. private:
  3870. socket_t sock_;
  3871. tls::tls_session_t session_;
  3872. time_t read_timeout_sec_;
  3873. time_t read_timeout_usec_;
  3874. time_t write_timeout_sec_;
  3875. time_t write_timeout_usec_;
  3876. time_t max_timeout_msec_;
  3877. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3878. };
  3879. #endif
  3880. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3881. time_t keep_alive_timeout_sec) {
  3882. using namespace std::chrono;
  3883. const auto interval_usec =
  3884. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  3885. // Avoid expensive `steady_clock::now()` call for the first time
  3886. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  3887. const auto start = steady_clock::now() - microseconds{interval_usec};
  3888. const auto timeout = seconds{keep_alive_timeout_sec};
  3889. while (true) {
  3890. if (svr_sock == INVALID_SOCKET) {
  3891. break; // Server socket is closed
  3892. }
  3893. auto val = select_read(sock, 0, interval_usec);
  3894. if (val < 0) {
  3895. break; // Ssocket error
  3896. } else if (val == 0) {
  3897. if (steady_clock::now() - start > timeout) {
  3898. break; // Timeout
  3899. }
  3900. } else {
  3901. return true; // Ready for read
  3902. }
  3903. }
  3904. return false;
  3905. }
  3906. template <typename T>
  3907. inline bool
  3908. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3909. size_t keep_alive_max_count,
  3910. time_t keep_alive_timeout_sec, T callback) {
  3911. assert(keep_alive_max_count > 0);
  3912. auto ret = false;
  3913. auto count = keep_alive_max_count;
  3914. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  3915. auto close_connection = count == 1;
  3916. auto connection_closed = false;
  3917. ret = callback(close_connection, connection_closed);
  3918. if (!ret || connection_closed) { break; }
  3919. count--;
  3920. }
  3921. return ret;
  3922. }
  3923. template <typename T>
  3924. inline bool
  3925. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3926. size_t keep_alive_max_count,
  3927. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  3928. time_t read_timeout_usec, time_t write_timeout_sec,
  3929. time_t write_timeout_usec, T callback) {
  3930. return process_server_socket_core(
  3931. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  3932. [&](bool close_connection, bool &connection_closed) {
  3933. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3934. write_timeout_sec, write_timeout_usec);
  3935. return callback(strm, close_connection, connection_closed);
  3936. });
  3937. }
  3938. inline bool process_client_socket(
  3939. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3940. time_t write_timeout_sec, time_t write_timeout_usec,
  3941. time_t max_timeout_msec,
  3942. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3943. std::function<bool(Stream &)> callback) {
  3944. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3945. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  3946. start_time);
  3947. return callback(strm);
  3948. }
  3949. inline int shutdown_socket(socket_t sock) {
  3950. #ifdef _WIN32
  3951. return shutdown(sock, SD_BOTH);
  3952. #else
  3953. return shutdown(sock, SHUT_RDWR);
  3954. #endif
  3955. }
  3956. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  3957. if (s.size() > 1 && s[0] == '\0') {
  3958. auto ret = s;
  3959. ret[0] = '@';
  3960. return ret;
  3961. }
  3962. return s;
  3963. }
  3964. inline std::string
  3965. unescape_abstract_namespace_unix_domain(const std::string &s) {
  3966. if (s.size() > 1 && s[0] == '@') {
  3967. auto ret = s;
  3968. ret[0] = '\0';
  3969. return ret;
  3970. }
  3971. return s;
  3972. }
  3973. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  3974. const struct addrinfo *hints,
  3975. struct addrinfo **res, time_t timeout_sec) {
  3976. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  3977. if (timeout_sec <= 0) {
  3978. // No timeout specified, use standard getaddrinfo
  3979. return getaddrinfo(node, service, hints, res);
  3980. }
  3981. #ifdef _WIN32
  3982. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  3983. OVERLAPPED overlapped = {0};
  3984. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  3985. if (!event) { return EAI_FAIL; }
  3986. overlapped.hEvent = event;
  3987. PADDRINFOEXW result_addrinfo = nullptr;
  3988. HANDLE cancel_handle = nullptr;
  3989. ADDRINFOEXW hints_ex = {0};
  3990. if (hints) {
  3991. hints_ex.ai_flags = hints->ai_flags;
  3992. hints_ex.ai_family = hints->ai_family;
  3993. hints_ex.ai_socktype = hints->ai_socktype;
  3994. hints_ex.ai_protocol = hints->ai_protocol;
  3995. }
  3996. auto wnode = u8string_to_wstring(node);
  3997. auto wservice = u8string_to_wstring(service);
  3998. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  3999. hints ? &hints_ex : nullptr, &result_addrinfo,
  4000. nullptr, &overlapped, nullptr, &cancel_handle);
  4001. if (ret == WSA_IO_PENDING) {
  4002. auto wait_result =
  4003. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4004. if (wait_result == WAIT_TIMEOUT) {
  4005. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4006. ::CloseHandle(event);
  4007. return EAI_AGAIN;
  4008. }
  4009. DWORD bytes_returned;
  4010. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4011. &bytes_returned, FALSE)) {
  4012. ::CloseHandle(event);
  4013. return ::WSAGetLastError();
  4014. }
  4015. }
  4016. ::CloseHandle(event);
  4017. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4018. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4019. return 0;
  4020. }
  4021. return ret;
  4022. #elif TARGET_OS_MAC
  4023. if (!node) { return EAI_NONAME; }
  4024. // macOS implementation using CFHost API for asynchronous DNS resolution
  4025. CFStringRef hostname_ref = CFStringCreateWithCString(
  4026. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4027. if (!hostname_ref) { return EAI_MEMORY; }
  4028. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4029. CFRelease(hostname_ref);
  4030. if (!host_ref) { return EAI_MEMORY; }
  4031. // Set up context for callback
  4032. struct CFHostContext {
  4033. bool completed = false;
  4034. bool success = false;
  4035. CFArrayRef addresses = nullptr;
  4036. std::mutex mutex;
  4037. std::condition_variable cv;
  4038. } context;
  4039. CFHostClientContext client_context;
  4040. memset(&client_context, 0, sizeof(client_context));
  4041. client_context.info = &context;
  4042. // Set callback
  4043. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4044. const CFStreamError *error, void *info) {
  4045. auto ctx = static_cast<CFHostContext *>(info);
  4046. std::lock_guard<std::mutex> lock(ctx->mutex);
  4047. if (error && error->error != 0) {
  4048. ctx->success = false;
  4049. } else {
  4050. Boolean hasBeenResolved;
  4051. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4052. if (ctx->addresses && hasBeenResolved) {
  4053. CFRetain(ctx->addresses);
  4054. ctx->success = true;
  4055. } else {
  4056. ctx->success = false;
  4057. }
  4058. }
  4059. ctx->completed = true;
  4060. ctx->cv.notify_one();
  4061. };
  4062. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4063. CFRelease(host_ref);
  4064. return EAI_SYSTEM;
  4065. }
  4066. // Schedule on run loop
  4067. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4068. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4069. // Start resolution
  4070. CFStreamError stream_error;
  4071. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4072. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4073. CFRelease(host_ref);
  4074. return EAI_FAIL;
  4075. }
  4076. // Wait for completion with timeout
  4077. auto timeout_time =
  4078. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4079. bool timed_out = false;
  4080. {
  4081. std::unique_lock<std::mutex> lock(context.mutex);
  4082. while (!context.completed) {
  4083. auto now = std::chrono::steady_clock::now();
  4084. if (now >= timeout_time) {
  4085. timed_out = true;
  4086. break;
  4087. }
  4088. // Run the runloop for a short time
  4089. lock.unlock();
  4090. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4091. lock.lock();
  4092. }
  4093. }
  4094. // Clean up
  4095. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4096. CFHostSetClient(host_ref, nullptr, nullptr);
  4097. if (timed_out || !context.completed) {
  4098. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4099. CFRelease(host_ref);
  4100. return EAI_AGAIN;
  4101. }
  4102. if (!context.success || !context.addresses) {
  4103. CFRelease(host_ref);
  4104. return EAI_NODATA;
  4105. }
  4106. // Convert CFArray to addrinfo
  4107. CFIndex count = CFArrayGetCount(context.addresses);
  4108. if (count == 0) {
  4109. CFRelease(context.addresses);
  4110. CFRelease(host_ref);
  4111. return EAI_NODATA;
  4112. }
  4113. struct addrinfo *result_addrinfo = nullptr;
  4114. struct addrinfo **current = &result_addrinfo;
  4115. for (CFIndex i = 0; i < count; i++) {
  4116. CFDataRef addr_data =
  4117. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4118. if (!addr_data) continue;
  4119. const struct sockaddr *sockaddr_ptr =
  4120. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4121. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4122. // Allocate addrinfo structure
  4123. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4124. if (!*current) {
  4125. freeaddrinfo(result_addrinfo);
  4126. CFRelease(context.addresses);
  4127. CFRelease(host_ref);
  4128. return EAI_MEMORY;
  4129. }
  4130. memset(*current, 0, sizeof(struct addrinfo));
  4131. // Set up addrinfo fields
  4132. (*current)->ai_family = sockaddr_ptr->sa_family;
  4133. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4134. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4135. (*current)->ai_addrlen = sockaddr_len;
  4136. // Copy sockaddr
  4137. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4138. if (!(*current)->ai_addr) {
  4139. freeaddrinfo(result_addrinfo);
  4140. CFRelease(context.addresses);
  4141. CFRelease(host_ref);
  4142. return EAI_MEMORY;
  4143. }
  4144. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4145. // Set port if service is specified
  4146. if (service && strlen(service) > 0) {
  4147. int port = atoi(service);
  4148. if (port > 0) {
  4149. if (sockaddr_ptr->sa_family == AF_INET) {
  4150. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4151. ->sin_port = htons(static_cast<uint16_t>(port));
  4152. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4153. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4154. ->sin6_port = htons(static_cast<uint16_t>(port));
  4155. }
  4156. }
  4157. }
  4158. current = &((*current)->ai_next);
  4159. }
  4160. CFRelease(context.addresses);
  4161. CFRelease(host_ref);
  4162. *res = result_addrinfo;
  4163. return 0;
  4164. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  4165. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  4166. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  4167. struct gaicb request;
  4168. struct gaicb *requests[1] = {&request};
  4169. struct sigevent sevp;
  4170. struct timespec timeout;
  4171. // Initialize the request structure
  4172. memset(&request, 0, sizeof(request));
  4173. request.ar_name = node;
  4174. request.ar_service = service;
  4175. request.ar_request = hints;
  4176. // Set up timeout
  4177. timeout.tv_sec = timeout_sec;
  4178. timeout.tv_nsec = 0;
  4179. // Initialize sigevent structure (not used, but required)
  4180. memset(&sevp, 0, sizeof(sevp));
  4181. sevp.sigev_notify = SIGEV_NONE;
  4182. // Start asynchronous resolution
  4183. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  4184. if (start_result != 0) { return start_result; }
  4185. // Wait for completion with timeout
  4186. int wait_result =
  4187. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  4188. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  4189. // Completed successfully, get the result
  4190. int gai_result = gai_error(&request);
  4191. if (gai_result == 0) {
  4192. *res = request.ar_result;
  4193. return 0;
  4194. } else {
  4195. // Clean up on error
  4196. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  4197. return gai_result;
  4198. }
  4199. } else if (wait_result == EAI_AGAIN) {
  4200. // Timeout occurred, cancel the request
  4201. gai_cancel(&request);
  4202. return EAI_AGAIN;
  4203. } else {
  4204. // Other error occurred
  4205. gai_cancel(&request);
  4206. return wait_result;
  4207. }
  4208. #else
  4209. // Fallback implementation using thread-based timeout for other Unix systems
  4210. struct GetAddrInfoState {
  4211. ~GetAddrInfoState() {
  4212. if (info) { freeaddrinfo(info); }
  4213. }
  4214. std::mutex mutex;
  4215. std::condition_variable result_cv;
  4216. bool completed = false;
  4217. int result = EAI_SYSTEM;
  4218. std::string node;
  4219. std::string service;
  4220. struct addrinfo hints;
  4221. struct addrinfo *info = nullptr;
  4222. };
  4223. // Allocate on the heap, so the resolver thread can keep using the data.
  4224. auto state = std::make_shared<GetAddrInfoState>();
  4225. if (node) { state->node = node; }
  4226. state->service = service;
  4227. state->hints = *hints;
  4228. std::thread resolve_thread([state]() {
  4229. auto thread_result =
  4230. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4231. &state->info);
  4232. std::lock_guard<std::mutex> lock(state->mutex);
  4233. state->result = thread_result;
  4234. state->completed = true;
  4235. state->result_cv.notify_one();
  4236. });
  4237. // Wait for completion or timeout
  4238. std::unique_lock<std::mutex> lock(state->mutex);
  4239. auto finished =
  4240. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4241. [&] { return state->completed; });
  4242. if (finished) {
  4243. // Operation completed within timeout
  4244. resolve_thread.join();
  4245. *res = state->info;
  4246. state->info = nullptr; // Pass ownership to caller
  4247. return state->result;
  4248. } else {
  4249. // Timeout occurred
  4250. resolve_thread.detach(); // Let the thread finish in background
  4251. return EAI_AGAIN; // Return timeout error
  4252. }
  4253. #endif
  4254. #else
  4255. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4256. return getaddrinfo(node, service, hints, res);
  4257. #endif
  4258. }
  4259. template <typename BindOrConnect>
  4260. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4261. int address_family, int socket_flags, bool tcp_nodelay,
  4262. bool ipv6_v6only, SocketOptions socket_options,
  4263. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4264. // Get address info
  4265. const char *node = nullptr;
  4266. struct addrinfo hints;
  4267. struct addrinfo *result;
  4268. memset(&hints, 0, sizeof(struct addrinfo));
  4269. hints.ai_socktype = SOCK_STREAM;
  4270. hints.ai_protocol = IPPROTO_IP;
  4271. if (!ip.empty()) {
  4272. node = ip.c_str();
  4273. // Ask getaddrinfo to convert IP in c-string to address
  4274. hints.ai_family = AF_UNSPEC;
  4275. hints.ai_flags = AI_NUMERICHOST;
  4276. } else {
  4277. if (!host.empty()) { node = host.c_str(); }
  4278. hints.ai_family = address_family;
  4279. hints.ai_flags = socket_flags;
  4280. }
  4281. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  4282. if (hints.ai_family == AF_UNIX) {
  4283. const auto addrlen = host.length();
  4284. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  4285. #ifdef SOCK_CLOEXEC
  4286. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  4287. hints.ai_protocol);
  4288. #else
  4289. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4290. #endif
  4291. if (sock != INVALID_SOCKET) {
  4292. sockaddr_un addr{};
  4293. addr.sun_family = AF_UNIX;
  4294. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  4295. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  4296. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  4297. hints.ai_addrlen = static_cast<socklen_t>(
  4298. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  4299. #ifndef SOCK_CLOEXEC
  4300. #ifndef _WIN32
  4301. fcntl(sock, F_SETFD, FD_CLOEXEC);
  4302. #endif
  4303. #endif
  4304. if (socket_options) { socket_options(sock); }
  4305. #ifdef _WIN32
  4306. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  4307. // remove the option.
  4308. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  4309. #endif
  4310. bool dummy;
  4311. if (!bind_or_connect(sock, hints, dummy)) {
  4312. close_socket(sock);
  4313. sock = INVALID_SOCKET;
  4314. }
  4315. }
  4316. return sock;
  4317. }
  4318. #endif
  4319. auto service = std::to_string(port);
  4320. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  4321. timeout_sec)) {
  4322. #if defined __linux__ && !defined __ANDROID__
  4323. res_init();
  4324. #endif
  4325. return INVALID_SOCKET;
  4326. }
  4327. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4328. for (auto rp = result; rp; rp = rp->ai_next) {
  4329. // Create a socket
  4330. #ifdef _WIN32
  4331. auto sock =
  4332. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  4333. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  4334. /**
  4335. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  4336. * and above the socket creation fails on older Windows Systems.
  4337. *
  4338. * Let's try to create a socket the old way in this case.
  4339. *
  4340. * Reference:
  4341. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  4342. *
  4343. * WSA_FLAG_NO_HANDLE_INHERIT:
  4344. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  4345. * SP1, and later
  4346. *
  4347. */
  4348. if (sock == INVALID_SOCKET) {
  4349. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4350. }
  4351. #else
  4352. #ifdef SOCK_CLOEXEC
  4353. auto sock =
  4354. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  4355. #else
  4356. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4357. #endif
  4358. #endif
  4359. if (sock == INVALID_SOCKET) { continue; }
  4360. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  4361. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  4362. close_socket(sock);
  4363. continue;
  4364. }
  4365. #endif
  4366. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  4367. if (rp->ai_family == AF_INET6) {
  4368. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  4369. }
  4370. if (socket_options) { socket_options(sock); }
  4371. // bind or connect
  4372. auto quit = false;
  4373. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  4374. close_socket(sock);
  4375. if (quit) { break; }
  4376. }
  4377. return INVALID_SOCKET;
  4378. }
  4379. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  4380. #ifdef _WIN32
  4381. auto flags = nonblocking ? 1UL : 0UL;
  4382. ioctlsocket(sock, FIONBIO, &flags);
  4383. #else
  4384. auto flags = fcntl(sock, F_GETFL, 0);
  4385. fcntl(sock, F_SETFL,
  4386. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  4387. #endif
  4388. }
  4389. inline bool is_connection_error() {
  4390. #ifdef _WIN32
  4391. return WSAGetLastError() != WSAEWOULDBLOCK;
  4392. #else
  4393. return errno != EINPROGRESS;
  4394. #endif
  4395. }
  4396. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  4397. struct addrinfo hints;
  4398. struct addrinfo *result;
  4399. memset(&hints, 0, sizeof(struct addrinfo));
  4400. hints.ai_family = AF_UNSPEC;
  4401. hints.ai_socktype = SOCK_STREAM;
  4402. hints.ai_protocol = 0;
  4403. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  4404. return false;
  4405. }
  4406. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4407. auto ret = false;
  4408. for (auto rp = result; rp; rp = rp->ai_next) {
  4409. const auto &ai = *rp;
  4410. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4411. ret = true;
  4412. break;
  4413. }
  4414. }
  4415. return ret;
  4416. }
  4417. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  4418. #define USE_IF2IP
  4419. #endif
  4420. #ifdef USE_IF2IP
  4421. inline std::string if2ip(int address_family, const std::string &ifn) {
  4422. struct ifaddrs *ifap;
  4423. getifaddrs(&ifap);
  4424. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  4425. std::string addr_candidate;
  4426. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  4427. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  4428. (AF_UNSPEC == address_family ||
  4429. ifa->ifa_addr->sa_family == address_family)) {
  4430. if (ifa->ifa_addr->sa_family == AF_INET) {
  4431. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  4432. char buf[INET_ADDRSTRLEN];
  4433. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  4434. return std::string(buf, INET_ADDRSTRLEN);
  4435. }
  4436. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  4437. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  4438. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  4439. char buf[INET6_ADDRSTRLEN] = {};
  4440. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  4441. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  4442. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  4443. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  4444. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  4445. } else {
  4446. return std::string(buf, INET6_ADDRSTRLEN);
  4447. }
  4448. }
  4449. }
  4450. }
  4451. }
  4452. }
  4453. return addr_candidate;
  4454. }
  4455. #endif
  4456. inline socket_t create_client_socket(
  4457. const std::string &host, const std::string &ip, int port,
  4458. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  4459. SocketOptions socket_options, time_t connection_timeout_sec,
  4460. time_t connection_timeout_usec, time_t read_timeout_sec,
  4461. time_t read_timeout_usec, time_t write_timeout_sec,
  4462. time_t write_timeout_usec, const std::string &intf, Error &error) {
  4463. auto sock = create_socket(
  4464. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  4465. std::move(socket_options),
  4466. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  4467. if (!intf.empty()) {
  4468. #ifdef USE_IF2IP
  4469. auto ip_from_if = if2ip(address_family, intf);
  4470. if (ip_from_if.empty()) { ip_from_if = intf; }
  4471. if (!bind_ip_address(sock2, ip_from_if)) {
  4472. error = Error::BindIPAddress;
  4473. return false;
  4474. }
  4475. #endif
  4476. }
  4477. set_nonblocking(sock2, true);
  4478. auto ret =
  4479. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  4480. if (ret < 0) {
  4481. if (is_connection_error()) {
  4482. error = Error::Connection;
  4483. return false;
  4484. }
  4485. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  4486. connection_timeout_usec);
  4487. if (error != Error::Success) {
  4488. if (error == Error::ConnectionTimeout) { quit = true; }
  4489. return false;
  4490. }
  4491. }
  4492. set_nonblocking(sock2, false);
  4493. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  4494. read_timeout_usec);
  4495. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  4496. write_timeout_usec);
  4497. error = Error::Success;
  4498. return true;
  4499. },
  4500. connection_timeout_sec); // Pass DNS timeout
  4501. if (sock != INVALID_SOCKET) {
  4502. error = Error::Success;
  4503. } else {
  4504. if (error == Error::Success) { error = Error::Connection; }
  4505. }
  4506. return sock;
  4507. }
  4508. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  4509. socklen_t addr_len, std::string &ip, int &port) {
  4510. if (addr.ss_family == AF_INET) {
  4511. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  4512. } else if (addr.ss_family == AF_INET6) {
  4513. port =
  4514. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  4515. } else {
  4516. return false;
  4517. }
  4518. std::array<char, NI_MAXHOST> ipstr{};
  4519. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  4520. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  4521. 0, NI_NUMERICHOST)) {
  4522. return false;
  4523. }
  4524. ip = ipstr.data();
  4525. return true;
  4526. }
  4527. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4528. struct sockaddr_storage addr;
  4529. socklen_t addr_len = sizeof(addr);
  4530. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4531. &addr_len)) {
  4532. get_ip_and_port(addr, addr_len, ip, port);
  4533. }
  4534. }
  4535. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4536. struct sockaddr_storage addr;
  4537. socklen_t addr_len = sizeof(addr);
  4538. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4539. &addr_len)) {
  4540. #ifndef _WIN32
  4541. if (addr.ss_family == AF_UNIX) {
  4542. #if defined(__linux__)
  4543. struct ucred ucred;
  4544. socklen_t len = sizeof(ucred);
  4545. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  4546. port = ucred.pid;
  4547. }
  4548. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  4549. pid_t pid;
  4550. socklen_t len = sizeof(pid);
  4551. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  4552. port = pid;
  4553. }
  4554. #endif
  4555. return;
  4556. }
  4557. #endif
  4558. get_ip_and_port(addr, addr_len, ip, port);
  4559. }
  4560. }
  4561. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  4562. unsigned int h) {
  4563. return (l == 0)
  4564. ? h
  4565. : str2tag_core(
  4566. s + 1, l - 1,
  4567. // Unsets the 6 high bits of h, therefore no overflow happens
  4568. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  4569. h * 33) ^
  4570. static_cast<unsigned char>(*s));
  4571. }
  4572. inline unsigned int str2tag(const std::string &s) {
  4573. return str2tag_core(s.data(), s.size(), 0);
  4574. }
  4575. namespace udl {
  4576. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  4577. return str2tag_core(s, l, 0);
  4578. }
  4579. } // namespace udl
  4580. inline std::string
  4581. find_content_type(const std::string &path,
  4582. const std::map<std::string, std::string> &user_data,
  4583. const std::string &default_content_type) {
  4584. auto ext = file_extension(path);
  4585. auto it = user_data.find(ext);
  4586. if (it != user_data.end()) { return it->second; }
  4587. using udl::operator""_t;
  4588. switch (str2tag(ext)) {
  4589. default: return default_content_type;
  4590. case "css"_t: return "text/css";
  4591. case "csv"_t: return "text/csv";
  4592. case "htm"_t:
  4593. case "html"_t: return "text/html";
  4594. case "js"_t:
  4595. case "mjs"_t: return "text/javascript";
  4596. case "txt"_t: return "text/plain";
  4597. case "vtt"_t: return "text/vtt";
  4598. case "apng"_t: return "image/apng";
  4599. case "avif"_t: return "image/avif";
  4600. case "bmp"_t: return "image/bmp";
  4601. case "gif"_t: return "image/gif";
  4602. case "png"_t: return "image/png";
  4603. case "svg"_t: return "image/svg+xml";
  4604. case "webp"_t: return "image/webp";
  4605. case "ico"_t: return "image/x-icon";
  4606. case "tif"_t: return "image/tiff";
  4607. case "tiff"_t: return "image/tiff";
  4608. case "jpg"_t:
  4609. case "jpeg"_t: return "image/jpeg";
  4610. case "mp4"_t: return "video/mp4";
  4611. case "mpeg"_t: return "video/mpeg";
  4612. case "webm"_t: return "video/webm";
  4613. case "mp3"_t: return "audio/mp3";
  4614. case "mpga"_t: return "audio/mpeg";
  4615. case "weba"_t: return "audio/webm";
  4616. case "wav"_t: return "audio/wave";
  4617. case "otf"_t: return "font/otf";
  4618. case "ttf"_t: return "font/ttf";
  4619. case "woff"_t: return "font/woff";
  4620. case "woff2"_t: return "font/woff2";
  4621. case "7z"_t: return "application/x-7z-compressed";
  4622. case "atom"_t: return "application/atom+xml";
  4623. case "pdf"_t: return "application/pdf";
  4624. case "json"_t: return "application/json";
  4625. case "rss"_t: return "application/rss+xml";
  4626. case "tar"_t: return "application/x-tar";
  4627. case "xht"_t:
  4628. case "xhtml"_t: return "application/xhtml+xml";
  4629. case "xslt"_t: return "application/xslt+xml";
  4630. case "xml"_t: return "application/xml";
  4631. case "gz"_t: return "application/gzip";
  4632. case "zip"_t: return "application/zip";
  4633. case "wasm"_t: return "application/wasm";
  4634. }
  4635. }
  4636. inline bool can_compress_content_type(const std::string &content_type) {
  4637. using udl::operator""_t;
  4638. auto tag = str2tag(content_type);
  4639. switch (tag) {
  4640. case "image/svg+xml"_t:
  4641. case "application/javascript"_t:
  4642. case "application/json"_t:
  4643. case "application/xml"_t:
  4644. case "application/protobuf"_t:
  4645. case "application/xhtml+xml"_t: return true;
  4646. case "text/event-stream"_t: return false;
  4647. default: return !content_type.rfind("text/", 0);
  4648. }
  4649. }
  4650. inline EncodingType encoding_type(const Request &req, const Response &res) {
  4651. auto ret =
  4652. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  4653. if (!ret) { return EncodingType::None; }
  4654. const auto &s = req.get_header_value("Accept-Encoding");
  4655. (void)(s);
  4656. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4657. // TODO: 'Accept-Encoding' has br, not br;q=0
  4658. ret = s.find("br") != std::string::npos;
  4659. if (ret) { return EncodingType::Brotli; }
  4660. #endif
  4661. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4662. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  4663. ret = s.find("gzip") != std::string::npos;
  4664. if (ret) { return EncodingType::Gzip; }
  4665. #endif
  4666. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4667. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  4668. ret = s.find("zstd") != std::string::npos;
  4669. if (ret) { return EncodingType::Zstd; }
  4670. #endif
  4671. return EncodingType::None;
  4672. }
  4673. inline bool nocompressor::compress(const char *data, size_t data_length,
  4674. bool /*last*/, Callback callback) {
  4675. if (!data_length) { return true; }
  4676. return callback(data, data_length);
  4677. }
  4678. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4679. inline gzip_compressor::gzip_compressor() {
  4680. std::memset(&strm_, 0, sizeof(strm_));
  4681. strm_.zalloc = Z_NULL;
  4682. strm_.zfree = Z_NULL;
  4683. strm_.opaque = Z_NULL;
  4684. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  4685. Z_DEFAULT_STRATEGY) == Z_OK;
  4686. }
  4687. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  4688. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  4689. bool last, Callback callback) {
  4690. assert(is_valid_);
  4691. do {
  4692. constexpr size_t max_avail_in =
  4693. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4694. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4695. (std::min)(data_length, max_avail_in));
  4696. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4697. data_length -= strm_.avail_in;
  4698. data += strm_.avail_in;
  4699. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  4700. auto ret = Z_OK;
  4701. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4702. do {
  4703. strm_.avail_out = static_cast<uInt>(buff.size());
  4704. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4705. ret = deflate(&strm_, flush);
  4706. if (ret == Z_STREAM_ERROR) { return false; }
  4707. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4708. return false;
  4709. }
  4710. } while (strm_.avail_out == 0);
  4711. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  4712. (flush == Z_NO_FLUSH && ret == Z_OK));
  4713. assert(strm_.avail_in == 0);
  4714. } while (data_length > 0);
  4715. return true;
  4716. }
  4717. inline gzip_decompressor::gzip_decompressor() {
  4718. std::memset(&strm_, 0, sizeof(strm_));
  4719. strm_.zalloc = Z_NULL;
  4720. strm_.zfree = Z_NULL;
  4721. strm_.opaque = Z_NULL;
  4722. // 15 is the value of wbits, which should be at the maximum possible value
  4723. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  4724. // that the stream type should be automatically detected either gzip or
  4725. // deflate.
  4726. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  4727. }
  4728. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  4729. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  4730. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  4731. Callback callback) {
  4732. assert(is_valid_);
  4733. auto ret = Z_OK;
  4734. do {
  4735. constexpr size_t max_avail_in =
  4736. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4737. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4738. (std::min)(data_length, max_avail_in));
  4739. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4740. data_length -= strm_.avail_in;
  4741. data += strm_.avail_in;
  4742. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4743. while (strm_.avail_in > 0 && ret == Z_OK) {
  4744. strm_.avail_out = static_cast<uInt>(buff.size());
  4745. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4746. ret = inflate(&strm_, Z_NO_FLUSH);
  4747. assert(ret != Z_STREAM_ERROR);
  4748. switch (ret) {
  4749. case Z_NEED_DICT:
  4750. case Z_DATA_ERROR:
  4751. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  4752. }
  4753. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4754. return false;
  4755. }
  4756. }
  4757. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  4758. } while (data_length > 0);
  4759. return true;
  4760. }
  4761. #endif
  4762. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4763. inline brotli_compressor::brotli_compressor() {
  4764. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  4765. }
  4766. inline brotli_compressor::~brotli_compressor() {
  4767. BrotliEncoderDestroyInstance(state_);
  4768. }
  4769. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  4770. bool last, Callback callback) {
  4771. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4772. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  4773. auto available_in = data_length;
  4774. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4775. for (;;) {
  4776. if (last) {
  4777. if (BrotliEncoderIsFinished(state_)) { break; }
  4778. } else {
  4779. if (!available_in) { break; }
  4780. }
  4781. auto available_out = buff.size();
  4782. auto next_out = buff.data();
  4783. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  4784. &available_out, &next_out, nullptr)) {
  4785. return false;
  4786. }
  4787. auto output_bytes = buff.size() - available_out;
  4788. if (output_bytes) {
  4789. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  4790. }
  4791. }
  4792. return true;
  4793. }
  4794. inline brotli_decompressor::brotli_decompressor() {
  4795. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  4796. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  4797. : BROTLI_DECODER_RESULT_ERROR;
  4798. }
  4799. inline brotli_decompressor::~brotli_decompressor() {
  4800. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  4801. }
  4802. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  4803. inline bool brotli_decompressor::decompress(const char *data,
  4804. size_t data_length,
  4805. Callback callback) {
  4806. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4807. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  4808. return 0;
  4809. }
  4810. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4811. size_t avail_in = data_length;
  4812. size_t total_out;
  4813. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  4814. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4815. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  4816. char *next_out = buff.data();
  4817. size_t avail_out = buff.size();
  4818. decoder_r = BrotliDecoderDecompressStream(
  4819. decoder_s, &avail_in, &next_in, &avail_out,
  4820. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  4821. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  4822. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  4823. }
  4824. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4825. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  4826. }
  4827. #endif
  4828. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4829. inline zstd_compressor::zstd_compressor() {
  4830. ctx_ = ZSTD_createCCtx();
  4831. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  4832. }
  4833. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  4834. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  4835. bool last, Callback callback) {
  4836. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4837. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  4838. ZSTD_inBuffer input = {data, data_length, 0};
  4839. bool finished;
  4840. do {
  4841. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4842. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  4843. if (ZSTD_isError(remaining)) { return false; }
  4844. if (!callback(buff.data(), output.pos)) { return false; }
  4845. finished = last ? (remaining == 0) : (input.pos == input.size);
  4846. } while (!finished);
  4847. return true;
  4848. }
  4849. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  4850. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  4851. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  4852. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  4853. Callback callback) {
  4854. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4855. ZSTD_inBuffer input = {data, data_length, 0};
  4856. while (input.pos < input.size) {
  4857. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4858. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  4859. if (ZSTD_isError(remaining)) { return false; }
  4860. if (!callback(buff.data(), output.pos)) { return false; }
  4861. }
  4862. return true;
  4863. }
  4864. #endif
  4865. inline std::unique_ptr<decompressor>
  4866. create_decompressor(const std::string &encoding) {
  4867. std::unique_ptr<decompressor> decompressor;
  4868. if (encoding == "gzip" || encoding == "deflate") {
  4869. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4870. decompressor = detail::make_unique<gzip_decompressor>();
  4871. #endif
  4872. } else if (encoding.find("br") != std::string::npos) {
  4873. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4874. decompressor = detail::make_unique<brotli_decompressor>();
  4875. #endif
  4876. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  4877. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4878. decompressor = detail::make_unique<zstd_decompressor>();
  4879. #endif
  4880. }
  4881. return decompressor;
  4882. }
  4883. inline bool is_prohibited_header_name(const std::string &name) {
  4884. using udl::operator""_t;
  4885. switch (str2tag(name)) {
  4886. case "REMOTE_ADDR"_t:
  4887. case "REMOTE_PORT"_t:
  4888. case "LOCAL_ADDR"_t:
  4889. case "LOCAL_PORT"_t: return true;
  4890. default: return false;
  4891. }
  4892. }
  4893. inline bool has_header(const Headers &headers, const std::string &key) {
  4894. if (is_prohibited_header_name(key)) { return false; }
  4895. return headers.find(key) != headers.end();
  4896. }
  4897. inline const char *get_header_value(const Headers &headers,
  4898. const std::string &key, const char *def,
  4899. size_t id) {
  4900. if (is_prohibited_header_name(key)) {
  4901. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4902. std::string msg = "Prohibited header name '" + key + "' is specified.";
  4903. throw std::invalid_argument(msg);
  4904. #else
  4905. return "";
  4906. #endif
  4907. }
  4908. auto rng = headers.equal_range(key);
  4909. auto it = rng.first;
  4910. std::advance(it, static_cast<ssize_t>(id));
  4911. if (it != rng.second) { return it->second.c_str(); }
  4912. return def;
  4913. }
  4914. inline bool read_headers(Stream &strm, Headers &headers) {
  4915. const auto bufsiz = 2048;
  4916. char buf[bufsiz];
  4917. stream_line_reader line_reader(strm, buf, bufsiz);
  4918. size_t header_count = 0;
  4919. for (;;) {
  4920. if (!line_reader.getline()) { return false; }
  4921. // Check if the line ends with CRLF.
  4922. auto line_terminator_len = 2;
  4923. if (line_reader.end_with_crlf()) {
  4924. // Blank line indicates end of headers.
  4925. if (line_reader.size() == 2) { break; }
  4926. } else {
  4927. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4928. // Blank line indicates end of headers.
  4929. if (line_reader.size() == 1) { break; }
  4930. line_terminator_len = 1;
  4931. #else
  4932. continue; // Skip invalid line.
  4933. #endif
  4934. }
  4935. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4936. // Check header count limit
  4937. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4938. // Exclude line terminator
  4939. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  4940. if (!parse_header(line_reader.ptr(), end,
  4941. [&](const std::string &key, const std::string &val) {
  4942. headers.emplace(key, val);
  4943. })) {
  4944. return false;
  4945. }
  4946. header_count++;
  4947. }
  4948. return true;
  4949. }
  4950. inline bool read_content_with_length(Stream &strm, size_t len,
  4951. DownloadProgress progress,
  4952. ContentReceiverWithProgress out) {
  4953. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4954. detail::BodyReader br;
  4955. br.stream = &strm;
  4956. br.content_length = len;
  4957. br.chunked = false;
  4958. br.bytes_read = 0;
  4959. br.last_error = Error::Success;
  4960. size_t r = 0;
  4961. while (r < len) {
  4962. auto read_len = static_cast<size_t>(len - r);
  4963. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  4964. auto n = detail::read_body_content(&strm, br, buf, to_read);
  4965. if (n <= 0) { return false; }
  4966. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  4967. r += static_cast<size_t>(n);
  4968. if (progress) {
  4969. if (!progress(r, len)) { return false; }
  4970. }
  4971. }
  4972. return true;
  4973. }
  4974. inline void skip_content_with_length(Stream &strm, size_t len) {
  4975. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4976. size_t r = 0;
  4977. while (r < len) {
  4978. auto read_len = static_cast<size_t>(len - r);
  4979. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  4980. if (n <= 0) { return; }
  4981. r += static_cast<size_t>(n);
  4982. }
  4983. }
  4984. enum class ReadContentResult {
  4985. Success, // Successfully read the content
  4986. PayloadTooLarge, // The content exceeds the specified payload limit
  4987. Error // An error occurred while reading the content
  4988. };
  4989. inline ReadContentResult
  4990. read_content_without_length(Stream &strm, size_t payload_max_length,
  4991. ContentReceiverWithProgress out) {
  4992. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4993. size_t r = 0;
  4994. for (;;) {
  4995. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  4996. if (n == 0) { return ReadContentResult::Success; }
  4997. if (n < 0) { return ReadContentResult::Error; }
  4998. // Check if adding this data would exceed the payload limit
  4999. if (r > payload_max_length ||
  5000. payload_max_length - r < static_cast<size_t>(n)) {
  5001. return ReadContentResult::PayloadTooLarge;
  5002. }
  5003. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  5004. return ReadContentResult::Error;
  5005. }
  5006. r += static_cast<size_t>(n);
  5007. }
  5008. return ReadContentResult::Success;
  5009. }
  5010. template <typename T>
  5011. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  5012. size_t payload_max_length,
  5013. ContentReceiverWithProgress out) {
  5014. detail::ChunkedDecoder dec(strm);
  5015. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5016. size_t total_len = 0;
  5017. for (;;) {
  5018. size_t chunk_offset = 0;
  5019. size_t chunk_total = 0;
  5020. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  5021. if (n < 0) { return ReadContentResult::Error; }
  5022. if (n == 0) {
  5023. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  5024. return ReadContentResult::Error;
  5025. }
  5026. return ReadContentResult::Success;
  5027. }
  5028. if (total_len > payload_max_length ||
  5029. payload_max_length - total_len < static_cast<size_t>(n)) {
  5030. return ReadContentResult::PayloadTooLarge;
  5031. }
  5032. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  5033. return ReadContentResult::Error;
  5034. }
  5035. total_len += static_cast<size_t>(n);
  5036. }
  5037. }
  5038. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  5039. return case_ignore::equal(
  5040. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  5041. }
  5042. template <typename T, typename U>
  5043. bool prepare_content_receiver(T &x, int &status,
  5044. ContentReceiverWithProgress receiver,
  5045. bool decompress, U callback) {
  5046. if (decompress) {
  5047. std::string encoding = x.get_header_value("Content-Encoding");
  5048. std::unique_ptr<decompressor> decompressor;
  5049. if (!encoding.empty()) {
  5050. decompressor = detail::create_decompressor(encoding);
  5051. if (!decompressor) {
  5052. // Unsupported encoding or no support compiled in
  5053. status = StatusCode::UnsupportedMediaType_415;
  5054. return false;
  5055. }
  5056. }
  5057. if (decompressor) {
  5058. if (decompressor->is_valid()) {
  5059. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  5060. size_t off, size_t len) {
  5061. return decompressor->decompress(buf, n,
  5062. [&](const char *buf2, size_t n2) {
  5063. return receiver(buf2, n2, off, len);
  5064. });
  5065. };
  5066. return callback(std::move(out));
  5067. } else {
  5068. status = StatusCode::InternalServerError_500;
  5069. return false;
  5070. }
  5071. }
  5072. }
  5073. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  5074. size_t len) {
  5075. return receiver(buf, n, off, len);
  5076. };
  5077. return callback(std::move(out));
  5078. }
  5079. template <typename T>
  5080. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  5081. DownloadProgress progress,
  5082. ContentReceiverWithProgress receiver, bool decompress) {
  5083. return prepare_content_receiver(
  5084. x, status, std::move(receiver), decompress,
  5085. [&](const ContentReceiverWithProgress &out) {
  5086. auto ret = true;
  5087. auto exceed_payload_max_length = false;
  5088. if (is_chunked_transfer_encoding(x.headers)) {
  5089. auto result = read_content_chunked(strm, x, payload_max_length, out);
  5090. if (result == ReadContentResult::Success) {
  5091. ret = true;
  5092. } else if (result == ReadContentResult::PayloadTooLarge) {
  5093. exceed_payload_max_length = true;
  5094. ret = false;
  5095. } else {
  5096. ret = false;
  5097. }
  5098. } else if (!has_header(x.headers, "Content-Length")) {
  5099. auto result =
  5100. read_content_without_length(strm, payload_max_length, out);
  5101. if (result == ReadContentResult::Success) {
  5102. ret = true;
  5103. } else if (result == ReadContentResult::PayloadTooLarge) {
  5104. exceed_payload_max_length = true;
  5105. ret = false;
  5106. } else {
  5107. ret = false;
  5108. }
  5109. } else {
  5110. auto is_invalid_value = false;
  5111. auto len = get_header_value_u64(x.headers, "Content-Length",
  5112. (std::numeric_limits<size_t>::max)(),
  5113. 0, is_invalid_value);
  5114. if (is_invalid_value) {
  5115. ret = false;
  5116. } else if (len > payload_max_length) {
  5117. exceed_payload_max_length = true;
  5118. skip_content_with_length(strm, len);
  5119. ret = false;
  5120. } else if (len > 0) {
  5121. ret = read_content_with_length(strm, len, std::move(progress), out);
  5122. }
  5123. }
  5124. if (!ret) {
  5125. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  5126. : StatusCode::BadRequest_400;
  5127. }
  5128. return ret;
  5129. });
  5130. }
  5131. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  5132. const std::string &path) {
  5133. std::string s = method;
  5134. s += ' ';
  5135. s += path;
  5136. s += " HTTP/1.1\r\n";
  5137. return strm.write(s.data(), s.size());
  5138. }
  5139. inline ssize_t write_response_line(Stream &strm, int status) {
  5140. std::string s = "HTTP/1.1 ";
  5141. s += std::to_string(status);
  5142. s += ' ';
  5143. s += httplib::status_message(status);
  5144. s += "\r\n";
  5145. return strm.write(s.data(), s.size());
  5146. }
  5147. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  5148. ssize_t write_len = 0;
  5149. for (const auto &x : headers) {
  5150. std::string s;
  5151. s = x.first;
  5152. s += ": ";
  5153. s += x.second;
  5154. s += "\r\n";
  5155. auto len = strm.write(s.data(), s.size());
  5156. if (len < 0) { return len; }
  5157. write_len += len;
  5158. }
  5159. auto len = strm.write("\r\n");
  5160. if (len < 0) { return len; }
  5161. write_len += len;
  5162. return write_len;
  5163. }
  5164. inline bool write_data(Stream &strm, const char *d, size_t l) {
  5165. size_t offset = 0;
  5166. while (offset < l) {
  5167. auto length = strm.write(d + offset, l - offset);
  5168. if (length < 0) { return false; }
  5169. offset += static_cast<size_t>(length);
  5170. }
  5171. return true;
  5172. }
  5173. template <typename T>
  5174. inline bool write_content_with_progress(Stream &strm,
  5175. const ContentProvider &content_provider,
  5176. size_t offset, size_t length,
  5177. T is_shutting_down,
  5178. const UploadProgress &upload_progress,
  5179. Error &error) {
  5180. size_t end_offset = offset + length;
  5181. size_t start_offset = offset;
  5182. auto ok = true;
  5183. DataSink data_sink;
  5184. data_sink.write = [&](const char *d, size_t l) -> bool {
  5185. if (ok) {
  5186. if (write_data(strm, d, l)) {
  5187. offset += l;
  5188. if (upload_progress && length > 0) {
  5189. size_t current_written = offset - start_offset;
  5190. if (!upload_progress(current_written, length)) {
  5191. ok = false;
  5192. return false;
  5193. }
  5194. }
  5195. } else {
  5196. ok = false;
  5197. }
  5198. }
  5199. return ok;
  5200. };
  5201. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5202. while (offset < end_offset && !is_shutting_down()) {
  5203. if (!strm.wait_writable()) {
  5204. error = Error::Write;
  5205. return false;
  5206. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  5207. error = Error::Canceled;
  5208. return false;
  5209. } else if (!ok) {
  5210. error = Error::Write;
  5211. return false;
  5212. }
  5213. }
  5214. error = Error::Success;
  5215. return true;
  5216. }
  5217. template <typename T>
  5218. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5219. size_t offset, size_t length, T is_shutting_down,
  5220. Error &error) {
  5221. return write_content_with_progress<T>(strm, content_provider, offset, length,
  5222. is_shutting_down, nullptr, error);
  5223. }
  5224. template <typename T>
  5225. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5226. size_t offset, size_t length,
  5227. const T &is_shutting_down) {
  5228. auto error = Error::Success;
  5229. return write_content(strm, content_provider, offset, length, is_shutting_down,
  5230. error);
  5231. }
  5232. template <typename T>
  5233. inline bool
  5234. write_content_without_length(Stream &strm,
  5235. const ContentProvider &content_provider,
  5236. const T &is_shutting_down) {
  5237. size_t offset = 0;
  5238. auto data_available = true;
  5239. auto ok = true;
  5240. DataSink data_sink;
  5241. data_sink.write = [&](const char *d, size_t l) -> bool {
  5242. if (ok) {
  5243. offset += l;
  5244. if (!write_data(strm, d, l)) { ok = false; }
  5245. }
  5246. return ok;
  5247. };
  5248. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5249. data_sink.done = [&](void) { data_available = false; };
  5250. while (data_available && !is_shutting_down()) {
  5251. if (!strm.wait_writable()) {
  5252. return false;
  5253. } else if (!content_provider(offset, 0, data_sink)) {
  5254. return false;
  5255. } else if (!ok) {
  5256. return false;
  5257. }
  5258. }
  5259. return true;
  5260. }
  5261. template <typename T, typename U>
  5262. inline bool
  5263. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  5264. const T &is_shutting_down, U &compressor, Error &error) {
  5265. size_t offset = 0;
  5266. auto data_available = true;
  5267. auto ok = true;
  5268. DataSink data_sink;
  5269. data_sink.write = [&](const char *d, size_t l) -> bool {
  5270. if (ok) {
  5271. data_available = l > 0;
  5272. offset += l;
  5273. std::string payload;
  5274. if (compressor.compress(d, l, false,
  5275. [&](const char *data, size_t data_len) {
  5276. payload.append(data, data_len);
  5277. return true;
  5278. })) {
  5279. if (!payload.empty()) {
  5280. // Emit chunked response header and footer for each chunk
  5281. auto chunk =
  5282. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5283. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  5284. }
  5285. } else {
  5286. ok = false;
  5287. }
  5288. }
  5289. return ok;
  5290. };
  5291. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5292. auto done_with_trailer = [&](const Headers *trailer) {
  5293. if (!ok) { return; }
  5294. data_available = false;
  5295. std::string payload;
  5296. if (!compressor.compress(nullptr, 0, true,
  5297. [&](const char *data, size_t data_len) {
  5298. payload.append(data, data_len);
  5299. return true;
  5300. })) {
  5301. ok = false;
  5302. return;
  5303. }
  5304. if (!payload.empty()) {
  5305. // Emit chunked response header and footer for each chunk
  5306. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5307. if (!write_data(strm, chunk.data(), chunk.size())) {
  5308. ok = false;
  5309. return;
  5310. }
  5311. }
  5312. constexpr const char done_marker[] = "0\r\n";
  5313. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  5314. // Trailer
  5315. if (trailer) {
  5316. for (const auto &kv : *trailer) {
  5317. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  5318. if (!write_data(strm, field_line.data(), field_line.size())) {
  5319. ok = false;
  5320. }
  5321. }
  5322. }
  5323. constexpr const char crlf[] = "\r\n";
  5324. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  5325. };
  5326. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  5327. data_sink.done_with_trailer = [&](const Headers &trailer) {
  5328. done_with_trailer(&trailer);
  5329. };
  5330. while (data_available && !is_shutting_down()) {
  5331. if (!strm.wait_writable()) {
  5332. error = Error::Write;
  5333. return false;
  5334. } else if (!content_provider(offset, 0, data_sink)) {
  5335. error = Error::Canceled;
  5336. return false;
  5337. } else if (!ok) {
  5338. error = Error::Write;
  5339. return false;
  5340. }
  5341. }
  5342. error = Error::Success;
  5343. return true;
  5344. }
  5345. template <typename T, typename U>
  5346. inline bool write_content_chunked(Stream &strm,
  5347. const ContentProvider &content_provider,
  5348. const T &is_shutting_down, U &compressor) {
  5349. auto error = Error::Success;
  5350. return write_content_chunked(strm, content_provider, is_shutting_down,
  5351. compressor, error);
  5352. }
  5353. template <typename T>
  5354. inline bool redirect(T &cli, Request &req, Response &res,
  5355. const std::string &path, const std::string &location,
  5356. Error &error) {
  5357. Request new_req = req;
  5358. new_req.path = path;
  5359. new_req.redirect_count_ -= 1;
  5360. if (res.status == StatusCode::SeeOther_303 &&
  5361. (req.method != "GET" && req.method != "HEAD")) {
  5362. new_req.method = "GET";
  5363. new_req.body.clear();
  5364. new_req.headers.clear();
  5365. }
  5366. Response new_res;
  5367. auto ret = cli.send(new_req, new_res, error);
  5368. if (ret) {
  5369. req = std::move(new_req);
  5370. res = std::move(new_res);
  5371. if (res.location.empty()) { res.location = location; }
  5372. }
  5373. return ret;
  5374. }
  5375. inline std::string params_to_query_str(const Params &params) {
  5376. std::string query;
  5377. for (auto it = params.begin(); it != params.end(); ++it) {
  5378. if (it != params.begin()) { query += '&'; }
  5379. query += encode_query_component(it->first);
  5380. query += '=';
  5381. query += encode_query_component(it->second);
  5382. }
  5383. return query;
  5384. }
  5385. inline void parse_query_text(const char *data, std::size_t size,
  5386. Params &params) {
  5387. std::set<std::string> cache;
  5388. split(data, data + size, '&', [&](const char *b, const char *e) {
  5389. std::string kv(b, e);
  5390. if (cache.find(kv) != cache.end()) { return; }
  5391. cache.insert(std::move(kv));
  5392. std::string key;
  5393. std::string val;
  5394. divide(b, static_cast<std::size_t>(e - b), '=',
  5395. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  5396. std::size_t rhs_size) {
  5397. key.assign(lhs_data, lhs_size);
  5398. val.assign(rhs_data, rhs_size);
  5399. });
  5400. if (!key.empty()) {
  5401. params.emplace(decode_query_component(key), decode_query_component(val));
  5402. }
  5403. });
  5404. }
  5405. inline void parse_query_text(const std::string &s, Params &params) {
  5406. parse_query_text(s.data(), s.size(), params);
  5407. }
  5408. // Normalize a query string by decoding and re-encoding each key/value pair
  5409. // while preserving the original parameter order. This avoids double-encoding
  5410. // and ensures consistent encoding without reordering (unlike Params which
  5411. // uses std::multimap and sorts keys).
  5412. inline std::string normalize_query_string(const std::string &query) {
  5413. std::string result;
  5414. split(query.data(), query.data() + query.size(), '&',
  5415. [&](const char *b, const char *e) {
  5416. std::string key;
  5417. std::string val;
  5418. divide(b, static_cast<std::size_t>(e - b), '=',
  5419. [&](const char *lhs_data, std::size_t lhs_size,
  5420. const char *rhs_data, std::size_t rhs_size) {
  5421. key.assign(lhs_data, lhs_size);
  5422. val.assign(rhs_data, rhs_size);
  5423. });
  5424. if (!key.empty()) {
  5425. auto dec_key = decode_query_component(key);
  5426. auto dec_val = decode_query_component(val);
  5427. if (!result.empty()) { result += '&'; }
  5428. result += encode_query_component(dec_key);
  5429. if (!val.empty() || std::find(b, e, '=') != e) {
  5430. result += '=';
  5431. result += encode_query_component(dec_val);
  5432. }
  5433. }
  5434. });
  5435. return result;
  5436. }
  5437. inline bool parse_multipart_boundary(const std::string &content_type,
  5438. std::string &boundary) {
  5439. auto boundary_keyword = "boundary=";
  5440. auto pos = content_type.find(boundary_keyword);
  5441. if (pos == std::string::npos) { return false; }
  5442. auto end = content_type.find(';', pos);
  5443. auto beg = pos + strlen(boundary_keyword);
  5444. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  5445. return !boundary.empty();
  5446. }
  5447. inline void parse_disposition_params(const std::string &s, Params &params) {
  5448. std::set<std::string> cache;
  5449. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  5450. std::string kv(b, e);
  5451. if (cache.find(kv) != cache.end()) { return; }
  5452. cache.insert(kv);
  5453. std::string key;
  5454. std::string val;
  5455. split(b, e, '=', [&](const char *b2, const char *e2) {
  5456. if (key.empty()) {
  5457. key.assign(b2, e2);
  5458. } else {
  5459. val.assign(b2, e2);
  5460. }
  5461. });
  5462. if (!key.empty()) {
  5463. params.emplace(trim_double_quotes_copy((key)),
  5464. trim_double_quotes_copy((val)));
  5465. }
  5466. });
  5467. }
  5468. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5469. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  5470. #else
  5471. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  5472. #endif
  5473. auto is_valid = [](const std::string &str) {
  5474. return std::all_of(str.cbegin(), str.cend(),
  5475. [](unsigned char c) { return std::isdigit(c); });
  5476. };
  5477. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  5478. const auto pos = static_cast<size_t>(6);
  5479. const auto len = static_cast<size_t>(s.size() - 6);
  5480. auto all_valid_ranges = true;
  5481. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  5482. if (!all_valid_ranges) { return; }
  5483. const auto it = std::find(b, e, '-');
  5484. if (it == e) {
  5485. all_valid_ranges = false;
  5486. return;
  5487. }
  5488. const auto lhs = std::string(b, it);
  5489. const auto rhs = std::string(it + 1, e);
  5490. if (!is_valid(lhs) || !is_valid(rhs)) {
  5491. all_valid_ranges = false;
  5492. return;
  5493. }
  5494. const auto first =
  5495. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  5496. const auto last =
  5497. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  5498. if ((first == -1 && last == -1) ||
  5499. (first != -1 && last != -1 && first > last)) {
  5500. all_valid_ranges = false;
  5501. return;
  5502. }
  5503. ranges.emplace_back(first, last);
  5504. });
  5505. return all_valid_ranges && !ranges.empty();
  5506. }
  5507. return false;
  5508. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5509. }
  5510. #else
  5511. } catch (...) { return false; }
  5512. #endif
  5513. inline bool parse_accept_header(const std::string &s,
  5514. std::vector<std::string> &content_types) {
  5515. content_types.clear();
  5516. // Empty string is considered valid (no preference)
  5517. if (s.empty()) { return true; }
  5518. // Check for invalid patterns: leading/trailing commas or consecutive commas
  5519. if (s.front() == ',' || s.back() == ',' ||
  5520. s.find(",,") != std::string::npos) {
  5521. return false;
  5522. }
  5523. struct AcceptEntry {
  5524. std::string media_type;
  5525. double quality;
  5526. int order; // Original order in header
  5527. };
  5528. std::vector<AcceptEntry> entries;
  5529. int order = 0;
  5530. bool has_invalid_entry = false;
  5531. // Split by comma and parse each entry
  5532. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5533. std::string entry(b, e);
  5534. entry = trim_copy(entry);
  5535. if (entry.empty()) {
  5536. has_invalid_entry = true;
  5537. return;
  5538. }
  5539. AcceptEntry accept_entry;
  5540. accept_entry.quality = 1.0; // Default quality
  5541. accept_entry.order = order++;
  5542. // Find q= parameter
  5543. auto q_pos = entry.find(";q=");
  5544. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  5545. if (q_pos != std::string::npos) {
  5546. // Extract media type (before q parameter)
  5547. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  5548. // Extract quality value
  5549. auto q_start = entry.find('=', q_pos) + 1;
  5550. auto q_end = entry.find(';', q_start);
  5551. if (q_end == std::string::npos) { q_end = entry.length(); }
  5552. std::string quality_str =
  5553. trim_copy(entry.substr(q_start, q_end - q_start));
  5554. if (quality_str.empty()) {
  5555. has_invalid_entry = true;
  5556. return;
  5557. }
  5558. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5559. {
  5560. std::istringstream iss(quality_str);
  5561. iss >> accept_entry.quality;
  5562. // Check if conversion was successful and entire string was consumed
  5563. if (iss.fail() || !iss.eof()) {
  5564. has_invalid_entry = true;
  5565. return;
  5566. }
  5567. }
  5568. #else
  5569. try {
  5570. accept_entry.quality = std::stod(quality_str);
  5571. } catch (...) {
  5572. has_invalid_entry = true;
  5573. return;
  5574. }
  5575. #endif
  5576. // Check if quality is in valid range [0.0, 1.0]
  5577. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  5578. has_invalid_entry = true;
  5579. return;
  5580. }
  5581. } else {
  5582. // No quality parameter, use entire entry as media type
  5583. accept_entry.media_type = entry;
  5584. }
  5585. // Remove additional parameters from media type
  5586. auto param_pos = accept_entry.media_type.find(';');
  5587. if (param_pos != std::string::npos) {
  5588. accept_entry.media_type =
  5589. trim_copy(accept_entry.media_type.substr(0, param_pos));
  5590. }
  5591. // Basic validation of media type format
  5592. if (accept_entry.media_type.empty()) {
  5593. has_invalid_entry = true;
  5594. return;
  5595. }
  5596. // Check for basic media type format (should contain '/' or be '*')
  5597. if (accept_entry.media_type != "*" &&
  5598. accept_entry.media_type.find('/') == std::string::npos) {
  5599. has_invalid_entry = true;
  5600. return;
  5601. }
  5602. entries.push_back(std::move(accept_entry));
  5603. });
  5604. // Return false if any invalid entry was found
  5605. if (has_invalid_entry) { return false; }
  5606. // Sort by quality (descending), then by original order (ascending)
  5607. std::sort(entries.begin(), entries.end(),
  5608. [](const AcceptEntry &a, const AcceptEntry &b) {
  5609. if (a.quality != b.quality) {
  5610. return a.quality > b.quality; // Higher quality first
  5611. }
  5612. return a.order < b.order; // Earlier order first for same quality
  5613. });
  5614. // Extract sorted media types
  5615. content_types.reserve(entries.size());
  5616. for (auto &entry : entries) {
  5617. content_types.push_back(std::move(entry.media_type));
  5618. }
  5619. return true;
  5620. }
  5621. class FormDataParser {
  5622. public:
  5623. FormDataParser() = default;
  5624. void set_boundary(std::string &&boundary) {
  5625. boundary_ = std::move(boundary);
  5626. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  5627. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  5628. }
  5629. bool is_valid() const { return is_valid_; }
  5630. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  5631. const ContentReceiver &content_callback) {
  5632. buf_append(buf, n);
  5633. while (buf_size() > 0) {
  5634. switch (state_) {
  5635. case 0: { // Initial boundary
  5636. auto pos = buf_find(dash_boundary_crlf_);
  5637. if (pos == buf_size()) { return true; }
  5638. buf_erase(pos + dash_boundary_crlf_.size());
  5639. state_ = 1;
  5640. break;
  5641. }
  5642. case 1: { // New entry
  5643. clear_file_info();
  5644. state_ = 2;
  5645. break;
  5646. }
  5647. case 2: { // Headers
  5648. auto pos = buf_find(crlf_);
  5649. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5650. while (pos < buf_size()) {
  5651. // Empty line
  5652. if (pos == 0) {
  5653. if (!header_callback(file_)) {
  5654. is_valid_ = false;
  5655. return false;
  5656. }
  5657. buf_erase(crlf_.size());
  5658. state_ = 3;
  5659. break;
  5660. }
  5661. const auto header = buf_head(pos);
  5662. if (!parse_header(header.data(), header.data() + header.size(),
  5663. [&](const std::string &, const std::string &) {})) {
  5664. is_valid_ = false;
  5665. return false;
  5666. }
  5667. // Parse and emplace space trimmed headers into a map
  5668. if (!parse_header(
  5669. header.data(), header.data() + header.size(),
  5670. [&](const std::string &key, const std::string &val) {
  5671. file_.headers.emplace(key, val);
  5672. })) {
  5673. is_valid_ = false;
  5674. return false;
  5675. }
  5676. constexpr const char header_content_type[] = "Content-Type:";
  5677. if (start_with_case_ignore(header, header_content_type)) {
  5678. file_.content_type =
  5679. trim_copy(header.substr(str_len(header_content_type)));
  5680. } else {
  5681. thread_local const std::regex re_content_disposition(
  5682. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  5683. std::regex_constants::icase);
  5684. std::smatch m;
  5685. if (std::regex_match(header, m, re_content_disposition)) {
  5686. Params params;
  5687. parse_disposition_params(m[1], params);
  5688. auto it = params.find("name");
  5689. if (it != params.end()) {
  5690. file_.name = it->second;
  5691. } else {
  5692. is_valid_ = false;
  5693. return false;
  5694. }
  5695. it = params.find("filename");
  5696. if (it != params.end()) { file_.filename = it->second; }
  5697. it = params.find("filename*");
  5698. if (it != params.end()) {
  5699. // Only allow UTF-8 encoding...
  5700. thread_local const std::regex re_rfc5987_encoding(
  5701. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  5702. std::smatch m2;
  5703. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  5704. file_.filename = decode_path_component(m2[1]); // override...
  5705. } else {
  5706. is_valid_ = false;
  5707. return false;
  5708. }
  5709. }
  5710. }
  5711. }
  5712. buf_erase(pos + crlf_.size());
  5713. pos = buf_find(crlf_);
  5714. }
  5715. if (state_ != 3) { return true; }
  5716. break;
  5717. }
  5718. case 3: { // Body
  5719. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  5720. auto pos = buf_find(crlf_dash_boundary_);
  5721. if (pos < buf_size()) {
  5722. if (!content_callback(buf_data(), pos)) {
  5723. is_valid_ = false;
  5724. return false;
  5725. }
  5726. buf_erase(pos + crlf_dash_boundary_.size());
  5727. state_ = 4;
  5728. } else {
  5729. auto len = buf_size() - crlf_dash_boundary_.size();
  5730. if (len > 0) {
  5731. if (!content_callback(buf_data(), len)) {
  5732. is_valid_ = false;
  5733. return false;
  5734. }
  5735. buf_erase(len);
  5736. }
  5737. return true;
  5738. }
  5739. break;
  5740. }
  5741. case 4: { // Boundary
  5742. if (crlf_.size() > buf_size()) { return true; }
  5743. if (buf_start_with(crlf_)) {
  5744. buf_erase(crlf_.size());
  5745. state_ = 1;
  5746. } else {
  5747. if (dash_.size() > buf_size()) { return true; }
  5748. if (buf_start_with(dash_)) {
  5749. buf_erase(dash_.size());
  5750. is_valid_ = true;
  5751. buf_erase(buf_size()); // Remove epilogue
  5752. } else {
  5753. return true;
  5754. }
  5755. }
  5756. break;
  5757. }
  5758. }
  5759. }
  5760. return true;
  5761. }
  5762. private:
  5763. void clear_file_info() {
  5764. file_.name.clear();
  5765. file_.filename.clear();
  5766. file_.content_type.clear();
  5767. file_.headers.clear();
  5768. }
  5769. bool start_with_case_ignore(const std::string &a, const char *b) const {
  5770. const auto b_len = strlen(b);
  5771. if (a.size() < b_len) { return false; }
  5772. for (size_t i = 0; i < b_len; i++) {
  5773. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  5774. return false;
  5775. }
  5776. }
  5777. return true;
  5778. }
  5779. const std::string dash_ = "--";
  5780. const std::string crlf_ = "\r\n";
  5781. std::string boundary_;
  5782. std::string dash_boundary_crlf_;
  5783. std::string crlf_dash_boundary_;
  5784. size_t state_ = 0;
  5785. bool is_valid_ = false;
  5786. FormData file_;
  5787. // Buffer
  5788. bool start_with(const std::string &a, size_t spos, size_t epos,
  5789. const std::string &b) const {
  5790. if (epos - spos < b.size()) { return false; }
  5791. for (size_t i = 0; i < b.size(); i++) {
  5792. if (a[i + spos] != b[i]) { return false; }
  5793. }
  5794. return true;
  5795. }
  5796. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  5797. const char *buf_data() const { return &buf_[buf_spos_]; }
  5798. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  5799. bool buf_start_with(const std::string &s) const {
  5800. return start_with(buf_, buf_spos_, buf_epos_, s);
  5801. }
  5802. size_t buf_find(const std::string &s) const {
  5803. auto c = s.front();
  5804. size_t off = buf_spos_;
  5805. while (off < buf_epos_) {
  5806. auto pos = off;
  5807. while (true) {
  5808. if (pos == buf_epos_) { return buf_size(); }
  5809. if (buf_[pos] == c) { break; }
  5810. pos++;
  5811. }
  5812. auto remaining_size = buf_epos_ - pos;
  5813. if (s.size() > remaining_size) { return buf_size(); }
  5814. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  5815. off = pos + 1;
  5816. }
  5817. return buf_size();
  5818. }
  5819. void buf_append(const char *data, size_t n) {
  5820. auto remaining_size = buf_size();
  5821. if (remaining_size > 0 && buf_spos_ > 0) {
  5822. for (size_t i = 0; i < remaining_size; i++) {
  5823. buf_[i] = buf_[buf_spos_ + i];
  5824. }
  5825. }
  5826. buf_spos_ = 0;
  5827. buf_epos_ = remaining_size;
  5828. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  5829. for (size_t i = 0; i < n; i++) {
  5830. buf_[buf_epos_ + i] = data[i];
  5831. }
  5832. buf_epos_ += n;
  5833. }
  5834. void buf_erase(size_t size) { buf_spos_ += size; }
  5835. std::string buf_;
  5836. size_t buf_spos_ = 0;
  5837. size_t buf_epos_ = 0;
  5838. };
  5839. inline std::string random_string(size_t length) {
  5840. constexpr const char data[] =
  5841. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  5842. thread_local auto engine([]() {
  5843. // std::random_device might actually be deterministic on some
  5844. // platforms, but due to lack of support in the c++ standard library,
  5845. // doing better requires either some ugly hacks or breaking portability.
  5846. std::random_device seed_gen;
  5847. // Request 128 bits of entropy for initialization
  5848. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  5849. return std::mt19937(seed_sequence);
  5850. }());
  5851. std::string result;
  5852. for (size_t i = 0; i < length; i++) {
  5853. result += data[engine() % (sizeof(data) - 1)];
  5854. }
  5855. return result;
  5856. }
  5857. inline std::string make_multipart_data_boundary() {
  5858. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  5859. }
  5860. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  5861. auto valid = true;
  5862. for (size_t i = 0; i < boundary.size(); i++) {
  5863. auto c = boundary[i];
  5864. if (!std::isalnum(c) && c != '-' && c != '_') {
  5865. valid = false;
  5866. break;
  5867. }
  5868. }
  5869. return valid;
  5870. }
  5871. template <typename T>
  5872. inline std::string
  5873. serialize_multipart_formdata_item_begin(const T &item,
  5874. const std::string &boundary) {
  5875. std::string body = "--" + boundary + "\r\n";
  5876. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5877. if (!item.filename.empty()) {
  5878. body += "; filename=\"" + item.filename + "\"";
  5879. }
  5880. body += "\r\n";
  5881. if (!item.content_type.empty()) {
  5882. body += "Content-Type: " + item.content_type + "\r\n";
  5883. }
  5884. body += "\r\n";
  5885. return body;
  5886. }
  5887. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  5888. inline std::string
  5889. serialize_multipart_formdata_finish(const std::string &boundary) {
  5890. return "--" + boundary + "--\r\n";
  5891. }
  5892. inline std::string
  5893. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  5894. return "multipart/form-data; boundary=" + boundary;
  5895. }
  5896. inline std::string
  5897. serialize_multipart_formdata(const UploadFormDataItems &items,
  5898. const std::string &boundary, bool finish = true) {
  5899. std::string body;
  5900. for (const auto &item : items) {
  5901. body += serialize_multipart_formdata_item_begin(item, boundary);
  5902. body += item.content + serialize_multipart_formdata_item_end();
  5903. }
  5904. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  5905. return body;
  5906. }
  5907. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  5908. if (ranges.size() <= 1) return;
  5909. // Sort ranges by start position
  5910. std::sort(ranges.begin(), ranges.end(),
  5911. [](const Range &a, const Range &b) { return a.first < b.first; });
  5912. Ranges coalesced;
  5913. coalesced.reserve(ranges.size());
  5914. for (auto &r : ranges) {
  5915. auto first_pos = r.first;
  5916. auto last_pos = r.second;
  5917. // Handle special cases like in range_error
  5918. if (first_pos == -1 && last_pos == -1) {
  5919. first_pos = 0;
  5920. last_pos = static_cast<ssize_t>(content_length);
  5921. }
  5922. if (first_pos == -1) {
  5923. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  5924. last_pos = static_cast<ssize_t>(content_length) - 1;
  5925. }
  5926. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  5927. last_pos = static_cast<ssize_t>(content_length) - 1;
  5928. }
  5929. // Skip invalid ranges
  5930. if (!(0 <= first_pos && first_pos <= last_pos &&
  5931. last_pos < static_cast<ssize_t>(content_length))) {
  5932. continue;
  5933. }
  5934. // Coalesce with previous range if overlapping or adjacent (but not
  5935. // identical)
  5936. if (!coalesced.empty()) {
  5937. auto &prev = coalesced.back();
  5938. // Check if current range overlaps or is adjacent to previous range
  5939. // but don't coalesce identical ranges (allow duplicates)
  5940. if (first_pos <= prev.second + 1 &&
  5941. !(first_pos == prev.first && last_pos == prev.second)) {
  5942. // Extend the previous range
  5943. prev.second = (std::max)(prev.second, last_pos);
  5944. continue;
  5945. }
  5946. }
  5947. // Add new range
  5948. coalesced.emplace_back(first_pos, last_pos);
  5949. }
  5950. ranges = std::move(coalesced);
  5951. }
  5952. inline bool range_error(Request &req, Response &res) {
  5953. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  5954. ssize_t content_len = static_cast<ssize_t>(
  5955. res.content_length_ ? res.content_length_ : res.body.size());
  5956. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  5957. size_t overwrapping_count = 0;
  5958. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  5959. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  5960. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  5961. // Too many ranges
  5962. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  5963. for (auto &r : req.ranges) {
  5964. auto &first_pos = r.first;
  5965. auto &last_pos = r.second;
  5966. if (first_pos == -1 && last_pos == -1) {
  5967. first_pos = 0;
  5968. last_pos = content_len;
  5969. }
  5970. if (first_pos == -1) {
  5971. first_pos = content_len - last_pos;
  5972. last_pos = content_len - 1;
  5973. }
  5974. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  5975. // A client can limit the number of bytes requested without knowing the
  5976. // size of the selected representation. If the last-pos value is absent,
  5977. // or if the value is greater than or equal to the current length of the
  5978. // representation data, the byte range is interpreted as the remainder of
  5979. // the representation (i.e., the server replaces the value of last-pos
  5980. // with a value that is one less than the current length of the selected
  5981. // representation).
  5982. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  5983. if (last_pos == -1 || last_pos >= content_len) {
  5984. last_pos = content_len - 1;
  5985. }
  5986. // Range must be within content length
  5987. if (!(0 <= first_pos && first_pos <= last_pos &&
  5988. last_pos <= content_len - 1)) {
  5989. return true;
  5990. }
  5991. // Request must not have more than two overlapping ranges
  5992. for (const auto &processed_range : processed_ranges) {
  5993. if (!(last_pos < processed_range.first ||
  5994. first_pos > processed_range.second)) {
  5995. overwrapping_count++;
  5996. if (overwrapping_count > 2) { return true; }
  5997. break; // Only count once per range
  5998. }
  5999. }
  6000. processed_ranges.emplace_back(first_pos, last_pos);
  6001. }
  6002. // After validation, coalesce overlapping ranges as per RFC 9110
  6003. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  6004. }
  6005. return false;
  6006. }
  6007. inline std::pair<size_t, size_t>
  6008. get_range_offset_and_length(Range r, size_t content_length) {
  6009. assert(r.first != -1 && r.second != -1);
  6010. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  6011. assert(r.first <= r.second &&
  6012. r.second < static_cast<ssize_t>(content_length));
  6013. (void)(content_length);
  6014. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  6015. }
  6016. inline std::string make_content_range_header_field(
  6017. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  6018. auto st = offset_and_length.first;
  6019. auto ed = st + offset_and_length.second - 1;
  6020. std::string field = "bytes ";
  6021. field += std::to_string(st);
  6022. field += '-';
  6023. field += std::to_string(ed);
  6024. field += '/';
  6025. field += std::to_string(content_length);
  6026. return field;
  6027. }
  6028. template <typename SToken, typename CToken, typename Content>
  6029. bool process_multipart_ranges_data(const Request &req,
  6030. const std::string &boundary,
  6031. const std::string &content_type,
  6032. size_t content_length, SToken stoken,
  6033. CToken ctoken, Content content) {
  6034. for (size_t i = 0; i < req.ranges.size(); i++) {
  6035. ctoken("--");
  6036. stoken(boundary);
  6037. ctoken("\r\n");
  6038. if (!content_type.empty()) {
  6039. ctoken("Content-Type: ");
  6040. stoken(content_type);
  6041. ctoken("\r\n");
  6042. }
  6043. auto offset_and_length =
  6044. get_range_offset_and_length(req.ranges[i], content_length);
  6045. ctoken("Content-Range: ");
  6046. stoken(make_content_range_header_field(offset_and_length, content_length));
  6047. ctoken("\r\n");
  6048. ctoken("\r\n");
  6049. if (!content(offset_and_length.first, offset_and_length.second)) {
  6050. return false;
  6051. }
  6052. ctoken("\r\n");
  6053. }
  6054. ctoken("--");
  6055. stoken(boundary);
  6056. ctoken("--");
  6057. return true;
  6058. }
  6059. inline void make_multipart_ranges_data(const Request &req, Response &res,
  6060. const std::string &boundary,
  6061. const std::string &content_type,
  6062. size_t content_length,
  6063. std::string &data) {
  6064. process_multipart_ranges_data(
  6065. req, boundary, content_type, content_length,
  6066. [&](const std::string &token) { data += token; },
  6067. [&](const std::string &token) { data += token; },
  6068. [&](size_t offset, size_t length) {
  6069. assert(offset + length <= content_length);
  6070. data += res.body.substr(offset, length);
  6071. return true;
  6072. });
  6073. }
  6074. inline size_t get_multipart_ranges_data_length(const Request &req,
  6075. const std::string &boundary,
  6076. const std::string &content_type,
  6077. size_t content_length) {
  6078. size_t data_length = 0;
  6079. process_multipart_ranges_data(
  6080. req, boundary, content_type, content_length,
  6081. [&](const std::string &token) { data_length += token.size(); },
  6082. [&](const std::string &token) { data_length += token.size(); },
  6083. [&](size_t /*offset*/, size_t length) {
  6084. data_length += length;
  6085. return true;
  6086. });
  6087. return data_length;
  6088. }
  6089. template <typename T>
  6090. inline bool
  6091. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  6092. const std::string &boundary,
  6093. const std::string &content_type,
  6094. size_t content_length, const T &is_shutting_down) {
  6095. return process_multipart_ranges_data(
  6096. req, boundary, content_type, content_length,
  6097. [&](const std::string &token) { strm.write(token); },
  6098. [&](const std::string &token) { strm.write(token); },
  6099. [&](size_t offset, size_t length) {
  6100. return write_content(strm, res.content_provider_, offset, length,
  6101. is_shutting_down);
  6102. });
  6103. }
  6104. inline bool expect_content(const Request &req) {
  6105. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  6106. req.method == "DELETE") {
  6107. return true;
  6108. }
  6109. if (req.has_header("Content-Length") &&
  6110. req.get_header_value_u64("Content-Length") > 0) {
  6111. return true;
  6112. }
  6113. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  6114. return false;
  6115. }
  6116. inline bool has_crlf(const std::string &s) {
  6117. auto p = s.c_str();
  6118. while (*p) {
  6119. if (*p == '\r' || *p == '\n') { return true; }
  6120. p++;
  6121. }
  6122. return false;
  6123. }
  6124. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6125. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  6126. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  6127. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  6128. unsigned int hash_length = 0;
  6129. unsigned char hash[EVP_MAX_MD_SIZE];
  6130. EVP_DigestInit_ex(context.get(), algo, nullptr);
  6131. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  6132. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  6133. std::stringstream ss;
  6134. for (auto i = 0u; i < hash_length; ++i) {
  6135. ss << std::hex << std::setw(2) << std::setfill('0')
  6136. << static_cast<unsigned int>(hash[i]);
  6137. }
  6138. return ss.str();
  6139. }
  6140. inline std::string MD5(const std::string &s) {
  6141. return message_digest(s, EVP_md5());
  6142. }
  6143. inline std::string SHA_256(const std::string &s) {
  6144. return message_digest(s, EVP_sha256());
  6145. }
  6146. inline std::string SHA_512(const std::string &s) {
  6147. return message_digest(s, EVP_sha512());
  6148. }
  6149. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  6150. inline std::string MD5(const std::string &s) {
  6151. unsigned char hash[16];
  6152. #if MBEDTLS_VERSION_MAJOR >= 3
  6153. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6154. hash);
  6155. #else
  6156. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6157. hash);
  6158. #endif
  6159. std::stringstream ss;
  6160. for (auto i = 0u; i < 16; ++i) {
  6161. ss << std::hex << std::setw(2) << std::setfill('0')
  6162. << static_cast<unsigned int>(hash[i]);
  6163. }
  6164. return ss.str();
  6165. }
  6166. inline std::string SHA_256(const std::string &s) {
  6167. unsigned char hash[32];
  6168. #if MBEDTLS_VERSION_MAJOR >= 3
  6169. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6170. hash, 0);
  6171. #else
  6172. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6173. s.size(), hash, 0);
  6174. #endif
  6175. std::stringstream ss;
  6176. for (auto i = 0u; i < 32; ++i) {
  6177. ss << std::hex << std::setw(2) << std::setfill('0')
  6178. << static_cast<unsigned int>(hash[i]);
  6179. }
  6180. return ss.str();
  6181. }
  6182. inline std::string SHA_512(const std::string &s) {
  6183. unsigned char hash[64];
  6184. #if MBEDTLS_VERSION_MAJOR >= 3
  6185. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6186. hash, 0);
  6187. #else
  6188. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6189. s.size(), hash, 0);
  6190. #endif
  6191. std::stringstream ss;
  6192. for (auto i = 0u; i < 64; ++i) {
  6193. ss << std::hex << std::setw(2) << std::setfill('0')
  6194. << static_cast<unsigned int>(hash[i]);
  6195. }
  6196. return ss.str();
  6197. }
  6198. #endif
  6199. #ifdef CPPHTTPLIB_SSL_ENABLED
  6200. inline std::pair<std::string, std::string> make_digest_authentication_header(
  6201. const Request &req, const std::map<std::string, std::string> &auth,
  6202. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  6203. const std::string &password, bool is_proxy = false) {
  6204. std::string nc;
  6205. {
  6206. std::stringstream ss;
  6207. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  6208. nc = ss.str();
  6209. }
  6210. std::string qop;
  6211. if (auth.find("qop") != auth.end()) {
  6212. qop = auth.at("qop");
  6213. if (qop.find("auth-int") != std::string::npos) {
  6214. qop = "auth-int";
  6215. } else if (qop.find("auth") != std::string::npos) {
  6216. qop = "auth";
  6217. } else {
  6218. qop.clear();
  6219. }
  6220. }
  6221. std::string algo = "MD5";
  6222. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  6223. std::string response;
  6224. {
  6225. auto H = algo == "SHA-256" ? detail::SHA_256
  6226. : algo == "SHA-512" ? detail::SHA_512
  6227. : detail::MD5;
  6228. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  6229. auto A2 = req.method + ":" + req.path;
  6230. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  6231. if (qop.empty()) {
  6232. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  6233. } else {
  6234. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  6235. ":" + qop + ":" + H(A2));
  6236. }
  6237. }
  6238. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  6239. auto field = "Digest username=\"" + username + "\", realm=\"" +
  6240. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  6241. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  6242. (qop.empty() ? ", response=\""
  6243. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  6244. cnonce + "\", response=\"") +
  6245. response + "\"" +
  6246. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  6247. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6248. return std::make_pair(key, field);
  6249. }
  6250. #endif // CPPHTTPLIB_SSL_ENABLED
  6251. #ifdef _WIN32
  6252. class WSInit {
  6253. public:
  6254. WSInit() {
  6255. WSADATA wsaData;
  6256. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  6257. }
  6258. ~WSInit() {
  6259. if (is_valid_) WSACleanup();
  6260. }
  6261. bool is_valid_ = false;
  6262. };
  6263. static WSInit wsinit_;
  6264. #endif
  6265. inline bool parse_www_authenticate(const Response &res,
  6266. std::map<std::string, std::string> &auth,
  6267. bool is_proxy) {
  6268. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  6269. if (res.has_header(auth_key)) {
  6270. thread_local auto re =
  6271. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  6272. auto s = res.get_header_value(auth_key);
  6273. auto pos = s.find(' ');
  6274. if (pos != std::string::npos) {
  6275. auto type = s.substr(0, pos);
  6276. if (type == "Basic") {
  6277. return false;
  6278. } else if (type == "Digest") {
  6279. s = s.substr(pos + 1);
  6280. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  6281. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  6282. const auto &m = *i;
  6283. auto key = s.substr(static_cast<size_t>(m.position(1)),
  6284. static_cast<size_t>(m.length(1)));
  6285. auto val = m.length(2) > 0
  6286. ? s.substr(static_cast<size_t>(m.position(2)),
  6287. static_cast<size_t>(m.length(2)))
  6288. : s.substr(static_cast<size_t>(m.position(3)),
  6289. static_cast<size_t>(m.length(3)));
  6290. auth[std::move(key)] = std::move(val);
  6291. }
  6292. return true;
  6293. }
  6294. }
  6295. }
  6296. return false;
  6297. }
  6298. class ContentProviderAdapter {
  6299. public:
  6300. explicit ContentProviderAdapter(
  6301. ContentProviderWithoutLength &&content_provider)
  6302. : content_provider_(std::move(content_provider)) {}
  6303. bool operator()(size_t offset, size_t, DataSink &sink) {
  6304. return content_provider_(offset, sink);
  6305. }
  6306. private:
  6307. ContentProviderWithoutLength content_provider_;
  6308. };
  6309. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  6310. namespace fields {
  6311. inline bool is_token_char(char c) {
  6312. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  6313. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  6314. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  6315. }
  6316. inline bool is_token(const std::string &s) {
  6317. if (s.empty()) { return false; }
  6318. for (auto c : s) {
  6319. if (!is_token_char(c)) { return false; }
  6320. }
  6321. return true;
  6322. }
  6323. inline bool is_field_name(const std::string &s) { return is_token(s); }
  6324. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  6325. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  6326. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  6327. inline bool is_field_content(const std::string &s) {
  6328. if (s.empty()) { return true; }
  6329. if (s.size() == 1) {
  6330. return is_field_vchar(s[0]);
  6331. } else if (s.size() == 2) {
  6332. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  6333. } else {
  6334. size_t i = 0;
  6335. if (!is_field_vchar(s[i])) { return false; }
  6336. i++;
  6337. while (i < s.size() - 1) {
  6338. auto c = s[i++];
  6339. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  6340. } else {
  6341. return false;
  6342. }
  6343. }
  6344. return is_field_vchar(s[i]);
  6345. }
  6346. }
  6347. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  6348. } // namespace fields
  6349. } // namespace detail
  6350. inline const char *status_message(int status) {
  6351. switch (status) {
  6352. case StatusCode::Continue_100: return "Continue";
  6353. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  6354. case StatusCode::Processing_102: return "Processing";
  6355. case StatusCode::EarlyHints_103: return "Early Hints";
  6356. case StatusCode::OK_200: return "OK";
  6357. case StatusCode::Created_201: return "Created";
  6358. case StatusCode::Accepted_202: return "Accepted";
  6359. case StatusCode::NonAuthoritativeInformation_203:
  6360. return "Non-Authoritative Information";
  6361. case StatusCode::NoContent_204: return "No Content";
  6362. case StatusCode::ResetContent_205: return "Reset Content";
  6363. case StatusCode::PartialContent_206: return "Partial Content";
  6364. case StatusCode::MultiStatus_207: return "Multi-Status";
  6365. case StatusCode::AlreadyReported_208: return "Already Reported";
  6366. case StatusCode::IMUsed_226: return "IM Used";
  6367. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  6368. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  6369. case StatusCode::Found_302: return "Found";
  6370. case StatusCode::SeeOther_303: return "See Other";
  6371. case StatusCode::NotModified_304: return "Not Modified";
  6372. case StatusCode::UseProxy_305: return "Use Proxy";
  6373. case StatusCode::unused_306: return "unused";
  6374. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  6375. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  6376. case StatusCode::BadRequest_400: return "Bad Request";
  6377. case StatusCode::Unauthorized_401: return "Unauthorized";
  6378. case StatusCode::PaymentRequired_402: return "Payment Required";
  6379. case StatusCode::Forbidden_403: return "Forbidden";
  6380. case StatusCode::NotFound_404: return "Not Found";
  6381. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  6382. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  6383. case StatusCode::ProxyAuthenticationRequired_407:
  6384. return "Proxy Authentication Required";
  6385. case StatusCode::RequestTimeout_408: return "Request Timeout";
  6386. case StatusCode::Conflict_409: return "Conflict";
  6387. case StatusCode::Gone_410: return "Gone";
  6388. case StatusCode::LengthRequired_411: return "Length Required";
  6389. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  6390. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  6391. case StatusCode::UriTooLong_414: return "URI Too Long";
  6392. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  6393. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  6394. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  6395. case StatusCode::ImATeapot_418: return "I'm a teapot";
  6396. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  6397. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  6398. case StatusCode::Locked_423: return "Locked";
  6399. case StatusCode::FailedDependency_424: return "Failed Dependency";
  6400. case StatusCode::TooEarly_425: return "Too Early";
  6401. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  6402. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  6403. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  6404. case StatusCode::RequestHeaderFieldsTooLarge_431:
  6405. return "Request Header Fields Too Large";
  6406. case StatusCode::UnavailableForLegalReasons_451:
  6407. return "Unavailable For Legal Reasons";
  6408. case StatusCode::NotImplemented_501: return "Not Implemented";
  6409. case StatusCode::BadGateway_502: return "Bad Gateway";
  6410. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  6411. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  6412. case StatusCode::HttpVersionNotSupported_505:
  6413. return "HTTP Version Not Supported";
  6414. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  6415. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  6416. case StatusCode::LoopDetected_508: return "Loop Detected";
  6417. case StatusCode::NotExtended_510: return "Not Extended";
  6418. case StatusCode::NetworkAuthenticationRequired_511:
  6419. return "Network Authentication Required";
  6420. default:
  6421. case StatusCode::InternalServerError_500: return "Internal Server Error";
  6422. }
  6423. }
  6424. inline std::string to_string(const Error error) {
  6425. switch (error) {
  6426. case Error::Success: return "Success (no error)";
  6427. case Error::Unknown: return "Unknown";
  6428. case Error::Connection: return "Could not establish connection";
  6429. case Error::BindIPAddress: return "Failed to bind IP address";
  6430. case Error::Read: return "Failed to read connection";
  6431. case Error::Write: return "Failed to write connection";
  6432. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  6433. case Error::Canceled: return "Connection handling canceled";
  6434. case Error::SSLConnection: return "SSL connection failed";
  6435. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  6436. case Error::SSLServerVerification: return "SSL server verification failed";
  6437. case Error::SSLServerHostnameVerification:
  6438. return "SSL server hostname verification failed";
  6439. case Error::UnsupportedMultipartBoundaryChars:
  6440. return "Unsupported HTTP multipart boundary characters";
  6441. case Error::Compression: return "Compression failed";
  6442. case Error::ConnectionTimeout: return "Connection timed out";
  6443. case Error::ProxyConnection: return "Proxy connection failed";
  6444. case Error::ConnectionClosed: return "Connection closed by server";
  6445. case Error::Timeout: return "Read timeout";
  6446. case Error::ResourceExhaustion: return "Resource exhaustion";
  6447. case Error::TooManyFormDataFiles: return "Too many form data files";
  6448. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  6449. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  6450. case Error::ExceedMaxSocketDescriptorCount:
  6451. return "Exceeded maximum socket descriptor count";
  6452. case Error::InvalidRequestLine: return "Invalid request line";
  6453. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  6454. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  6455. case Error::InvalidHeaders: return "Invalid headers";
  6456. case Error::MultipartParsing: return "Multipart parsing failed";
  6457. case Error::OpenFile: return "Failed to open file";
  6458. case Error::Listen: return "Failed to listen on socket";
  6459. case Error::GetSockName: return "Failed to get socket name";
  6460. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  6461. case Error::HTTPParsing: return "HTTP parsing failed";
  6462. case Error::InvalidRangeHeader: return "Invalid Range header";
  6463. default: break;
  6464. }
  6465. return "Invalid";
  6466. }
  6467. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  6468. os << to_string(obj);
  6469. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  6470. return os;
  6471. }
  6472. inline std::string hosted_at(const std::string &hostname) {
  6473. std::vector<std::string> addrs;
  6474. hosted_at(hostname, addrs);
  6475. if (addrs.empty()) { return std::string(); }
  6476. return addrs[0];
  6477. }
  6478. inline void hosted_at(const std::string &hostname,
  6479. std::vector<std::string> &addrs) {
  6480. struct addrinfo hints;
  6481. struct addrinfo *result;
  6482. memset(&hints, 0, sizeof(struct addrinfo));
  6483. hints.ai_family = AF_UNSPEC;
  6484. hints.ai_socktype = SOCK_STREAM;
  6485. hints.ai_protocol = 0;
  6486. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  6487. &result, 0)) {
  6488. #if defined __linux__ && !defined __ANDROID__
  6489. res_init();
  6490. #endif
  6491. return;
  6492. }
  6493. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6494. for (auto rp = result; rp; rp = rp->ai_next) {
  6495. const auto &addr =
  6496. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  6497. std::string ip;
  6498. auto dummy = -1;
  6499. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  6500. dummy)) {
  6501. addrs.emplace_back(std::move(ip));
  6502. }
  6503. }
  6504. }
  6505. inline std::string encode_uri_component(const std::string &value) {
  6506. std::ostringstream escaped;
  6507. escaped.fill('0');
  6508. escaped << std::hex;
  6509. for (auto c : value) {
  6510. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6511. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6512. c == ')') {
  6513. escaped << c;
  6514. } else {
  6515. escaped << std::uppercase;
  6516. escaped << '%' << std::setw(2)
  6517. << static_cast<int>(static_cast<unsigned char>(c));
  6518. escaped << std::nouppercase;
  6519. }
  6520. }
  6521. return escaped.str();
  6522. }
  6523. inline std::string encode_uri(const std::string &value) {
  6524. std::ostringstream escaped;
  6525. escaped.fill('0');
  6526. escaped << std::hex;
  6527. for (auto c : value) {
  6528. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6529. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6530. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  6531. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  6532. escaped << c;
  6533. } else {
  6534. escaped << std::uppercase;
  6535. escaped << '%' << std::setw(2)
  6536. << static_cast<int>(static_cast<unsigned char>(c));
  6537. escaped << std::nouppercase;
  6538. }
  6539. }
  6540. return escaped.str();
  6541. }
  6542. inline std::string decode_uri_component(const std::string &value) {
  6543. std::string result;
  6544. for (size_t i = 0; i < value.size(); i++) {
  6545. if (value[i] == '%' && i + 2 < value.size()) {
  6546. auto val = 0;
  6547. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6548. result += static_cast<char>(val);
  6549. i += 2;
  6550. } else {
  6551. result += value[i];
  6552. }
  6553. } else {
  6554. result += value[i];
  6555. }
  6556. }
  6557. return result;
  6558. }
  6559. inline std::string decode_uri(const std::string &value) {
  6560. std::string result;
  6561. for (size_t i = 0; i < value.size(); i++) {
  6562. if (value[i] == '%' && i + 2 < value.size()) {
  6563. auto val = 0;
  6564. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6565. result += static_cast<char>(val);
  6566. i += 2;
  6567. } else {
  6568. result += value[i];
  6569. }
  6570. } else {
  6571. result += value[i];
  6572. }
  6573. }
  6574. return result;
  6575. }
  6576. inline std::string encode_path_component(const std::string &component) {
  6577. std::string result;
  6578. result.reserve(component.size() * 3);
  6579. for (size_t i = 0; i < component.size(); i++) {
  6580. auto c = static_cast<unsigned char>(component[i]);
  6581. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  6582. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6583. result += static_cast<char>(c);
  6584. }
  6585. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  6586. // "," / ";" / "="
  6587. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  6588. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  6589. c == '=') {
  6590. result += static_cast<char>(c);
  6591. }
  6592. // Colon is allowed in path segments except first segment
  6593. else if (c == ':') {
  6594. result += static_cast<char>(c);
  6595. }
  6596. // @ is allowed in path
  6597. else if (c == '@') {
  6598. result += static_cast<char>(c);
  6599. } else {
  6600. result += '%';
  6601. char hex[3];
  6602. snprintf(hex, sizeof(hex), "%02X", c);
  6603. result.append(hex, 2);
  6604. }
  6605. }
  6606. return result;
  6607. }
  6608. inline std::string decode_path_component(const std::string &component) {
  6609. std::string result;
  6610. result.reserve(component.size());
  6611. for (size_t i = 0; i < component.size(); i++) {
  6612. if (component[i] == '%' && i + 1 < component.size()) {
  6613. if (component[i + 1] == 'u') {
  6614. // Unicode %uXXXX encoding
  6615. auto val = 0;
  6616. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  6617. // 4 digits Unicode codes
  6618. char buff[4];
  6619. size_t len = detail::to_utf8(val, buff);
  6620. if (len > 0) { result.append(buff, len); }
  6621. i += 5; // 'u0000'
  6622. } else {
  6623. result += component[i];
  6624. }
  6625. } else {
  6626. // Standard %XX encoding
  6627. auto val = 0;
  6628. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  6629. // 2 digits hex codes
  6630. result += static_cast<char>(val);
  6631. i += 2; // 'XX'
  6632. } else {
  6633. result += component[i];
  6634. }
  6635. }
  6636. } else {
  6637. result += component[i];
  6638. }
  6639. }
  6640. return result;
  6641. }
  6642. inline std::string encode_query_component(const std::string &component,
  6643. bool space_as_plus) {
  6644. std::string result;
  6645. result.reserve(component.size() * 3);
  6646. for (size_t i = 0; i < component.size(); i++) {
  6647. auto c = static_cast<unsigned char>(component[i]);
  6648. // Unreserved characters per RFC 3986
  6649. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6650. result += static_cast<char>(c);
  6651. }
  6652. // Space handling
  6653. else if (c == ' ') {
  6654. if (space_as_plus) {
  6655. result += '+';
  6656. } else {
  6657. result += "%20";
  6658. }
  6659. }
  6660. // Plus sign handling
  6661. else if (c == '+') {
  6662. if (space_as_plus) {
  6663. result += "%2B";
  6664. } else {
  6665. result += static_cast<char>(c);
  6666. }
  6667. }
  6668. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  6669. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  6670. c == '*' || c == ',' || c == ';') {
  6671. result += static_cast<char>(c);
  6672. }
  6673. // Colon and @ are allowed in query
  6674. else if (c == ':' || c == '@') {
  6675. result += static_cast<char>(c);
  6676. }
  6677. // Forward slash is allowed in query values
  6678. else if (c == '/') {
  6679. result += static_cast<char>(c);
  6680. }
  6681. // Question mark is allowed in query values (after first ?)
  6682. else if (c == '?') {
  6683. result += static_cast<char>(c);
  6684. } else {
  6685. result += '%';
  6686. char hex[3];
  6687. snprintf(hex, sizeof(hex), "%02X", c);
  6688. result.append(hex, 2);
  6689. }
  6690. }
  6691. return result;
  6692. }
  6693. inline std::string decode_query_component(const std::string &component,
  6694. bool plus_as_space) {
  6695. std::string result;
  6696. result.reserve(component.size());
  6697. for (size_t i = 0; i < component.size(); i++) {
  6698. if (component[i] == '%' && i + 2 < component.size()) {
  6699. std::string hex = component.substr(i + 1, 2);
  6700. char *end;
  6701. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  6702. if (end == hex.c_str() + 2) {
  6703. result += static_cast<char>(value);
  6704. i += 2;
  6705. } else {
  6706. result += component[i];
  6707. }
  6708. } else if (component[i] == '+' && plus_as_space) {
  6709. result += ' '; // + becomes space in form-urlencoded
  6710. } else {
  6711. result += component[i];
  6712. }
  6713. }
  6714. return result;
  6715. }
  6716. inline std::string append_query_params(const std::string &path,
  6717. const Params &params) {
  6718. std::string path_with_query = path;
  6719. thread_local const std::regex re("[^?]+\\?.*");
  6720. auto delm = std::regex_match(path, re) ? '&' : '?';
  6721. path_with_query += delm + detail::params_to_query_str(params);
  6722. return path_with_query;
  6723. }
  6724. // Header utilities
  6725. inline std::pair<std::string, std::string>
  6726. make_range_header(const Ranges &ranges) {
  6727. std::string field = "bytes=";
  6728. auto i = 0;
  6729. for (const auto &r : ranges) {
  6730. if (i != 0) { field += ", "; }
  6731. if (r.first != -1) { field += std::to_string(r.first); }
  6732. field += '-';
  6733. if (r.second != -1) { field += std::to_string(r.second); }
  6734. i++;
  6735. }
  6736. return std::make_pair("Range", std::move(field));
  6737. }
  6738. inline std::pair<std::string, std::string>
  6739. make_basic_authentication_header(const std::string &username,
  6740. const std::string &password, bool is_proxy) {
  6741. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  6742. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6743. return std::make_pair(key, std::move(field));
  6744. }
  6745. inline std::pair<std::string, std::string>
  6746. make_bearer_token_authentication_header(const std::string &token,
  6747. bool is_proxy = false) {
  6748. auto field = "Bearer " + token;
  6749. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6750. return std::make_pair(key, std::move(field));
  6751. }
  6752. // Request implementation
  6753. inline bool Request::has_header(const std::string &key) const {
  6754. return detail::has_header(headers, key);
  6755. }
  6756. inline std::string Request::get_header_value(const std::string &key,
  6757. const char *def, size_t id) const {
  6758. return detail::get_header_value(headers, key, def, id);
  6759. }
  6760. inline size_t Request::get_header_value_count(const std::string &key) const {
  6761. auto r = headers.equal_range(key);
  6762. return static_cast<size_t>(std::distance(r.first, r.second));
  6763. }
  6764. inline void Request::set_header(const std::string &key,
  6765. const std::string &val) {
  6766. if (detail::fields::is_field_name(key) &&
  6767. detail::fields::is_field_value(val)) {
  6768. headers.emplace(key, val);
  6769. }
  6770. }
  6771. inline bool Request::has_trailer(const std::string &key) const {
  6772. return trailers.find(key) != trailers.end();
  6773. }
  6774. inline std::string Request::get_trailer_value(const std::string &key,
  6775. size_t id) const {
  6776. auto rng = trailers.equal_range(key);
  6777. auto it = rng.first;
  6778. std::advance(it, static_cast<ssize_t>(id));
  6779. if (it != rng.second) { return it->second; }
  6780. return std::string();
  6781. }
  6782. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  6783. auto r = trailers.equal_range(key);
  6784. return static_cast<size_t>(std::distance(r.first, r.second));
  6785. }
  6786. inline bool Request::has_param(const std::string &key) const {
  6787. return params.find(key) != params.end();
  6788. }
  6789. inline std::string Request::get_param_value(const std::string &key,
  6790. size_t id) const {
  6791. auto rng = params.equal_range(key);
  6792. auto it = rng.first;
  6793. std::advance(it, static_cast<ssize_t>(id));
  6794. if (it != rng.second) { return it->second; }
  6795. return std::string();
  6796. }
  6797. inline size_t Request::get_param_value_count(const std::string &key) const {
  6798. auto r = params.equal_range(key);
  6799. return static_cast<size_t>(std::distance(r.first, r.second));
  6800. }
  6801. inline bool Request::is_multipart_form_data() const {
  6802. const auto &content_type = get_header_value("Content-Type");
  6803. return !content_type.rfind("multipart/form-data", 0);
  6804. }
  6805. // Multipart FormData implementation
  6806. inline std::string MultipartFormData::get_field(const std::string &key,
  6807. size_t id) const {
  6808. auto rng = fields.equal_range(key);
  6809. auto it = rng.first;
  6810. std::advance(it, static_cast<ssize_t>(id));
  6811. if (it != rng.second) { return it->second.content; }
  6812. return std::string();
  6813. }
  6814. inline std::vector<std::string>
  6815. MultipartFormData::get_fields(const std::string &key) const {
  6816. std::vector<std::string> values;
  6817. auto rng = fields.equal_range(key);
  6818. for (auto it = rng.first; it != rng.second; it++) {
  6819. values.push_back(it->second.content);
  6820. }
  6821. return values;
  6822. }
  6823. inline bool MultipartFormData::has_field(const std::string &key) const {
  6824. return fields.find(key) != fields.end();
  6825. }
  6826. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  6827. auto r = fields.equal_range(key);
  6828. return static_cast<size_t>(std::distance(r.first, r.second));
  6829. }
  6830. inline FormData MultipartFormData::get_file(const std::string &key,
  6831. size_t id) const {
  6832. auto rng = files.equal_range(key);
  6833. auto it = rng.first;
  6834. std::advance(it, static_cast<ssize_t>(id));
  6835. if (it != rng.second) { return it->second; }
  6836. return FormData();
  6837. }
  6838. inline std::vector<FormData>
  6839. MultipartFormData::get_files(const std::string &key) const {
  6840. std::vector<FormData> values;
  6841. auto rng = files.equal_range(key);
  6842. for (auto it = rng.first; it != rng.second; it++) {
  6843. values.push_back(it->second);
  6844. }
  6845. return values;
  6846. }
  6847. inline bool MultipartFormData::has_file(const std::string &key) const {
  6848. return files.find(key) != files.end();
  6849. }
  6850. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  6851. auto r = files.equal_range(key);
  6852. return static_cast<size_t>(std::distance(r.first, r.second));
  6853. }
  6854. // Response implementation
  6855. inline bool Response::has_header(const std::string &key) const {
  6856. return headers.find(key) != headers.end();
  6857. }
  6858. inline std::string Response::get_header_value(const std::string &key,
  6859. const char *def,
  6860. size_t id) const {
  6861. return detail::get_header_value(headers, key, def, id);
  6862. }
  6863. inline size_t Response::get_header_value_count(const std::string &key) const {
  6864. auto r = headers.equal_range(key);
  6865. return static_cast<size_t>(std::distance(r.first, r.second));
  6866. }
  6867. inline void Response::set_header(const std::string &key,
  6868. const std::string &val) {
  6869. if (detail::fields::is_field_name(key) &&
  6870. detail::fields::is_field_value(val)) {
  6871. headers.emplace(key, val);
  6872. }
  6873. }
  6874. inline bool Response::has_trailer(const std::string &key) const {
  6875. return trailers.find(key) != trailers.end();
  6876. }
  6877. inline std::string Response::get_trailer_value(const std::string &key,
  6878. size_t id) const {
  6879. auto rng = trailers.equal_range(key);
  6880. auto it = rng.first;
  6881. std::advance(it, static_cast<ssize_t>(id));
  6882. if (it != rng.second) { return it->second; }
  6883. return std::string();
  6884. }
  6885. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  6886. auto r = trailers.equal_range(key);
  6887. return static_cast<size_t>(std::distance(r.first, r.second));
  6888. }
  6889. inline void Response::set_redirect(const std::string &url, int stat) {
  6890. if (detail::fields::is_field_value(url)) {
  6891. set_header("Location", url);
  6892. if (300 <= stat && stat < 400) {
  6893. this->status = stat;
  6894. } else {
  6895. this->status = StatusCode::Found_302;
  6896. }
  6897. }
  6898. }
  6899. inline void Response::set_content(const char *s, size_t n,
  6900. const std::string &content_type) {
  6901. body.assign(s, n);
  6902. auto rng = headers.equal_range("Content-Type");
  6903. headers.erase(rng.first, rng.second);
  6904. set_header("Content-Type", content_type);
  6905. }
  6906. inline void Response::set_content(const std::string &s,
  6907. const std::string &content_type) {
  6908. set_content(s.data(), s.size(), content_type);
  6909. }
  6910. inline void Response::set_content(std::string &&s,
  6911. const std::string &content_type) {
  6912. body = std::move(s);
  6913. auto rng = headers.equal_range("Content-Type");
  6914. headers.erase(rng.first, rng.second);
  6915. set_header("Content-Type", content_type);
  6916. }
  6917. inline void Response::set_content_provider(
  6918. size_t in_length, const std::string &content_type, ContentProvider provider,
  6919. ContentProviderResourceReleaser resource_releaser) {
  6920. set_header("Content-Type", content_type);
  6921. content_length_ = in_length;
  6922. if (in_length > 0) { content_provider_ = std::move(provider); }
  6923. content_provider_resource_releaser_ = std::move(resource_releaser);
  6924. is_chunked_content_provider_ = false;
  6925. }
  6926. inline void Response::set_content_provider(
  6927. const std::string &content_type, ContentProviderWithoutLength provider,
  6928. ContentProviderResourceReleaser resource_releaser) {
  6929. set_header("Content-Type", content_type);
  6930. content_length_ = 0;
  6931. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6932. content_provider_resource_releaser_ = std::move(resource_releaser);
  6933. is_chunked_content_provider_ = false;
  6934. }
  6935. inline void Response::set_chunked_content_provider(
  6936. const std::string &content_type, ContentProviderWithoutLength provider,
  6937. ContentProviderResourceReleaser resource_releaser) {
  6938. set_header("Content-Type", content_type);
  6939. content_length_ = 0;
  6940. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6941. content_provider_resource_releaser_ = std::move(resource_releaser);
  6942. is_chunked_content_provider_ = true;
  6943. }
  6944. inline void Response::set_file_content(const std::string &path,
  6945. const std::string &content_type) {
  6946. file_content_path_ = path;
  6947. file_content_content_type_ = content_type;
  6948. }
  6949. inline void Response::set_file_content(const std::string &path) {
  6950. file_content_path_ = path;
  6951. }
  6952. // Result implementation
  6953. inline bool Result::has_request_header(const std::string &key) const {
  6954. return request_headers_.find(key) != request_headers_.end();
  6955. }
  6956. inline std::string Result::get_request_header_value(const std::string &key,
  6957. const char *def,
  6958. size_t id) const {
  6959. return detail::get_header_value(request_headers_, key, def, id);
  6960. }
  6961. inline size_t
  6962. Result::get_request_header_value_count(const std::string &key) const {
  6963. auto r = request_headers_.equal_range(key);
  6964. return static_cast<size_t>(std::distance(r.first, r.second));
  6965. }
  6966. // Stream implementation
  6967. inline ssize_t Stream::write(const char *ptr) {
  6968. return write(ptr, strlen(ptr));
  6969. }
  6970. inline ssize_t Stream::write(const std::string &s) {
  6971. return write(s.data(), s.size());
  6972. }
  6973. // BodyReader implementation
  6974. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  6975. if (!stream) {
  6976. last_error = Error::Connection;
  6977. return -1;
  6978. }
  6979. if (eof) { return 0; }
  6980. if (!chunked) {
  6981. // Content-Length based reading
  6982. if (bytes_read >= content_length) {
  6983. eof = true;
  6984. return 0;
  6985. }
  6986. auto remaining = content_length - bytes_read;
  6987. auto to_read = (std::min)(len, remaining);
  6988. auto n = stream->read(buf, to_read);
  6989. if (n < 0) {
  6990. last_error = stream->get_error();
  6991. if (last_error == Error::Success) { last_error = Error::Read; }
  6992. eof = true;
  6993. return n;
  6994. }
  6995. if (n == 0) {
  6996. // Unexpected EOF before content_length
  6997. last_error = stream->get_error();
  6998. if (last_error == Error::Success) { last_error = Error::Read; }
  6999. eof = true;
  7000. return 0;
  7001. }
  7002. bytes_read += static_cast<size_t>(n);
  7003. if (bytes_read >= content_length) { eof = true; }
  7004. return n;
  7005. }
  7006. // Chunked transfer encoding: delegate to shared decoder instance.
  7007. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  7008. size_t chunk_offset = 0;
  7009. size_t chunk_total = 0;
  7010. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  7011. if (n < 0) {
  7012. last_error = stream->get_error();
  7013. if (last_error == Error::Success) { last_error = Error::Read; }
  7014. eof = true;
  7015. return n;
  7016. }
  7017. if (n == 0) {
  7018. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  7019. eof = true;
  7020. return 0;
  7021. }
  7022. bytes_read += static_cast<size_t>(n);
  7023. return n;
  7024. }
  7025. namespace detail {
  7026. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  7027. time_t timeout_sec, time_t timeout_usec,
  7028. time_t &actual_timeout_sec,
  7029. time_t &actual_timeout_usec) {
  7030. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  7031. auto actual_timeout_msec =
  7032. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  7033. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  7034. actual_timeout_sec = actual_timeout_msec / 1000;
  7035. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  7036. }
  7037. // Socket stream implementation
  7038. inline SocketStream::SocketStream(
  7039. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  7040. time_t write_timeout_sec, time_t write_timeout_usec,
  7041. time_t max_timeout_msec,
  7042. std::chrono::time_point<std::chrono::steady_clock> start_time)
  7043. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  7044. read_timeout_usec_(read_timeout_usec),
  7045. write_timeout_sec_(write_timeout_sec),
  7046. write_timeout_usec_(write_timeout_usec),
  7047. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  7048. read_buff_(read_buff_size_, 0) {}
  7049. inline SocketStream::~SocketStream() = default;
  7050. inline bool SocketStream::is_readable() const {
  7051. return read_buff_off_ < read_buff_content_size_;
  7052. }
  7053. inline bool SocketStream::wait_readable() const {
  7054. if (max_timeout_msec_ <= 0) {
  7055. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  7056. }
  7057. time_t read_timeout_sec;
  7058. time_t read_timeout_usec;
  7059. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  7060. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  7061. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  7062. }
  7063. inline bool SocketStream::wait_writable() const {
  7064. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  7065. is_socket_alive(sock_);
  7066. }
  7067. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  7068. #ifdef _WIN32
  7069. size =
  7070. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7071. #else
  7072. size = (std::min)(size,
  7073. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  7074. #endif
  7075. if (read_buff_off_ < read_buff_content_size_) {
  7076. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  7077. if (size <= remaining_size) {
  7078. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  7079. read_buff_off_ += size;
  7080. return static_cast<ssize_t>(size);
  7081. } else {
  7082. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  7083. read_buff_off_ += remaining_size;
  7084. return static_cast<ssize_t>(remaining_size);
  7085. }
  7086. }
  7087. if (!wait_readable()) {
  7088. error_ = Error::Timeout;
  7089. return -1;
  7090. }
  7091. read_buff_off_ = 0;
  7092. read_buff_content_size_ = 0;
  7093. if (size < read_buff_size_) {
  7094. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  7095. CPPHTTPLIB_RECV_FLAGS);
  7096. if (n <= 0) {
  7097. if (n == 0) {
  7098. error_ = Error::ConnectionClosed;
  7099. } else {
  7100. error_ = Error::Read;
  7101. }
  7102. return n;
  7103. } else if (n <= static_cast<ssize_t>(size)) {
  7104. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  7105. return n;
  7106. } else {
  7107. memcpy(ptr, read_buff_.data(), size);
  7108. read_buff_off_ = size;
  7109. read_buff_content_size_ = static_cast<size_t>(n);
  7110. return static_cast<ssize_t>(size);
  7111. }
  7112. } else {
  7113. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  7114. if (n <= 0) {
  7115. if (n == 0) {
  7116. error_ = Error::ConnectionClosed;
  7117. } else {
  7118. error_ = Error::Read;
  7119. }
  7120. }
  7121. return n;
  7122. }
  7123. }
  7124. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  7125. if (!wait_writable()) { return -1; }
  7126. #if defined(_WIN32) && !defined(_WIN64)
  7127. size =
  7128. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7129. #endif
  7130. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  7131. }
  7132. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  7133. int &port) const {
  7134. return detail::get_remote_ip_and_port(sock_, ip, port);
  7135. }
  7136. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  7137. int &port) const {
  7138. return detail::get_local_ip_and_port(sock_, ip, port);
  7139. }
  7140. inline socket_t SocketStream::socket() const { return sock_; }
  7141. inline time_t SocketStream::duration() const {
  7142. return std::chrono::duration_cast<std::chrono::milliseconds>(
  7143. std::chrono::steady_clock::now() - start_time_)
  7144. .count();
  7145. }
  7146. // Buffer stream implementation
  7147. inline bool BufferStream::is_readable() const { return true; }
  7148. inline bool BufferStream::wait_readable() const { return true; }
  7149. inline bool BufferStream::wait_writable() const { return true; }
  7150. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  7151. #if defined(_MSC_VER) && _MSC_VER < 1910
  7152. auto len_read = buffer._Copy_s(ptr, size, size, position);
  7153. #else
  7154. auto len_read = buffer.copy(ptr, size, position);
  7155. #endif
  7156. position += static_cast<size_t>(len_read);
  7157. return static_cast<ssize_t>(len_read);
  7158. }
  7159. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  7160. buffer.append(ptr, size);
  7161. return static_cast<ssize_t>(size);
  7162. }
  7163. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  7164. int & /*port*/) const {}
  7165. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  7166. int & /*port*/) const {}
  7167. inline socket_t BufferStream::socket() const { return 0; }
  7168. inline time_t BufferStream::duration() const { return 0; }
  7169. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  7170. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  7171. : MatcherBase(pattern) {
  7172. constexpr const char marker[] = "/:";
  7173. // One past the last ending position of a path param substring
  7174. std::size_t last_param_end = 0;
  7175. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7176. // Needed to ensure that parameter names are unique during matcher
  7177. // construction
  7178. // If exceptions are disabled, only last duplicate path
  7179. // parameter will be set
  7180. std::unordered_set<std::string> param_name_set;
  7181. #endif
  7182. while (true) {
  7183. const auto marker_pos = pattern.find(
  7184. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  7185. if (marker_pos == std::string::npos) { break; }
  7186. static_fragments_.push_back(
  7187. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  7188. const auto param_name_start = marker_pos + str_len(marker);
  7189. auto sep_pos = pattern.find(separator, param_name_start);
  7190. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  7191. auto param_name =
  7192. pattern.substr(param_name_start, sep_pos - param_name_start);
  7193. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7194. if (param_name_set.find(param_name) != param_name_set.cend()) {
  7195. std::string msg = "Encountered path parameter '" + param_name +
  7196. "' multiple times in route pattern '" + pattern + "'.";
  7197. throw std::invalid_argument(msg);
  7198. }
  7199. #endif
  7200. param_names_.push_back(std::move(param_name));
  7201. last_param_end = sep_pos + 1;
  7202. }
  7203. if (last_param_end < pattern.length()) {
  7204. static_fragments_.push_back(pattern.substr(last_param_end));
  7205. }
  7206. }
  7207. inline bool PathParamsMatcher::match(Request &request) const {
  7208. request.matches = std::smatch();
  7209. request.path_params.clear();
  7210. request.path_params.reserve(param_names_.size());
  7211. // One past the position at which the path matched the pattern last time
  7212. std::size_t starting_pos = 0;
  7213. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  7214. const auto &fragment = static_fragments_[i];
  7215. if (starting_pos + fragment.length() > request.path.length()) {
  7216. return false;
  7217. }
  7218. // Avoid unnecessary allocation by using strncmp instead of substr +
  7219. // comparison
  7220. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  7221. fragment.length()) != 0) {
  7222. return false;
  7223. }
  7224. starting_pos += fragment.length();
  7225. // Should only happen when we have a static fragment after a param
  7226. // Example: '/users/:id/subscriptions'
  7227. // The 'subscriptions' fragment here does not have a corresponding param
  7228. if (i >= param_names_.size()) { continue; }
  7229. auto sep_pos = request.path.find(separator, starting_pos);
  7230. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  7231. const auto &param_name = param_names_[i];
  7232. request.path_params.emplace(
  7233. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  7234. // Mark everything up to '/' as matched
  7235. starting_pos = sep_pos + 1;
  7236. }
  7237. // Returns false if the path is longer than the pattern
  7238. return starting_pos >= request.path.length();
  7239. }
  7240. inline bool RegexMatcher::match(Request &request) const {
  7241. request.path_params.clear();
  7242. return std::regex_match(request.path, request.matches, regex_);
  7243. }
  7244. // Enclose IPv6 address in brackets if needed
  7245. inline std::string prepare_host_string(const std::string &host) {
  7246. // Enclose IPv6 address in brackets (but not if already enclosed)
  7247. if (host.find(':') == std::string::npos ||
  7248. (!host.empty() && host[0] == '[')) {
  7249. // IPv4, hostname, or already bracketed IPv6
  7250. return host;
  7251. } else {
  7252. // IPv6 address without brackets
  7253. return "[" + host + "]";
  7254. }
  7255. }
  7256. inline std::string make_host_and_port_string(const std::string &host, int port,
  7257. bool is_ssl) {
  7258. auto result = prepare_host_string(host);
  7259. // Append port if not default
  7260. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  7261. ; // do nothing
  7262. } else {
  7263. result += ":" + std::to_string(port);
  7264. }
  7265. return result;
  7266. }
  7267. // Create "host:port" string always including port number (for CONNECT method)
  7268. inline std::string
  7269. make_host_and_port_string_always_port(const std::string &host, int port) {
  7270. return prepare_host_string(host) + ":" + std::to_string(port);
  7271. }
  7272. template <typename T>
  7273. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  7274. T header_writer, Error &error) {
  7275. for (const auto &h : headers) {
  7276. if (!detail::fields::is_field_name(h.first) ||
  7277. !detail::fields::is_field_value(h.second)) {
  7278. error = Error::InvalidHeaders;
  7279. return false;
  7280. }
  7281. }
  7282. if (header_writer(strm, headers) <= 0) {
  7283. error = Error::Write;
  7284. return false;
  7285. }
  7286. return true;
  7287. }
  7288. } // namespace detail
  7289. // HTTP server implementation
  7290. inline Server::Server()
  7291. : new_task_queue(
  7292. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  7293. #ifndef _WIN32
  7294. signal(SIGPIPE, SIG_IGN);
  7295. #endif
  7296. }
  7297. inline Server::~Server() = default;
  7298. inline std::unique_ptr<detail::MatcherBase>
  7299. Server::make_matcher(const std::string &pattern) {
  7300. if (pattern.find("/:") != std::string::npos) {
  7301. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  7302. } else {
  7303. return detail::make_unique<detail::RegexMatcher>(pattern);
  7304. }
  7305. }
  7306. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  7307. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7308. return *this;
  7309. }
  7310. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  7311. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7312. return *this;
  7313. }
  7314. inline Server &Server::Post(const std::string &pattern,
  7315. HandlerWithContentReader handler) {
  7316. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7317. std::move(handler));
  7318. return *this;
  7319. }
  7320. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  7321. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7322. return *this;
  7323. }
  7324. inline Server &Server::Put(const std::string &pattern,
  7325. HandlerWithContentReader handler) {
  7326. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7327. std::move(handler));
  7328. return *this;
  7329. }
  7330. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  7331. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7332. return *this;
  7333. }
  7334. inline Server &Server::Patch(const std::string &pattern,
  7335. HandlerWithContentReader handler) {
  7336. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7337. std::move(handler));
  7338. return *this;
  7339. }
  7340. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  7341. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7342. return *this;
  7343. }
  7344. inline Server &Server::Delete(const std::string &pattern,
  7345. HandlerWithContentReader handler) {
  7346. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7347. std::move(handler));
  7348. return *this;
  7349. }
  7350. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  7351. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7352. return *this;
  7353. }
  7354. inline bool Server::set_base_dir(const std::string &dir,
  7355. const std::string &mount_point) {
  7356. return set_mount_point(mount_point, dir);
  7357. }
  7358. inline bool Server::set_mount_point(const std::string &mount_point,
  7359. const std::string &dir, Headers headers) {
  7360. detail::FileStat stat(dir);
  7361. if (stat.is_dir()) {
  7362. std::string mnt = !mount_point.empty() ? mount_point : "/";
  7363. if (!mnt.empty() && mnt[0] == '/') {
  7364. base_dirs_.push_back({std::move(mnt), dir, std::move(headers)});
  7365. return true;
  7366. }
  7367. }
  7368. return false;
  7369. }
  7370. inline bool Server::remove_mount_point(const std::string &mount_point) {
  7371. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  7372. if (it->mount_point == mount_point) {
  7373. base_dirs_.erase(it);
  7374. return true;
  7375. }
  7376. }
  7377. return false;
  7378. }
  7379. inline Server &
  7380. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  7381. const std::string &mime) {
  7382. file_extension_and_mimetype_map_[ext] = mime;
  7383. return *this;
  7384. }
  7385. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  7386. default_file_mimetype_ = mime;
  7387. return *this;
  7388. }
  7389. inline Server &Server::set_file_request_handler(Handler handler) {
  7390. file_request_handler_ = std::move(handler);
  7391. return *this;
  7392. }
  7393. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  7394. std::true_type) {
  7395. error_handler_ = std::move(handler);
  7396. return *this;
  7397. }
  7398. inline Server &Server::set_error_handler_core(Handler handler,
  7399. std::false_type) {
  7400. error_handler_ = [handler](const Request &req, Response &res) {
  7401. handler(req, res);
  7402. return HandlerResponse::Handled;
  7403. };
  7404. return *this;
  7405. }
  7406. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  7407. exception_handler_ = std::move(handler);
  7408. return *this;
  7409. }
  7410. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  7411. pre_routing_handler_ = std::move(handler);
  7412. return *this;
  7413. }
  7414. inline Server &Server::set_post_routing_handler(Handler handler) {
  7415. post_routing_handler_ = std::move(handler);
  7416. return *this;
  7417. }
  7418. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  7419. pre_request_handler_ = std::move(handler);
  7420. return *this;
  7421. }
  7422. inline Server &Server::set_logger(Logger logger) {
  7423. logger_ = std::move(logger);
  7424. return *this;
  7425. }
  7426. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  7427. error_logger_ = std::move(error_logger);
  7428. return *this;
  7429. }
  7430. inline Server &Server::set_pre_compression_logger(Logger logger) {
  7431. pre_compression_logger_ = std::move(logger);
  7432. return *this;
  7433. }
  7434. inline Server &
  7435. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  7436. expect_100_continue_handler_ = std::move(handler);
  7437. return *this;
  7438. }
  7439. inline Server &Server::set_address_family(int family) {
  7440. address_family_ = family;
  7441. return *this;
  7442. }
  7443. inline Server &Server::set_tcp_nodelay(bool on) {
  7444. tcp_nodelay_ = on;
  7445. return *this;
  7446. }
  7447. inline Server &Server::set_ipv6_v6only(bool on) {
  7448. ipv6_v6only_ = on;
  7449. return *this;
  7450. }
  7451. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  7452. socket_options_ = std::move(socket_options);
  7453. return *this;
  7454. }
  7455. inline Server &Server::set_default_headers(Headers headers) {
  7456. default_headers_ = std::move(headers);
  7457. return *this;
  7458. }
  7459. inline Server &Server::set_header_writer(
  7460. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7461. header_writer_ = writer;
  7462. return *this;
  7463. }
  7464. inline Server &
  7465. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  7466. trusted_proxies_ = proxies;
  7467. return *this;
  7468. }
  7469. inline Server &Server::set_keep_alive_max_count(size_t count) {
  7470. keep_alive_max_count_ = count;
  7471. return *this;
  7472. }
  7473. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  7474. keep_alive_timeout_sec_ = sec;
  7475. return *this;
  7476. }
  7477. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  7478. read_timeout_sec_ = sec;
  7479. read_timeout_usec_ = usec;
  7480. return *this;
  7481. }
  7482. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  7483. write_timeout_sec_ = sec;
  7484. write_timeout_usec_ = usec;
  7485. return *this;
  7486. }
  7487. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  7488. idle_interval_sec_ = sec;
  7489. idle_interval_usec_ = usec;
  7490. return *this;
  7491. }
  7492. inline Server &Server::set_payload_max_length(size_t length) {
  7493. payload_max_length_ = length;
  7494. return *this;
  7495. }
  7496. inline bool Server::bind_to_port(const std::string &host, int port,
  7497. int socket_flags) {
  7498. auto ret = bind_internal(host, port, socket_flags);
  7499. if (ret == -1) { is_decommissioned = true; }
  7500. return ret >= 0;
  7501. }
  7502. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  7503. auto ret = bind_internal(host, 0, socket_flags);
  7504. if (ret == -1) { is_decommissioned = true; }
  7505. return ret;
  7506. }
  7507. inline bool Server::listen_after_bind() { return listen_internal(); }
  7508. inline bool Server::listen(const std::string &host, int port,
  7509. int socket_flags) {
  7510. return bind_to_port(host, port, socket_flags) && listen_internal();
  7511. }
  7512. inline bool Server::is_running() const { return is_running_; }
  7513. inline void Server::wait_until_ready() const {
  7514. while (!is_running_ && !is_decommissioned) {
  7515. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7516. }
  7517. }
  7518. inline void Server::stop() {
  7519. if (is_running_) {
  7520. assert(svr_sock_ != INVALID_SOCKET);
  7521. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  7522. detail::shutdown_socket(sock);
  7523. detail::close_socket(sock);
  7524. }
  7525. is_decommissioned = false;
  7526. }
  7527. inline void Server::decommission() { is_decommissioned = true; }
  7528. inline bool Server::parse_request_line(const char *s, Request &req) const {
  7529. auto len = strlen(s);
  7530. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  7531. len -= 2;
  7532. {
  7533. size_t count = 0;
  7534. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  7535. switch (count) {
  7536. case 0: req.method = std::string(b, e); break;
  7537. case 1: req.target = std::string(b, e); break;
  7538. case 2: req.version = std::string(b, e); break;
  7539. default: break;
  7540. }
  7541. count++;
  7542. });
  7543. if (count != 3) { return false; }
  7544. }
  7545. thread_local const std::set<std::string> methods{
  7546. "GET", "HEAD", "POST", "PUT", "DELETE",
  7547. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7548. if (methods.find(req.method) == methods.end()) {
  7549. output_error_log(Error::InvalidHTTPMethod, &req);
  7550. return false;
  7551. }
  7552. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  7553. output_error_log(Error::InvalidHTTPVersion, &req);
  7554. return false;
  7555. }
  7556. {
  7557. // Skip URL fragment
  7558. for (size_t i = 0; i < req.target.size(); i++) {
  7559. if (req.target[i] == '#') {
  7560. req.target.erase(i);
  7561. break;
  7562. }
  7563. }
  7564. detail::divide(req.target, '?',
  7565. [&](const char *lhs_data, std::size_t lhs_size,
  7566. const char *rhs_data, std::size_t rhs_size) {
  7567. req.path =
  7568. decode_path_component(std::string(lhs_data, lhs_size));
  7569. detail::parse_query_text(rhs_data, rhs_size, req.params);
  7570. });
  7571. }
  7572. return true;
  7573. }
  7574. inline bool Server::write_response(Stream &strm, bool close_connection,
  7575. Request &req, Response &res) {
  7576. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  7577. // incorrectly to the error content.
  7578. req.ranges.clear();
  7579. return write_response_core(strm, close_connection, req, res, false);
  7580. }
  7581. inline bool Server::write_response_with_content(Stream &strm,
  7582. bool close_connection,
  7583. const Request &req,
  7584. Response &res) {
  7585. return write_response_core(strm, close_connection, req, res, true);
  7586. }
  7587. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  7588. const Request &req, Response &res,
  7589. bool need_apply_ranges) {
  7590. assert(res.status != -1);
  7591. if (400 <= res.status && error_handler_ &&
  7592. error_handler_(req, res) == HandlerResponse::Handled) {
  7593. need_apply_ranges = true;
  7594. }
  7595. std::string content_type;
  7596. std::string boundary;
  7597. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  7598. // Prepare additional headers
  7599. if (close_connection || req.get_header_value("Connection") == "close" ||
  7600. 400 <= res.status) { // Don't leave connections open after errors
  7601. res.set_header("Connection", "close");
  7602. } else {
  7603. std::string s = "timeout=";
  7604. s += std::to_string(keep_alive_timeout_sec_);
  7605. s += ", max=";
  7606. s += std::to_string(keep_alive_max_count_);
  7607. res.set_header("Keep-Alive", s);
  7608. }
  7609. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  7610. !res.has_header("Content-Type")) {
  7611. res.set_header("Content-Type", "text/plain");
  7612. }
  7613. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  7614. !res.has_header("Content-Length")) {
  7615. res.set_header("Content-Length", "0");
  7616. }
  7617. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  7618. res.set_header("Accept-Ranges", "bytes");
  7619. }
  7620. if (post_routing_handler_) { post_routing_handler_(req, res); }
  7621. // Response line and headers
  7622. {
  7623. detail::BufferStream bstrm;
  7624. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  7625. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  7626. // Flush buffer
  7627. auto &data = bstrm.get_buffer();
  7628. detail::write_data(strm, data.data(), data.size());
  7629. }
  7630. // Body
  7631. auto ret = true;
  7632. if (req.method != "HEAD") {
  7633. if (!res.body.empty()) {
  7634. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  7635. ret = false;
  7636. }
  7637. } else if (res.content_provider_) {
  7638. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  7639. res.content_provider_success_ = true;
  7640. } else {
  7641. ret = false;
  7642. }
  7643. }
  7644. }
  7645. // Log
  7646. output_log(req, res);
  7647. return ret;
  7648. }
  7649. inline bool
  7650. Server::write_content_with_provider(Stream &strm, const Request &req,
  7651. Response &res, const std::string &boundary,
  7652. const std::string &content_type) {
  7653. auto is_shutting_down = [this]() {
  7654. return this->svr_sock_ == INVALID_SOCKET;
  7655. };
  7656. if (res.content_length_ > 0) {
  7657. if (req.ranges.empty()) {
  7658. return detail::write_content(strm, res.content_provider_, 0,
  7659. res.content_length_, is_shutting_down);
  7660. } else if (req.ranges.size() == 1) {
  7661. auto offset_and_length = detail::get_range_offset_and_length(
  7662. req.ranges[0], res.content_length_);
  7663. return detail::write_content(strm, res.content_provider_,
  7664. offset_and_length.first,
  7665. offset_and_length.second, is_shutting_down);
  7666. } else {
  7667. return detail::write_multipart_ranges_data(
  7668. strm, req, res, boundary, content_type, res.content_length_,
  7669. is_shutting_down);
  7670. }
  7671. } else {
  7672. if (res.is_chunked_content_provider_) {
  7673. auto type = detail::encoding_type(req, res);
  7674. std::unique_ptr<detail::compressor> compressor;
  7675. if (type == detail::EncodingType::Gzip) {
  7676. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7677. compressor = detail::make_unique<detail::gzip_compressor>();
  7678. #endif
  7679. } else if (type == detail::EncodingType::Brotli) {
  7680. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7681. compressor = detail::make_unique<detail::brotli_compressor>();
  7682. #endif
  7683. } else if (type == detail::EncodingType::Zstd) {
  7684. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7685. compressor = detail::make_unique<detail::zstd_compressor>();
  7686. #endif
  7687. } else {
  7688. compressor = detail::make_unique<detail::nocompressor>();
  7689. }
  7690. assert(compressor != nullptr);
  7691. return detail::write_content_chunked(strm, res.content_provider_,
  7692. is_shutting_down, *compressor);
  7693. } else {
  7694. return detail::write_content_without_length(strm, res.content_provider_,
  7695. is_shutting_down);
  7696. }
  7697. }
  7698. }
  7699. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  7700. FormFields::iterator cur_field;
  7701. FormFiles::iterator cur_file;
  7702. auto is_text_field = false;
  7703. size_t count = 0;
  7704. if (read_content_core(
  7705. strm, req, res,
  7706. // Regular
  7707. [&](const char *buf, size_t n) {
  7708. // Prevent arithmetic overflow when checking sizes.
  7709. // Avoid computing (req.body.size() + n) directly because
  7710. // adding two unsigned `size_t` values can wrap around and
  7711. // produce a small result instead of indicating overflow.
  7712. // Instead, check using subtraction: ensure `n` does not
  7713. // exceed the remaining capacity `max_size() - size()`.
  7714. if (req.body.size() >= req.body.max_size() ||
  7715. n > req.body.max_size() - req.body.size()) {
  7716. return false;
  7717. }
  7718. // Limit decompressed body size to payload_max_length_ to protect
  7719. // against "zip bomb" attacks where a small compressed payload
  7720. // decompresses to a massive size.
  7721. if (payload_max_length_ > 0 &&
  7722. (req.body.size() >= payload_max_length_ ||
  7723. n > payload_max_length_ - req.body.size())) {
  7724. return false;
  7725. }
  7726. req.body.append(buf, n);
  7727. return true;
  7728. },
  7729. // Multipart FormData
  7730. [&](const FormData &file) {
  7731. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  7732. output_error_log(Error::TooManyFormDataFiles, &req);
  7733. return false;
  7734. }
  7735. if (file.filename.empty()) {
  7736. cur_field = req.form.fields.emplace(
  7737. file.name, FormField{file.name, file.content, file.headers});
  7738. is_text_field = true;
  7739. } else {
  7740. cur_file = req.form.files.emplace(file.name, file);
  7741. is_text_field = false;
  7742. }
  7743. return true;
  7744. },
  7745. [&](const char *buf, size_t n) {
  7746. if (is_text_field) {
  7747. auto &content = cur_field->second.content;
  7748. if (content.size() + n > content.max_size()) { return false; }
  7749. content.append(buf, n);
  7750. } else {
  7751. auto &content = cur_file->second.content;
  7752. if (content.size() + n > content.max_size()) { return false; }
  7753. content.append(buf, n);
  7754. }
  7755. return true;
  7756. })) {
  7757. const auto &content_type = req.get_header_value("Content-Type");
  7758. if (!content_type.find("application/x-www-form-urlencoded")) {
  7759. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  7760. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  7761. output_error_log(Error::ExceedMaxPayloadSize, &req);
  7762. return false;
  7763. }
  7764. detail::parse_query_text(req.body, req.params);
  7765. }
  7766. return true;
  7767. }
  7768. return false;
  7769. }
  7770. inline bool Server::read_content_with_content_receiver(
  7771. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7772. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  7773. return read_content_core(strm, req, res, std::move(receiver),
  7774. std::move(multipart_header),
  7775. std::move(multipart_receiver));
  7776. }
  7777. inline bool Server::read_content_core(
  7778. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7779. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  7780. detail::FormDataParser multipart_form_data_parser;
  7781. ContentReceiverWithProgress out;
  7782. if (req.is_multipart_form_data()) {
  7783. const auto &content_type = req.get_header_value("Content-Type");
  7784. std::string boundary;
  7785. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  7786. res.status = StatusCode::BadRequest_400;
  7787. output_error_log(Error::MultipartParsing, &req);
  7788. return false;
  7789. }
  7790. multipart_form_data_parser.set_boundary(std::move(boundary));
  7791. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  7792. return multipart_form_data_parser.parse(buf, n, multipart_header,
  7793. multipart_receiver);
  7794. };
  7795. } else {
  7796. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  7797. size_t /*len*/) { return receiver(buf, n); };
  7798. }
  7799. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  7800. // are true (no Transfer-Encoding and no Content-Length), then the message
  7801. // body length is zero (no message body is present).
  7802. //
  7803. // For non-SSL builds, peek into the socket to detect clients that send a
  7804. // body without a Content-Length header (raw HTTP over TCP). If there is
  7805. // pending data that exceeds the configured payload limit, treat this as an
  7806. // oversized request and fail early (causing connection close). For SSL
  7807. // builds we cannot reliably peek the decrypted application bytes, so keep
  7808. // the original behaviour.
  7809. #if !defined(CPPHTTPLIB_OPENSSL_SUPPORT)
  7810. if (!req.has_header("Content-Length") &&
  7811. !detail::is_chunked_transfer_encoding(req.headers)) {
  7812. // Only peek if payload_max_length is set to a finite value
  7813. if (payload_max_length_ > 0 &&
  7814. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  7815. socket_t s = strm.socket();
  7816. if (s != INVALID_SOCKET) {
  7817. // Peek to check if there is any pending data
  7818. char peekbuf[1];
  7819. ssize_t n = ::recv(s, peekbuf, 1, MSG_PEEK);
  7820. if (n > 0) {
  7821. // There is data, so read it with payload limit enforcement
  7822. auto result = detail::read_content_without_length(
  7823. strm, payload_max_length_, out);
  7824. if (result == detail::ReadContentResult::PayloadTooLarge) {
  7825. res.status = StatusCode::PayloadTooLarge_413;
  7826. return false;
  7827. } else if (result != detail::ReadContentResult::Success) {
  7828. return false;
  7829. }
  7830. return true;
  7831. }
  7832. }
  7833. }
  7834. return true;
  7835. }
  7836. #else
  7837. if (!req.has_header("Content-Length") &&
  7838. !detail::is_chunked_transfer_encoding(req.headers)) {
  7839. return true;
  7840. }
  7841. #endif
  7842. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  7843. out, true)) {
  7844. return false;
  7845. }
  7846. if (req.is_multipart_form_data()) {
  7847. if (!multipart_form_data_parser.is_valid()) {
  7848. res.status = StatusCode::BadRequest_400;
  7849. output_error_log(Error::MultipartParsing, &req);
  7850. return false;
  7851. }
  7852. }
  7853. return true;
  7854. }
  7855. inline bool Server::handle_file_request(Request &req, Response &res) {
  7856. for (const auto &entry : base_dirs_) {
  7857. // Prefix match
  7858. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  7859. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  7860. if (detail::is_valid_path(sub_path)) {
  7861. auto path = entry.base_dir + sub_path;
  7862. if (path.back() == '/') { path += "index.html"; }
  7863. detail::FileStat stat(path);
  7864. if (stat.is_dir()) {
  7865. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  7866. return true;
  7867. }
  7868. if (stat.is_file()) {
  7869. for (const auto &kv : entry.headers) {
  7870. res.set_header(kv.first, kv.second);
  7871. }
  7872. auto etag = detail::compute_etag(stat);
  7873. if (!etag.empty()) { res.set_header("ETag", etag); }
  7874. auto mtime = stat.mtime();
  7875. auto last_modified = detail::file_mtime_to_http_date(mtime);
  7876. if (!last_modified.empty()) {
  7877. res.set_header("Last-Modified", last_modified);
  7878. }
  7879. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  7880. check_if_range(req, etag, mtime);
  7881. auto mm = std::make_shared<detail::mmap>(path.c_str());
  7882. if (!mm->is_open()) {
  7883. output_error_log(Error::OpenFile, &req);
  7884. return false;
  7885. }
  7886. res.set_content_provider(
  7887. mm->size(),
  7888. detail::find_content_type(path, file_extension_and_mimetype_map_,
  7889. default_file_mimetype_),
  7890. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  7891. sink.write(mm->data() + offset, length);
  7892. return true;
  7893. });
  7894. if (req.method != "HEAD" && file_request_handler_) {
  7895. file_request_handler_(req, res);
  7896. }
  7897. return true;
  7898. } else {
  7899. output_error_log(Error::OpenFile, &req);
  7900. }
  7901. }
  7902. }
  7903. }
  7904. return false;
  7905. }
  7906. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  7907. const std::string &etag,
  7908. time_t mtime) const {
  7909. // Handle conditional GET:
  7910. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  7911. // 2. If-Modified-Since is checked only when If-None-Match is absent
  7912. if (req.has_header("If-None-Match")) {
  7913. if (!etag.empty()) {
  7914. auto val = req.get_header_value("If-None-Match");
  7915. // NOTE: We use exact string matching here. This works correctly
  7916. // because our server always generates weak ETags (W/"..."), and
  7917. // clients typically send back the same ETag they received.
  7918. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  7919. // If-None-Match, where W/"x" and "x" would match, but this
  7920. // simplified implementation requires exact matches.
  7921. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  7922. [&](const char *b, const char *e) {
  7923. return std::equal(b, e, "*") ||
  7924. std::equal(b, e, etag.begin());
  7925. });
  7926. if (ret) {
  7927. res.status = StatusCode::NotModified_304;
  7928. return true;
  7929. }
  7930. }
  7931. } else if (req.has_header("If-Modified-Since")) {
  7932. auto val = req.get_header_value("If-Modified-Since");
  7933. auto t = detail::parse_http_date(val);
  7934. if (t != static_cast<time_t>(-1) && mtime <= t) {
  7935. res.status = StatusCode::NotModified_304;
  7936. return true;
  7937. }
  7938. }
  7939. return false;
  7940. }
  7941. inline bool Server::check_if_range(Request &req, const std::string &etag,
  7942. time_t mtime) const {
  7943. // Handle If-Range for partial content requests (RFC 9110
  7944. // Section 13.1.5). If-Range is only evaluated when Range header is
  7945. // present. If the validator matches, serve partial content; otherwise
  7946. // serve full content.
  7947. if (!req.ranges.empty() && req.has_header("If-Range")) {
  7948. auto val = req.get_header_value("If-Range");
  7949. auto is_valid_range = [&]() {
  7950. if (detail::is_strong_etag(val)) {
  7951. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  7952. // comparison.
  7953. return (!etag.empty() && val == etag);
  7954. } else if (detail::is_weak_etag(val)) {
  7955. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  7956. return false;
  7957. } else {
  7958. // HTTP-date comparison
  7959. auto t = detail::parse_http_date(val);
  7960. return (t != static_cast<time_t>(-1) && mtime <= t);
  7961. }
  7962. };
  7963. if (!is_valid_range()) {
  7964. // Validator doesn't match: ignore Range and serve full content
  7965. req.ranges.clear();
  7966. return false;
  7967. }
  7968. }
  7969. return true;
  7970. }
  7971. inline socket_t
  7972. Server::create_server_socket(const std::string &host, int port,
  7973. int socket_flags,
  7974. SocketOptions socket_options) const {
  7975. return detail::create_socket(
  7976. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  7977. ipv6_v6only_, std::move(socket_options),
  7978. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  7979. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  7980. output_error_log(Error::BindIPAddress, nullptr);
  7981. return false;
  7982. }
  7983. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  7984. output_error_log(Error::Listen, nullptr);
  7985. return false;
  7986. }
  7987. return true;
  7988. });
  7989. }
  7990. inline int Server::bind_internal(const std::string &host, int port,
  7991. int socket_flags) {
  7992. if (is_decommissioned) { return -1; }
  7993. if (!is_valid()) { return -1; }
  7994. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  7995. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  7996. if (port == 0) {
  7997. struct sockaddr_storage addr;
  7998. socklen_t addr_len = sizeof(addr);
  7999. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  8000. &addr_len) == -1) {
  8001. output_error_log(Error::GetSockName, nullptr);
  8002. return -1;
  8003. }
  8004. if (addr.ss_family == AF_INET) {
  8005. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  8006. } else if (addr.ss_family == AF_INET6) {
  8007. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  8008. } else {
  8009. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  8010. return -1;
  8011. }
  8012. } else {
  8013. return port;
  8014. }
  8015. }
  8016. inline bool Server::listen_internal() {
  8017. if (is_decommissioned) { return false; }
  8018. auto ret = true;
  8019. is_running_ = true;
  8020. auto se = detail::scope_exit([&]() { is_running_ = false; });
  8021. {
  8022. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  8023. while (svr_sock_ != INVALID_SOCKET) {
  8024. #ifndef _WIN32
  8025. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  8026. #endif
  8027. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  8028. idle_interval_usec_);
  8029. if (val == 0) { // Timeout
  8030. task_queue->on_idle();
  8031. continue;
  8032. }
  8033. #ifndef _WIN32
  8034. }
  8035. #endif
  8036. #if defined _WIN32
  8037. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  8038. // OVERLAPPED
  8039. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  8040. #elif defined SOCK_CLOEXEC
  8041. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  8042. #else
  8043. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  8044. #endif
  8045. if (sock == INVALID_SOCKET) {
  8046. if (errno == EMFILE) {
  8047. // The per-process limit of open file descriptors has been reached.
  8048. // Try to accept new connections after a short sleep.
  8049. std::this_thread::sleep_for(std::chrono::microseconds{1});
  8050. continue;
  8051. } else if (errno == EINTR || errno == EAGAIN) {
  8052. continue;
  8053. }
  8054. if (svr_sock_ != INVALID_SOCKET) {
  8055. detail::close_socket(svr_sock_);
  8056. ret = false;
  8057. output_error_log(Error::Connection, nullptr);
  8058. } else {
  8059. ; // The server socket was closed by user.
  8060. }
  8061. break;
  8062. }
  8063. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  8064. read_timeout_sec_, read_timeout_usec_);
  8065. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  8066. write_timeout_sec_, write_timeout_usec_);
  8067. if (!task_queue->enqueue(
  8068. [this, sock]() { process_and_close_socket(sock); })) {
  8069. output_error_log(Error::ResourceExhaustion, nullptr);
  8070. detail::shutdown_socket(sock);
  8071. detail::close_socket(sock);
  8072. }
  8073. }
  8074. task_queue->shutdown();
  8075. }
  8076. is_decommissioned = !ret;
  8077. return ret;
  8078. }
  8079. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  8080. if (pre_routing_handler_ &&
  8081. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  8082. return true;
  8083. }
  8084. // File handler
  8085. if ((req.method == "GET" || req.method == "HEAD") &&
  8086. handle_file_request(req, res)) {
  8087. return true;
  8088. }
  8089. if (detail::expect_content(req)) {
  8090. // Content reader handler
  8091. {
  8092. ContentReader reader(
  8093. [&](ContentReceiver receiver) {
  8094. auto result = read_content_with_content_receiver(
  8095. strm, req, res, std::move(receiver), nullptr, nullptr);
  8096. if (!result) { output_error_log(Error::Read, &req); }
  8097. return result;
  8098. },
  8099. [&](FormDataHeader header, ContentReceiver receiver) {
  8100. auto result = read_content_with_content_receiver(
  8101. strm, req, res, nullptr, std::move(header),
  8102. std::move(receiver));
  8103. if (!result) { output_error_log(Error::Read, &req); }
  8104. return result;
  8105. });
  8106. if (req.method == "POST") {
  8107. if (dispatch_request_for_content_reader(
  8108. req, res, std::move(reader),
  8109. post_handlers_for_content_reader_)) {
  8110. return true;
  8111. }
  8112. } else if (req.method == "PUT") {
  8113. if (dispatch_request_for_content_reader(
  8114. req, res, std::move(reader),
  8115. put_handlers_for_content_reader_)) {
  8116. return true;
  8117. }
  8118. } else if (req.method == "PATCH") {
  8119. if (dispatch_request_for_content_reader(
  8120. req, res, std::move(reader),
  8121. patch_handlers_for_content_reader_)) {
  8122. return true;
  8123. }
  8124. } else if (req.method == "DELETE") {
  8125. if (dispatch_request_for_content_reader(
  8126. req, res, std::move(reader),
  8127. delete_handlers_for_content_reader_)) {
  8128. return true;
  8129. }
  8130. }
  8131. }
  8132. // Read content into `req.body`
  8133. if (!read_content(strm, req, res)) {
  8134. output_error_log(Error::Read, &req);
  8135. return false;
  8136. }
  8137. }
  8138. // Regular handler
  8139. if (req.method == "GET" || req.method == "HEAD") {
  8140. return dispatch_request(req, res, get_handlers_);
  8141. } else if (req.method == "POST") {
  8142. return dispatch_request(req, res, post_handlers_);
  8143. } else if (req.method == "PUT") {
  8144. return dispatch_request(req, res, put_handlers_);
  8145. } else if (req.method == "DELETE") {
  8146. return dispatch_request(req, res, delete_handlers_);
  8147. } else if (req.method == "OPTIONS") {
  8148. return dispatch_request(req, res, options_handlers_);
  8149. } else if (req.method == "PATCH") {
  8150. return dispatch_request(req, res, patch_handlers_);
  8151. }
  8152. res.status = StatusCode::BadRequest_400;
  8153. return false;
  8154. }
  8155. inline bool Server::dispatch_request(Request &req, Response &res,
  8156. const Handlers &handlers) const {
  8157. for (const auto &x : handlers) {
  8158. const auto &matcher = x.first;
  8159. const auto &handler = x.second;
  8160. if (matcher->match(req)) {
  8161. req.matched_route = matcher->pattern();
  8162. if (!pre_request_handler_ ||
  8163. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8164. handler(req, res);
  8165. }
  8166. return true;
  8167. }
  8168. }
  8169. return false;
  8170. }
  8171. inline void Server::apply_ranges(const Request &req, Response &res,
  8172. std::string &content_type,
  8173. std::string &boundary) const {
  8174. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  8175. auto it = res.headers.find("Content-Type");
  8176. if (it != res.headers.end()) {
  8177. content_type = it->second;
  8178. res.headers.erase(it);
  8179. }
  8180. boundary = detail::make_multipart_data_boundary();
  8181. res.set_header("Content-Type",
  8182. "multipart/byteranges; boundary=" + boundary);
  8183. }
  8184. auto type = detail::encoding_type(req, res);
  8185. if (res.body.empty()) {
  8186. if (res.content_length_ > 0) {
  8187. size_t length = 0;
  8188. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8189. length = res.content_length_;
  8190. } else if (req.ranges.size() == 1) {
  8191. auto offset_and_length = detail::get_range_offset_and_length(
  8192. req.ranges[0], res.content_length_);
  8193. length = offset_and_length.second;
  8194. auto content_range = detail::make_content_range_header_field(
  8195. offset_and_length, res.content_length_);
  8196. res.set_header("Content-Range", content_range);
  8197. } else {
  8198. length = detail::get_multipart_ranges_data_length(
  8199. req, boundary, content_type, res.content_length_);
  8200. }
  8201. res.set_header("Content-Length", std::to_string(length));
  8202. } else {
  8203. if (res.content_provider_) {
  8204. if (res.is_chunked_content_provider_) {
  8205. res.set_header("Transfer-Encoding", "chunked");
  8206. if (type == detail::EncodingType::Gzip) {
  8207. res.set_header("Content-Encoding", "gzip");
  8208. res.set_header("Vary", "Accept-Encoding");
  8209. } else if (type == detail::EncodingType::Brotli) {
  8210. res.set_header("Content-Encoding", "br");
  8211. res.set_header("Vary", "Accept-Encoding");
  8212. } else if (type == detail::EncodingType::Zstd) {
  8213. res.set_header("Content-Encoding", "zstd");
  8214. res.set_header("Vary", "Accept-Encoding");
  8215. }
  8216. }
  8217. }
  8218. }
  8219. } else {
  8220. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8221. ;
  8222. } else if (req.ranges.size() == 1) {
  8223. auto offset_and_length =
  8224. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  8225. auto offset = offset_and_length.first;
  8226. auto length = offset_and_length.second;
  8227. auto content_range = detail::make_content_range_header_field(
  8228. offset_and_length, res.body.size());
  8229. res.set_header("Content-Range", content_range);
  8230. assert(offset + length <= res.body.size());
  8231. res.body = res.body.substr(offset, length);
  8232. } else {
  8233. std::string data;
  8234. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  8235. res.body.size(), data);
  8236. res.body.swap(data);
  8237. }
  8238. if (type != detail::EncodingType::None) {
  8239. output_pre_compression_log(req, res);
  8240. std::unique_ptr<detail::compressor> compressor;
  8241. std::string content_encoding;
  8242. if (type == detail::EncodingType::Gzip) {
  8243. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8244. compressor = detail::make_unique<detail::gzip_compressor>();
  8245. content_encoding = "gzip";
  8246. #endif
  8247. } else if (type == detail::EncodingType::Brotli) {
  8248. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8249. compressor = detail::make_unique<detail::brotli_compressor>();
  8250. content_encoding = "br";
  8251. #endif
  8252. } else if (type == detail::EncodingType::Zstd) {
  8253. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8254. compressor = detail::make_unique<detail::zstd_compressor>();
  8255. content_encoding = "zstd";
  8256. #endif
  8257. }
  8258. if (compressor) {
  8259. std::string compressed;
  8260. if (compressor->compress(res.body.data(), res.body.size(), true,
  8261. [&](const char *data, size_t data_len) {
  8262. compressed.append(data, data_len);
  8263. return true;
  8264. })) {
  8265. res.body.swap(compressed);
  8266. res.set_header("Content-Encoding", content_encoding);
  8267. res.set_header("Vary", "Accept-Encoding");
  8268. }
  8269. }
  8270. }
  8271. auto length = std::to_string(res.body.size());
  8272. res.set_header("Content-Length", length);
  8273. }
  8274. }
  8275. inline bool Server::dispatch_request_for_content_reader(
  8276. Request &req, Response &res, ContentReader content_reader,
  8277. const HandlersForContentReader &handlers) const {
  8278. for (const auto &x : handlers) {
  8279. const auto &matcher = x.first;
  8280. const auto &handler = x.second;
  8281. if (matcher->match(req)) {
  8282. req.matched_route = matcher->pattern();
  8283. if (!pre_request_handler_ ||
  8284. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8285. handler(req, res, content_reader);
  8286. }
  8287. return true;
  8288. }
  8289. }
  8290. return false;
  8291. }
  8292. inline std::string
  8293. get_client_ip(const std::string &x_forwarded_for,
  8294. const std::vector<std::string> &trusted_proxies) {
  8295. // X-Forwarded-For is a comma-separated list per RFC 7239
  8296. std::vector<std::string> ip_list;
  8297. detail::split(x_forwarded_for.data(),
  8298. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  8299. [&](const char *b, const char *e) {
  8300. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  8301. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  8302. });
  8303. for (size_t i = 0; i < ip_list.size(); ++i) {
  8304. auto ip = ip_list[i];
  8305. auto is_trusted_proxy =
  8306. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  8307. [&](const std::string &proxy) { return ip == proxy; });
  8308. if (is_trusted_proxy) {
  8309. if (i == 0) {
  8310. // If the trusted proxy is the first IP, there's no preceding client IP
  8311. return ip;
  8312. } else {
  8313. // Return the IP immediately before the trusted proxy
  8314. return ip_list[i - 1];
  8315. }
  8316. }
  8317. }
  8318. // If no trusted proxy is found, return the first IP in the list
  8319. return ip_list.front();
  8320. }
  8321. inline bool
  8322. Server::process_request(Stream &strm, const std::string &remote_addr,
  8323. int remote_port, const std::string &local_addr,
  8324. int local_port, bool close_connection,
  8325. bool &connection_closed,
  8326. const std::function<void(Request &)> &setup_request) {
  8327. std::array<char, 2048> buf{};
  8328. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8329. // Connection has been closed on client
  8330. if (!line_reader.getline()) { return false; }
  8331. Request req;
  8332. req.start_time_ = std::chrono::steady_clock::now();
  8333. req.remote_addr = remote_addr;
  8334. req.remote_port = remote_port;
  8335. req.local_addr = local_addr;
  8336. req.local_port = local_port;
  8337. Response res;
  8338. res.version = "HTTP/1.1";
  8339. res.headers = default_headers_;
  8340. #ifdef __APPLE__
  8341. // Socket file descriptor exceeded FD_SETSIZE...
  8342. if (strm.socket() >= FD_SETSIZE) {
  8343. Headers dummy;
  8344. detail::read_headers(strm, dummy);
  8345. res.status = StatusCode::InternalServerError_500;
  8346. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  8347. return write_response(strm, close_connection, req, res);
  8348. }
  8349. #endif
  8350. // Request line and headers
  8351. if (!parse_request_line(line_reader.ptr(), req)) {
  8352. res.status = StatusCode::BadRequest_400;
  8353. output_error_log(Error::InvalidRequestLine, &req);
  8354. return write_response(strm, close_connection, req, res);
  8355. }
  8356. // Request headers
  8357. if (!detail::read_headers(strm, req.headers)) {
  8358. res.status = StatusCode::BadRequest_400;
  8359. output_error_log(Error::InvalidHeaders, &req);
  8360. return write_response(strm, close_connection, req, res);
  8361. }
  8362. // Check if the request URI doesn't exceed the limit
  8363. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  8364. res.status = StatusCode::UriTooLong_414;
  8365. output_error_log(Error::ExceedUriMaxLength, &req);
  8366. return write_response(strm, close_connection, req, res);
  8367. }
  8368. if (req.get_header_value("Connection") == "close") {
  8369. connection_closed = true;
  8370. }
  8371. if (req.version == "HTTP/1.0" &&
  8372. req.get_header_value("Connection") != "Keep-Alive") {
  8373. connection_closed = true;
  8374. }
  8375. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  8376. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  8377. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  8378. } else {
  8379. req.remote_addr = remote_addr;
  8380. }
  8381. req.remote_port = remote_port;
  8382. req.local_addr = local_addr;
  8383. req.local_port = local_port;
  8384. if (req.has_header("Accept")) {
  8385. const auto &accept_header = req.get_header_value("Accept");
  8386. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  8387. res.status = StatusCode::BadRequest_400;
  8388. output_error_log(Error::HTTPParsing, &req);
  8389. return write_response(strm, close_connection, req, res);
  8390. }
  8391. }
  8392. if (req.has_header("Range")) {
  8393. const auto &range_header_value = req.get_header_value("Range");
  8394. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  8395. res.status = StatusCode::RangeNotSatisfiable_416;
  8396. output_error_log(Error::InvalidRangeHeader, &req);
  8397. return write_response(strm, close_connection, req, res);
  8398. }
  8399. }
  8400. if (setup_request) { setup_request(req); }
  8401. if (req.get_header_value("Expect") == "100-continue") {
  8402. int status = StatusCode::Continue_100;
  8403. if (expect_100_continue_handler_) {
  8404. status = expect_100_continue_handler_(req, res);
  8405. }
  8406. switch (status) {
  8407. case StatusCode::Continue_100:
  8408. case StatusCode::ExpectationFailed_417:
  8409. detail::write_response_line(strm, status);
  8410. strm.write("\r\n");
  8411. break;
  8412. default:
  8413. connection_closed = true;
  8414. return write_response(strm, true, req, res);
  8415. }
  8416. }
  8417. // Setup `is_connection_closed` method
  8418. auto sock = strm.socket();
  8419. req.is_connection_closed = [sock]() {
  8420. return !detail::is_socket_alive(sock);
  8421. };
  8422. // Routing
  8423. auto routed = false;
  8424. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8425. routed = routing(req, res, strm);
  8426. #else
  8427. try {
  8428. routed = routing(req, res, strm);
  8429. } catch (std::exception &e) {
  8430. if (exception_handler_) {
  8431. auto ep = std::current_exception();
  8432. exception_handler_(req, res, ep);
  8433. routed = true;
  8434. } else {
  8435. res.status = StatusCode::InternalServerError_500;
  8436. std::string val;
  8437. auto s = e.what();
  8438. for (size_t i = 0; s[i]; i++) {
  8439. switch (s[i]) {
  8440. case '\r': val += "\\r"; break;
  8441. case '\n': val += "\\n"; break;
  8442. default: val += s[i]; break;
  8443. }
  8444. }
  8445. res.set_header("EXCEPTION_WHAT", val);
  8446. }
  8447. } catch (...) {
  8448. if (exception_handler_) {
  8449. auto ep = std::current_exception();
  8450. exception_handler_(req, res, ep);
  8451. routed = true;
  8452. } else {
  8453. res.status = StatusCode::InternalServerError_500;
  8454. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  8455. }
  8456. }
  8457. #endif
  8458. if (routed) {
  8459. if (res.status == -1) {
  8460. res.status = req.ranges.empty() ? StatusCode::OK_200
  8461. : StatusCode::PartialContent_206;
  8462. }
  8463. // Serve file content by using a content provider
  8464. if (!res.file_content_path_.empty()) {
  8465. const auto &path = res.file_content_path_;
  8466. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8467. if (!mm->is_open()) {
  8468. res.body.clear();
  8469. res.content_length_ = 0;
  8470. res.content_provider_ = nullptr;
  8471. res.status = StatusCode::NotFound_404;
  8472. output_error_log(Error::OpenFile, &req);
  8473. return write_response(strm, close_connection, req, res);
  8474. }
  8475. auto content_type = res.file_content_content_type_;
  8476. if (content_type.empty()) {
  8477. content_type = detail::find_content_type(
  8478. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  8479. }
  8480. res.set_content_provider(
  8481. mm->size(), content_type,
  8482. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8483. sink.write(mm->data() + offset, length);
  8484. return true;
  8485. });
  8486. }
  8487. if (detail::range_error(req, res)) {
  8488. res.body.clear();
  8489. res.content_length_ = 0;
  8490. res.content_provider_ = nullptr;
  8491. res.status = StatusCode::RangeNotSatisfiable_416;
  8492. return write_response(strm, close_connection, req, res);
  8493. }
  8494. return write_response_with_content(strm, close_connection, req, res);
  8495. } else {
  8496. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  8497. return write_response(strm, close_connection, req, res);
  8498. }
  8499. }
  8500. inline bool Server::is_valid() const { return true; }
  8501. inline bool Server::process_and_close_socket(socket_t sock) {
  8502. std::string remote_addr;
  8503. int remote_port = 0;
  8504. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8505. std::string local_addr;
  8506. int local_port = 0;
  8507. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8508. auto ret = detail::process_server_socket(
  8509. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8510. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8511. write_timeout_usec_,
  8512. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8513. return process_request(strm, remote_addr, remote_port, local_addr,
  8514. local_port, close_connection, connection_closed,
  8515. nullptr);
  8516. });
  8517. detail::shutdown_socket(sock);
  8518. detail::close_socket(sock);
  8519. return ret;
  8520. }
  8521. inline void Server::output_log(const Request &req, const Response &res) const {
  8522. if (logger_) {
  8523. std::lock_guard<std::mutex> guard(logger_mutex_);
  8524. logger_(req, res);
  8525. }
  8526. }
  8527. inline void Server::output_pre_compression_log(const Request &req,
  8528. const Response &res) const {
  8529. if (pre_compression_logger_) {
  8530. std::lock_guard<std::mutex> guard(logger_mutex_);
  8531. pre_compression_logger_(req, res);
  8532. }
  8533. }
  8534. inline void Server::output_error_log(const Error &err,
  8535. const Request *req) const {
  8536. if (error_logger_) {
  8537. std::lock_guard<std::mutex> guard(logger_mutex_);
  8538. error_logger_(err, req);
  8539. }
  8540. }
  8541. // HTTP client implementation
  8542. inline ClientImpl::ClientImpl(const std::string &host)
  8543. : ClientImpl(host, 80, std::string(), std::string()) {}
  8544. inline ClientImpl::ClientImpl(const std::string &host, int port)
  8545. : ClientImpl(host, port, std::string(), std::string()) {}
  8546. inline ClientImpl::ClientImpl(const std::string &host, int port,
  8547. const std::string &client_cert_path,
  8548. const std::string &client_key_path)
  8549. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  8550. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  8551. inline ClientImpl::~ClientImpl() {
  8552. // Wait until all the requests in flight are handled.
  8553. size_t retry_count = 10;
  8554. while (retry_count-- > 0) {
  8555. {
  8556. std::lock_guard<std::mutex> guard(socket_mutex_);
  8557. if (socket_requests_in_flight_ == 0) { break; }
  8558. }
  8559. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  8560. }
  8561. std::lock_guard<std::mutex> guard(socket_mutex_);
  8562. shutdown_socket(socket_);
  8563. close_socket(socket_);
  8564. }
  8565. inline bool ClientImpl::is_valid() const { return true; }
  8566. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  8567. client_cert_path_ = rhs.client_cert_path_;
  8568. client_key_path_ = rhs.client_key_path_;
  8569. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  8570. read_timeout_sec_ = rhs.read_timeout_sec_;
  8571. read_timeout_usec_ = rhs.read_timeout_usec_;
  8572. write_timeout_sec_ = rhs.write_timeout_sec_;
  8573. write_timeout_usec_ = rhs.write_timeout_usec_;
  8574. max_timeout_msec_ = rhs.max_timeout_msec_;
  8575. basic_auth_username_ = rhs.basic_auth_username_;
  8576. basic_auth_password_ = rhs.basic_auth_password_;
  8577. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  8578. #ifdef CPPHTTPLIB_SSL_ENABLED
  8579. digest_auth_username_ = rhs.digest_auth_username_;
  8580. digest_auth_password_ = rhs.digest_auth_password_;
  8581. #endif
  8582. keep_alive_ = rhs.keep_alive_;
  8583. follow_location_ = rhs.follow_location_;
  8584. path_encode_ = rhs.path_encode_;
  8585. address_family_ = rhs.address_family_;
  8586. tcp_nodelay_ = rhs.tcp_nodelay_;
  8587. ipv6_v6only_ = rhs.ipv6_v6only_;
  8588. socket_options_ = rhs.socket_options_;
  8589. compress_ = rhs.compress_;
  8590. decompress_ = rhs.decompress_;
  8591. interface_ = rhs.interface_;
  8592. proxy_host_ = rhs.proxy_host_;
  8593. proxy_port_ = rhs.proxy_port_;
  8594. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  8595. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  8596. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  8597. #ifdef CPPHTTPLIB_SSL_ENABLED
  8598. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  8599. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  8600. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  8601. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  8602. server_certificate_verification_ = rhs.server_certificate_verification_;
  8603. server_hostname_verification_ = rhs.server_hostname_verification_;
  8604. #endif
  8605. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8606. ca_cert_store_ = rhs.ca_cert_store_;
  8607. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  8608. #endif
  8609. logger_ = rhs.logger_;
  8610. error_logger_ = rhs.error_logger_;
  8611. }
  8612. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  8613. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8614. return detail::create_client_socket(
  8615. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  8616. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  8617. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  8618. write_timeout_sec_, write_timeout_usec_, interface_, error);
  8619. }
  8620. // Check is custom IP specified for host_
  8621. std::string ip;
  8622. auto it = addr_map_.find(host_);
  8623. if (it != addr_map_.end()) { ip = it->second; }
  8624. return detail::create_client_socket(
  8625. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  8626. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  8627. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8628. write_timeout_usec_, interface_, error);
  8629. }
  8630. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  8631. Error &error) {
  8632. auto sock = create_client_socket(error);
  8633. if (sock == INVALID_SOCKET) { return false; }
  8634. socket.sock = sock;
  8635. return true;
  8636. }
  8637. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  8638. return create_and_connect_socket(socket, error);
  8639. }
  8640. #ifdef CPPHTTPLIB_SSL_ENABLED
  8641. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  8642. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  8643. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  8644. if (!initialize_ssl(socket, error)) {
  8645. shutdown_socket(socket);
  8646. close_socket(socket);
  8647. return false;
  8648. }
  8649. return true;
  8650. }
  8651. #endif
  8652. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  8653. bool /*shutdown_gracefully*/) {
  8654. // If there are any requests in flight from threads other than us, then it's
  8655. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  8656. assert(socket_requests_in_flight_ == 0 ||
  8657. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8658. }
  8659. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  8660. if (socket.sock == INVALID_SOCKET) { return; }
  8661. detail::shutdown_socket(socket.sock);
  8662. }
  8663. inline void ClientImpl::close_socket(Socket &socket) {
  8664. // If there are requests in flight in another thread, usually closing
  8665. // the socket will be fine and they will simply receive an error when
  8666. // using the closed socket, but it is still a bug since rarely the OS
  8667. // may reassign the socket id to be used for a new socket, and then
  8668. // suddenly they will be operating on a live socket that is different
  8669. // than the one they intended!
  8670. assert(socket_requests_in_flight_ == 0 ||
  8671. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8672. // It is also a bug if this happens while SSL is still active
  8673. #ifdef CPPHTTPLIB_SSL_ENABLED
  8674. assert(socket.ssl == nullptr);
  8675. #endif
  8676. if (socket.sock == INVALID_SOCKET) { return; }
  8677. detail::close_socket(socket.sock);
  8678. socket.sock = INVALID_SOCKET;
  8679. }
  8680. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  8681. Response &res,
  8682. bool skip_100_continue) const {
  8683. std::array<char, 2048> buf{};
  8684. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8685. if (!line_reader.getline()) { return false; }
  8686. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  8687. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  8688. #else
  8689. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  8690. #endif
  8691. std::cmatch m;
  8692. if (!std::regex_match(line_reader.ptr(), m, re)) {
  8693. return req.method == "CONNECT";
  8694. }
  8695. res.version = std::string(m[1]);
  8696. res.status = std::stoi(std::string(m[2]));
  8697. res.reason = std::string(m[3]);
  8698. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  8699. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  8700. if (!line_reader.getline()) { return false; } // CRLF
  8701. if (!line_reader.getline()) { return false; } // next response line
  8702. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  8703. res.version = std::string(m[1]);
  8704. res.status = std::stoi(std::string(m[2]));
  8705. res.reason = std::string(m[3]);
  8706. }
  8707. return true;
  8708. }
  8709. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  8710. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  8711. auto ret = send_(req, res, error);
  8712. if (error == Error::SSLPeerCouldBeClosed_) {
  8713. assert(!ret);
  8714. ret = send_(req, res, error);
  8715. }
  8716. return ret;
  8717. }
  8718. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  8719. {
  8720. std::lock_guard<std::mutex> guard(socket_mutex_);
  8721. // Set this to false immediately - if it ever gets set to true by the end
  8722. // of the request, we know another thread instructed us to close the
  8723. // socket.
  8724. socket_should_be_closed_when_request_is_done_ = false;
  8725. auto is_alive = false;
  8726. if (socket_.is_open()) {
  8727. is_alive = detail::is_socket_alive(socket_.sock);
  8728. #ifdef CPPHTTPLIB_SSL_ENABLED
  8729. if (is_alive && is_ssl()) {
  8730. if (detail::tls::tls_is_peer_closed(socket_.ssl, socket_.sock)) {
  8731. is_alive = false;
  8732. }
  8733. }
  8734. #endif
  8735. if (!is_alive) {
  8736. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  8737. // seems like the other side has already closed the connection Also,
  8738. // there cannot be any requests in flight from other threads since we
  8739. // locked request_mutex_, so safe to close everything immediately
  8740. const bool shutdown_gracefully = false;
  8741. shutdown_ssl(socket_, shutdown_gracefully);
  8742. shutdown_socket(socket_);
  8743. close_socket(socket_);
  8744. }
  8745. }
  8746. if (!is_alive) {
  8747. if (!ensure_socket_connection(socket_, error)) {
  8748. output_error_log(error, &req);
  8749. return false;
  8750. }
  8751. #ifdef CPPHTTPLIB_SSL_ENABLED
  8752. // TODO: refactoring
  8753. if (is_ssl()) {
  8754. auto &scli = static_cast<SSLClient &>(*this);
  8755. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8756. auto success = false;
  8757. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  8758. error)) {
  8759. if (!success) { output_error_log(error, &req); }
  8760. return success;
  8761. }
  8762. }
  8763. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8764. if (!scli.initialize_ssl(socket_, error)) {
  8765. output_error_log(error, &req);
  8766. return false;
  8767. }
  8768. }
  8769. }
  8770. #endif
  8771. }
  8772. // Mark the current socket as being in use so that it cannot be closed by
  8773. // anyone else while this request is ongoing, even though we will be
  8774. // releasing the mutex.
  8775. if (socket_requests_in_flight_ > 1) {
  8776. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  8777. }
  8778. socket_requests_in_flight_ += 1;
  8779. socket_requests_are_from_thread_ = std::this_thread::get_id();
  8780. }
  8781. for (const auto &header : default_headers_) {
  8782. if (req.headers.find(header.first) == req.headers.end()) {
  8783. req.headers.insert(header);
  8784. }
  8785. }
  8786. auto ret = false;
  8787. auto close_connection = !keep_alive_;
  8788. auto se = detail::scope_exit([&]() {
  8789. // Briefly lock mutex in order to mark that a request is no longer ongoing
  8790. std::lock_guard<std::mutex> guard(socket_mutex_);
  8791. socket_requests_in_flight_ -= 1;
  8792. if (socket_requests_in_flight_ <= 0) {
  8793. assert(socket_requests_in_flight_ == 0);
  8794. socket_requests_are_from_thread_ = std::thread::id();
  8795. }
  8796. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  8797. !ret) {
  8798. shutdown_ssl(socket_, true);
  8799. shutdown_socket(socket_);
  8800. close_socket(socket_);
  8801. }
  8802. });
  8803. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  8804. return handle_request(strm, req, res, close_connection, error);
  8805. });
  8806. if (!ret) {
  8807. if (error == Error::Success) {
  8808. error = Error::Unknown;
  8809. output_error_log(error, &req);
  8810. }
  8811. }
  8812. return ret;
  8813. }
  8814. inline Result ClientImpl::send(const Request &req) {
  8815. auto req2 = req;
  8816. return send_(std::move(req2));
  8817. }
  8818. inline Result ClientImpl::send_(Request &&req) {
  8819. auto res = detail::make_unique<Response>();
  8820. auto error = Error::Success;
  8821. auto ret = send(req, *res, error);
  8822. #ifdef CPPHTTPLIB_SSL_ENABLED
  8823. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  8824. last_ssl_error_, last_backend_error_};
  8825. #else
  8826. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  8827. #endif
  8828. }
  8829. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  8830. const std::string &ct) {
  8831. (void)for_stream;
  8832. for (const auto &header : default_headers_) {
  8833. if (!r.has_header(header.first)) { r.headers.insert(header); }
  8834. }
  8835. if (!r.has_header("Host")) {
  8836. if (address_family_ == AF_UNIX) {
  8837. r.headers.emplace("Host", "localhost");
  8838. } else {
  8839. r.headers.emplace(
  8840. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  8841. }
  8842. }
  8843. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  8844. if (!r.content_receiver) {
  8845. if (!r.has_header("Accept-Encoding")) {
  8846. std::string accept_encoding;
  8847. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8848. accept_encoding = "br";
  8849. #endif
  8850. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8851. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8852. accept_encoding += "gzip, deflate";
  8853. #endif
  8854. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8855. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8856. accept_encoding += "zstd";
  8857. #endif
  8858. r.set_header("Accept-Encoding", accept_encoding);
  8859. }
  8860. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  8861. if (!r.has_header("User-Agent")) {
  8862. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  8863. r.set_header("User-Agent", agent);
  8864. }
  8865. #endif
  8866. }
  8867. if (!r.body.empty()) {
  8868. if (!ct.empty() && !r.has_header("Content-Type")) {
  8869. r.headers.emplace("Content-Type", ct);
  8870. }
  8871. if (!r.has_header("Content-Length")) {
  8872. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  8873. }
  8874. }
  8875. }
  8876. inline ClientImpl::StreamHandle
  8877. ClientImpl::open_stream(const std::string &method, const std::string &path,
  8878. const Params &params, const Headers &headers,
  8879. const std::string &body,
  8880. const std::string &content_type) {
  8881. StreamHandle handle;
  8882. handle.response = detail::make_unique<Response>();
  8883. handle.error = Error::Success;
  8884. auto query_path = params.empty() ? path : append_query_params(path, params);
  8885. handle.connection_ = detail::make_unique<ClientConnection>();
  8886. {
  8887. std::lock_guard<std::mutex> guard(socket_mutex_);
  8888. auto is_alive = false;
  8889. if (socket_.is_open()) {
  8890. is_alive = detail::is_socket_alive(socket_.sock);
  8891. #ifdef CPPHTTPLIB_SSL_ENABLED
  8892. if (is_alive && is_ssl()) {
  8893. if (detail::tls::tls_is_peer_closed(socket_.ssl, socket_.sock)) {
  8894. is_alive = false;
  8895. }
  8896. }
  8897. #endif
  8898. if (!is_alive) {
  8899. shutdown_ssl(socket_, false);
  8900. shutdown_socket(socket_);
  8901. close_socket(socket_);
  8902. }
  8903. }
  8904. if (!is_alive) {
  8905. if (!ensure_socket_connection(socket_, handle.error)) {
  8906. handle.response.reset();
  8907. return handle;
  8908. }
  8909. #ifdef CPPHTTPLIB_SSL_ENABLED
  8910. if (is_ssl()) {
  8911. auto &scli = static_cast<SSLClient &>(*this);
  8912. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8913. if (!scli.initialize_ssl(socket_, handle.error)) {
  8914. handle.response.reset();
  8915. return handle;
  8916. }
  8917. }
  8918. }
  8919. #endif
  8920. }
  8921. transfer_socket_ownership_to_handle(handle);
  8922. }
  8923. #ifdef CPPHTTPLIB_SSL_ENABLED
  8924. if (is_ssl() && handle.connection_->session) {
  8925. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  8926. handle.connection_->sock, handle.connection_->session,
  8927. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8928. write_timeout_usec_);
  8929. } else {
  8930. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8931. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8932. write_timeout_sec_, write_timeout_usec_);
  8933. }
  8934. #else
  8935. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8936. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8937. write_timeout_sec_, write_timeout_usec_);
  8938. #endif
  8939. handle.stream_ = handle.socket_stream_.get();
  8940. Request req;
  8941. req.method = method;
  8942. req.path = query_path;
  8943. req.headers = headers;
  8944. req.body = body;
  8945. prepare_default_headers(req, true, content_type);
  8946. auto &strm = *handle.stream_;
  8947. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  8948. handle.error = Error::Write;
  8949. handle.response.reset();
  8950. return handle;
  8951. }
  8952. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  8953. handle.error)) {
  8954. handle.response.reset();
  8955. return handle;
  8956. }
  8957. if (!body.empty()) {
  8958. if (strm.write(body.data(), body.size()) < 0) {
  8959. handle.error = Error::Write;
  8960. handle.response.reset();
  8961. return handle;
  8962. }
  8963. }
  8964. if (!read_response_line(strm, req, *handle.response) ||
  8965. !detail::read_headers(strm, handle.response->headers)) {
  8966. handle.error = Error::Read;
  8967. handle.response.reset();
  8968. return handle;
  8969. }
  8970. handle.body_reader_.stream = handle.stream_;
  8971. auto content_length_str = handle.response->get_header_value("Content-Length");
  8972. if (!content_length_str.empty()) {
  8973. handle.body_reader_.content_length =
  8974. static_cast<size_t>(std::stoull(content_length_str));
  8975. }
  8976. auto transfer_encoding =
  8977. handle.response->get_header_value("Transfer-Encoding");
  8978. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  8979. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  8980. if (!content_encoding.empty()) {
  8981. handle.decompressor_ = detail::create_decompressor(content_encoding);
  8982. }
  8983. return handle;
  8984. }
  8985. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  8986. if (!is_valid() || !response) { return -1; }
  8987. if (decompressor_) { return read_with_decompression(buf, len); }
  8988. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  8989. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  8990. trailers_parsed_ = true;
  8991. if (body_reader_.chunked_decoder) {
  8992. if (!body_reader_.chunked_decoder->parse_trailers_into(
  8993. response->trailers, response->headers)) {
  8994. return n;
  8995. }
  8996. } else {
  8997. detail::ChunkedDecoder dec(*stream_);
  8998. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  8999. return n;
  9000. }
  9001. }
  9002. }
  9003. return n;
  9004. }
  9005. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  9006. size_t len) {
  9007. if (decompress_offset_ < decompress_buffer_.size()) {
  9008. auto available = decompress_buffer_.size() - decompress_offset_;
  9009. auto to_copy = (std::min)(len, available);
  9010. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  9011. decompress_offset_ += to_copy;
  9012. return static_cast<ssize_t>(to_copy);
  9013. }
  9014. decompress_buffer_.clear();
  9015. decompress_offset_ = 0;
  9016. constexpr size_t kDecompressionBufferSize = 8192;
  9017. char compressed_buf[kDecompressionBufferSize];
  9018. while (true) {
  9019. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  9020. sizeof(compressed_buf));
  9021. if (n <= 0) { return n; }
  9022. bool decompress_ok =
  9023. decompressor_->decompress(compressed_buf, static_cast<size_t>(n),
  9024. [this](const char *data, size_t data_len) {
  9025. decompress_buffer_.append(data, data_len);
  9026. return true;
  9027. });
  9028. if (!decompress_ok) {
  9029. body_reader_.last_error = Error::Read;
  9030. return -1;
  9031. }
  9032. if (!decompress_buffer_.empty()) { break; }
  9033. }
  9034. auto to_copy = (std::min)(len, decompress_buffer_.size());
  9035. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  9036. decompress_offset_ = to_copy;
  9037. return static_cast<ssize_t>(to_copy);
  9038. }
  9039. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  9040. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  9041. return;
  9042. }
  9043. trailers_parsed_ = true;
  9044. const auto bufsiz = 128;
  9045. char line_buf[bufsiz];
  9046. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  9047. if (!line_reader.getline()) { return; }
  9048. if (!detail::parse_trailers(line_reader, response->trailers,
  9049. response->headers)) {
  9050. return;
  9051. }
  9052. }
  9053. // Inline method implementations for `ChunkedDecoder`.
  9054. namespace detail {
  9055. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  9056. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  9057. size_t &out_chunk_offset,
  9058. size_t &out_chunk_total) {
  9059. if (finished) { return 0; }
  9060. if (chunk_remaining == 0) {
  9061. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9062. if (!lr.getline()) { return -1; }
  9063. char *endptr = nullptr;
  9064. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  9065. if (endptr == lr.ptr()) { return -1; }
  9066. if (chunk_len == ULONG_MAX) { return -1; }
  9067. if (chunk_len == 0) {
  9068. chunk_remaining = 0;
  9069. finished = true;
  9070. out_chunk_offset = 0;
  9071. out_chunk_total = 0;
  9072. return 0;
  9073. }
  9074. chunk_remaining = static_cast<size_t>(chunk_len);
  9075. last_chunk_total = chunk_remaining;
  9076. last_chunk_offset = 0;
  9077. }
  9078. auto to_read = (std::min)(chunk_remaining, len);
  9079. auto n = strm.read(buf, to_read);
  9080. if (n <= 0) { return -1; }
  9081. auto offset_before = last_chunk_offset;
  9082. last_chunk_offset += static_cast<size_t>(n);
  9083. chunk_remaining -= static_cast<size_t>(n);
  9084. out_chunk_offset = offset_before;
  9085. out_chunk_total = last_chunk_total;
  9086. if (chunk_remaining == 0) {
  9087. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9088. if (!lr.getline()) { return -1; }
  9089. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  9090. }
  9091. return n;
  9092. }
  9093. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  9094. const Headers &src_headers) {
  9095. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9096. if (!lr.getline()) { return false; }
  9097. return parse_trailers(lr, dest, src_headers);
  9098. }
  9099. } // namespace detail
  9100. inline void
  9101. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  9102. handle.connection_->sock = socket_.sock;
  9103. #ifdef CPPHTTPLIB_SSL_ENABLED
  9104. handle.connection_->session = socket_.ssl;
  9105. socket_.ssl = nullptr;
  9106. #endif
  9107. socket_.sock = INVALID_SOCKET;
  9108. }
  9109. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  9110. Response &res, bool close_connection,
  9111. Error &error) {
  9112. if (req.path.empty()) {
  9113. error = Error::Connection;
  9114. output_error_log(error, &req);
  9115. return false;
  9116. }
  9117. auto req_save = req;
  9118. bool ret;
  9119. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  9120. auto req2 = req;
  9121. req2.path = "http://" +
  9122. detail::make_host_and_port_string(host_, port_, false) +
  9123. req.path;
  9124. ret = process_request(strm, req2, res, close_connection, error);
  9125. req = std::move(req2);
  9126. req.path = req_save.path;
  9127. } else {
  9128. ret = process_request(strm, req, res, close_connection, error);
  9129. }
  9130. if (!ret) { return false; }
  9131. if (res.get_header_value("Connection") == "close" ||
  9132. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  9133. // TODO this requires a not-entirely-obvious chain of calls to be correct
  9134. // for this to be safe.
  9135. // This is safe to call because handle_request is only called by send_
  9136. // which locks the request mutex during the process. It would be a bug
  9137. // to call it from a different thread since it's a thread-safety issue
  9138. // to do these things to the socket if another thread is using the socket.
  9139. std::lock_guard<std::mutex> guard(socket_mutex_);
  9140. shutdown_ssl(socket_, true);
  9141. shutdown_socket(socket_);
  9142. close_socket(socket_);
  9143. }
  9144. if (300 < res.status && res.status < 400 && follow_location_) {
  9145. req = std::move(req_save);
  9146. ret = redirect(req, res, error);
  9147. }
  9148. #ifdef CPPHTTPLIB_SSL_ENABLED
  9149. if ((res.status == StatusCode::Unauthorized_401 ||
  9150. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  9151. req.authorization_count_ < 5) {
  9152. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  9153. const auto &username =
  9154. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  9155. const auto &password =
  9156. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  9157. if (!username.empty() && !password.empty()) {
  9158. std::map<std::string, std::string> auth;
  9159. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  9160. Request new_req = req;
  9161. new_req.authorization_count_ += 1;
  9162. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  9163. : "Authorization");
  9164. new_req.headers.insert(detail::make_digest_authentication_header(
  9165. req, auth, new_req.authorization_count_, detail::random_string(10),
  9166. username, password, is_proxy));
  9167. Response new_res;
  9168. ret = send(new_req, new_res, error);
  9169. if (ret) { res = std::move(new_res); }
  9170. }
  9171. }
  9172. }
  9173. #endif
  9174. return ret;
  9175. }
  9176. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  9177. if (req.redirect_count_ == 0) {
  9178. error = Error::ExceedRedirectCount;
  9179. output_error_log(error, &req);
  9180. return false;
  9181. }
  9182. auto location = res.get_header_value("location");
  9183. if (location.empty()) { return false; }
  9184. thread_local const std::regex re(
  9185. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  9186. std::smatch m;
  9187. if (!std::regex_match(location, m, re)) { return false; }
  9188. auto scheme = is_ssl() ? "https" : "http";
  9189. auto next_scheme = m[1].str();
  9190. auto next_host = m[2].str();
  9191. if (next_host.empty()) { next_host = m[3].str(); }
  9192. auto port_str = m[4].str();
  9193. auto next_path = m[5].str();
  9194. auto next_query = m[6].str();
  9195. auto next_port = port_;
  9196. if (!port_str.empty()) {
  9197. next_port = std::stoi(port_str);
  9198. } else if (!next_scheme.empty()) {
  9199. next_port = next_scheme == "https" ? 443 : 80;
  9200. }
  9201. if (next_scheme.empty()) { next_scheme = scheme; }
  9202. if (next_host.empty()) { next_host = host_; }
  9203. if (next_path.empty()) { next_path = "/"; }
  9204. auto path = decode_query_component(next_path, true) + next_query;
  9205. // Same host redirect - use current client
  9206. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  9207. return detail::redirect(*this, req, res, path, location, error);
  9208. }
  9209. // Cross-host/scheme redirect - create new client with robust setup
  9210. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  9211. path, location, error);
  9212. }
  9213. // New method for robust redirect client creation
  9214. inline bool ClientImpl::create_redirect_client(
  9215. const std::string &scheme, const std::string &host, int port, Request &req,
  9216. Response &res, const std::string &path, const std::string &location,
  9217. Error &error) {
  9218. // Determine if we need SSL
  9219. auto need_ssl = (scheme == "https");
  9220. // Clean up request headers that are host/client specific
  9221. // Remove headers that should not be carried over to new host
  9222. auto headers_to_remove =
  9223. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  9224. for (const auto &header_name : headers_to_remove) {
  9225. auto it = req.headers.find(header_name);
  9226. while (it != req.headers.end()) {
  9227. it = req.headers.erase(it);
  9228. it = req.headers.find(header_name);
  9229. }
  9230. }
  9231. // Create appropriate client type and handle redirect
  9232. if (need_ssl) {
  9233. #ifdef CPPHTTPLIB_SSL_ENABLED
  9234. // Create SSL client for HTTPS redirect
  9235. SSLClient redirect_client(host, port);
  9236. // Setup basic client configuration first
  9237. setup_redirect_client(redirect_client);
  9238. // SSL-specific configuration for proxy environments
  9239. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9240. // Critical: Disable SSL verification for proxy environments
  9241. redirect_client.enable_server_certificate_verification(false);
  9242. redirect_client.enable_server_hostname_verification(false);
  9243. } else {
  9244. // For direct SSL connections, copy SSL verification settings
  9245. redirect_client.enable_server_certificate_verification(
  9246. server_certificate_verification_);
  9247. redirect_client.enable_server_hostname_verification(
  9248. server_hostname_verification_);
  9249. }
  9250. // Transfer CA certificate to redirect client
  9251. if (!ca_cert_pem_.empty()) {
  9252. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  9253. ca_cert_pem_.size());
  9254. }
  9255. if (!ca_cert_file_path_.empty()) {
  9256. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  9257. }
  9258. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9259. // OpenSSL-specific: Handle CA certificate store
  9260. if (ca_cert_store_ && X509_STORE_up_ref(ca_cert_store_)) {
  9261. redirect_client.set_ca_cert_store(ca_cert_store_);
  9262. }
  9263. #endif
  9264. // Client certificates are set through constructor for SSLClient
  9265. // NOTE: SSLClient constructor already takes client_cert_path and
  9266. // client_key_path so we need to create it properly if client certs are
  9267. // needed
  9268. // Execute the redirect
  9269. return detail::redirect(redirect_client, req, res, path, location, error);
  9270. #else
  9271. // SSL not supported - set appropriate error
  9272. error = Error::SSLConnection;
  9273. output_error_log(error, &req);
  9274. return false;
  9275. #endif
  9276. } else {
  9277. // HTTP redirect
  9278. ClientImpl redirect_client(host, port);
  9279. // Setup client with robust configuration
  9280. setup_redirect_client(redirect_client);
  9281. // Execute the redirect
  9282. return detail::redirect(redirect_client, req, res, path, location, error);
  9283. }
  9284. }
  9285. // New method for robust client setup (based on basic_manual_redirect.cpp
  9286. // logic)
  9287. template <typename ClientType>
  9288. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  9289. // Copy basic settings first
  9290. client.set_connection_timeout(connection_timeout_sec_);
  9291. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  9292. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  9293. client.set_keep_alive(keep_alive_);
  9294. client.set_follow_location(
  9295. true); // Enable redirects to handle multi-step redirects
  9296. client.set_path_encode(path_encode_);
  9297. client.set_compress(compress_);
  9298. client.set_decompress(decompress_);
  9299. // Copy authentication settings BEFORE proxy setup
  9300. if (!basic_auth_username_.empty()) {
  9301. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  9302. }
  9303. if (!bearer_token_auth_token_.empty()) {
  9304. client.set_bearer_token_auth(bearer_token_auth_token_);
  9305. }
  9306. #ifdef CPPHTTPLIB_SSL_ENABLED
  9307. if (!digest_auth_username_.empty()) {
  9308. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  9309. }
  9310. #endif
  9311. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  9312. // before proxy auth)
  9313. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9314. // First set proxy host and port
  9315. client.set_proxy(proxy_host_, proxy_port_);
  9316. // Then set proxy authentication (order matters!)
  9317. if (!proxy_basic_auth_username_.empty()) {
  9318. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  9319. proxy_basic_auth_password_);
  9320. }
  9321. if (!proxy_bearer_token_auth_token_.empty()) {
  9322. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  9323. }
  9324. #ifdef CPPHTTPLIB_SSL_ENABLED
  9325. if (!proxy_digest_auth_username_.empty()) {
  9326. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  9327. proxy_digest_auth_password_);
  9328. }
  9329. #endif
  9330. }
  9331. // Copy network and socket settings
  9332. client.set_address_family(address_family_);
  9333. client.set_tcp_nodelay(tcp_nodelay_);
  9334. client.set_ipv6_v6only(ipv6_v6only_);
  9335. if (socket_options_) { client.set_socket_options(socket_options_); }
  9336. if (!interface_.empty()) { client.set_interface(interface_); }
  9337. // Copy logging and headers
  9338. if (logger_) { client.set_logger(logger_); }
  9339. if (error_logger_) { client.set_error_logger(error_logger_); }
  9340. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  9341. // Each new client should generate its own headers based on its target host
  9342. }
  9343. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  9344. const Request &req,
  9345. Error &error) const {
  9346. auto is_shutting_down = []() { return false; };
  9347. if (req.is_chunked_content_provider_) {
  9348. // TODO: Brotli support
  9349. std::unique_ptr<detail::compressor> compressor;
  9350. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9351. if (compress_) {
  9352. compressor = detail::make_unique<detail::gzip_compressor>();
  9353. } else
  9354. #endif
  9355. {
  9356. compressor = detail::make_unique<detail::nocompressor>();
  9357. }
  9358. return detail::write_content_chunked(strm, req.content_provider_,
  9359. is_shutting_down, *compressor, error);
  9360. } else {
  9361. return detail::write_content_with_progress(
  9362. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  9363. req.upload_progress, error);
  9364. }
  9365. }
  9366. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  9367. bool close_connection, Error &error,
  9368. bool skip_body) {
  9369. // Prepare additional headers
  9370. if (close_connection) {
  9371. if (!req.has_header("Connection")) {
  9372. req.set_header("Connection", "close");
  9373. }
  9374. }
  9375. std::string ct_for_defaults;
  9376. if (!req.has_header("Content-Type") && !req.body.empty()) {
  9377. ct_for_defaults = "text/plain";
  9378. }
  9379. prepare_default_headers(req, false, ct_for_defaults);
  9380. if (req.body.empty()) {
  9381. if (req.content_provider_) {
  9382. if (!req.is_chunked_content_provider_) {
  9383. if (!req.has_header("Content-Length")) {
  9384. auto length = std::to_string(req.content_length_);
  9385. req.set_header("Content-Length", length);
  9386. }
  9387. }
  9388. } else {
  9389. if (req.method == "POST" || req.method == "PUT" ||
  9390. req.method == "PATCH") {
  9391. req.set_header("Content-Length", "0");
  9392. }
  9393. }
  9394. }
  9395. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  9396. if (!req.has_header("Authorization")) {
  9397. req.headers.insert(make_basic_authentication_header(
  9398. basic_auth_username_, basic_auth_password_, false));
  9399. }
  9400. }
  9401. if (!proxy_basic_auth_username_.empty() &&
  9402. !proxy_basic_auth_password_.empty()) {
  9403. if (!req.has_header("Proxy-Authorization")) {
  9404. req.headers.insert(make_basic_authentication_header(
  9405. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  9406. }
  9407. }
  9408. if (!bearer_token_auth_token_.empty()) {
  9409. if (!req.has_header("Authorization")) {
  9410. req.headers.insert(make_bearer_token_authentication_header(
  9411. bearer_token_auth_token_, false));
  9412. }
  9413. }
  9414. if (!proxy_bearer_token_auth_token_.empty()) {
  9415. if (!req.has_header("Proxy-Authorization")) {
  9416. req.headers.insert(make_bearer_token_authentication_header(
  9417. proxy_bearer_token_auth_token_, true));
  9418. }
  9419. }
  9420. // Request line and headers
  9421. {
  9422. detail::BufferStream bstrm;
  9423. // Extract path and query from req.path
  9424. std::string path_part, query_part;
  9425. auto query_pos = req.path.find('?');
  9426. if (query_pos != std::string::npos) {
  9427. path_part = req.path.substr(0, query_pos);
  9428. query_part = req.path.substr(query_pos + 1);
  9429. } else {
  9430. path_part = req.path;
  9431. query_part = "";
  9432. }
  9433. // Encode path part. If the original `req.path` already contained a
  9434. // query component, preserve its raw query string (including parameter
  9435. // order) instead of reparsing and reassembling it which may reorder
  9436. // parameters due to container ordering (e.g. `Params` uses
  9437. // `std::multimap`). When there is no query in `req.path`, fall back to
  9438. // building a query from `req.params` so existing callers that pass
  9439. // `Params` continue to work.
  9440. auto path_with_query =
  9441. path_encode_ ? detail::encode_path(path_part) : path_part;
  9442. if (!query_part.empty()) {
  9443. // Normalize the query string (decode then re-encode) while preserving
  9444. // the original parameter order.
  9445. auto normalized = detail::normalize_query_string(query_part);
  9446. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  9447. // Still populate req.params for handlers/users who read them.
  9448. detail::parse_query_text(query_part, req.params);
  9449. } else {
  9450. // No query in path; parse any query_part (empty) and append params
  9451. // from `req.params` when present (preserves prior behavior for
  9452. // callers who provide Params separately).
  9453. detail::parse_query_text(query_part, req.params);
  9454. if (!req.params.empty()) {
  9455. path_with_query = append_query_params(path_with_query, req.params);
  9456. }
  9457. }
  9458. // Write request line and headers
  9459. detail::write_request_line(bstrm, req.method, path_with_query);
  9460. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  9461. error)) {
  9462. output_error_log(error, &req);
  9463. return false;
  9464. }
  9465. // Flush buffer
  9466. auto &data = bstrm.get_buffer();
  9467. if (!detail::write_data(strm, data.data(), data.size())) {
  9468. error = Error::Write;
  9469. output_error_log(error, &req);
  9470. return false;
  9471. }
  9472. }
  9473. // After sending request line and headers, wait briefly for an early server
  9474. // response (e.g. 4xx) and avoid sending a potentially large request body
  9475. // unnecessarily. This workaround is only enabled on Windows because Unix
  9476. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  9477. // buffering can accept large writes even when the peer already responded.
  9478. // Check the stream first (which covers SSL via `is_readable()`), then
  9479. // fall back to select on the socket. Only perform the wait for very large
  9480. // request bodies to avoid interfering with normal small requests and
  9481. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  9482. // response. Skip this check when using Expect: 100-continue, as the protocol
  9483. // handles early responses properly.
  9484. #if defined(_WIN32)
  9485. if (!skip_body &&
  9486. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  9487. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  9488. auto start = std::chrono::high_resolution_clock::now();
  9489. for (;;) {
  9490. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  9491. // from SSL internals. If the underlying socket is readable, assume an
  9492. // early response may be present.
  9493. auto sock = strm.socket();
  9494. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  9495. return false;
  9496. }
  9497. // Fallback to stream-level check for non-socket streams or when the
  9498. // socket isn't reporting readable. Avoid using `is_readable()` for
  9499. // SSL, since `SSL_pending()` may report buffered records that do not
  9500. // indicate a complete application-level response yet.
  9501. if (!is_ssl() && strm.is_readable()) { return false; }
  9502. auto now = std::chrono::high_resolution_clock::now();
  9503. auto elapsed =
  9504. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  9505. .count();
  9506. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  9507. break;
  9508. }
  9509. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  9510. }
  9511. }
  9512. #endif
  9513. // Body
  9514. if (skip_body) { return true; }
  9515. return write_request_body(strm, req, error);
  9516. }
  9517. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  9518. Error &error) {
  9519. if (req.body.empty()) {
  9520. return write_content_with_provider(strm, req, error);
  9521. }
  9522. if (req.upload_progress) {
  9523. auto body_size = req.body.size();
  9524. size_t written = 0;
  9525. auto data = req.body.data();
  9526. while (written < body_size) {
  9527. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  9528. if (!detail::write_data(strm, data + written, to_write)) {
  9529. error = Error::Write;
  9530. output_error_log(error, &req);
  9531. return false;
  9532. }
  9533. written += to_write;
  9534. if (!req.upload_progress(written, body_size)) {
  9535. error = Error::Canceled;
  9536. output_error_log(error, &req);
  9537. return false;
  9538. }
  9539. }
  9540. } else {
  9541. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  9542. error = Error::Write;
  9543. output_error_log(error, &req);
  9544. return false;
  9545. }
  9546. }
  9547. return true;
  9548. }
  9549. inline std::unique_ptr<Response>
  9550. ClientImpl::send_with_content_provider_and_receiver(
  9551. Request &req, const char *body, size_t content_length,
  9552. ContentProvider content_provider,
  9553. ContentProviderWithoutLength content_provider_without_length,
  9554. const std::string &content_type, ContentReceiver content_receiver,
  9555. Error &error) {
  9556. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9557. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9558. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  9559. #endif
  9560. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9561. if (compress_ && !content_provider_without_length) {
  9562. // TODO: Brotli support
  9563. detail::gzip_compressor compressor;
  9564. if (content_provider) {
  9565. auto ok = true;
  9566. size_t offset = 0;
  9567. DataSink data_sink;
  9568. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  9569. if (ok) {
  9570. auto last = offset + data_len == content_length;
  9571. auto ret = compressor.compress(
  9572. data, data_len, last,
  9573. [&](const char *compressed_data, size_t compressed_data_len) {
  9574. req.body.append(compressed_data, compressed_data_len);
  9575. return true;
  9576. });
  9577. if (ret) {
  9578. offset += data_len;
  9579. } else {
  9580. ok = false;
  9581. }
  9582. }
  9583. return ok;
  9584. };
  9585. while (ok && offset < content_length) {
  9586. if (!content_provider(offset, content_length - offset, data_sink)) {
  9587. error = Error::Canceled;
  9588. output_error_log(error, &req);
  9589. return nullptr;
  9590. }
  9591. }
  9592. } else {
  9593. if (!compressor.compress(body, content_length, true,
  9594. [&](const char *data, size_t data_len) {
  9595. req.body.append(data, data_len);
  9596. return true;
  9597. })) {
  9598. error = Error::Compression;
  9599. output_error_log(error, &req);
  9600. return nullptr;
  9601. }
  9602. }
  9603. } else
  9604. #endif
  9605. {
  9606. if (content_provider) {
  9607. req.content_length_ = content_length;
  9608. req.content_provider_ = std::move(content_provider);
  9609. req.is_chunked_content_provider_ = false;
  9610. } else if (content_provider_without_length) {
  9611. req.content_length_ = 0;
  9612. req.content_provider_ = detail::ContentProviderAdapter(
  9613. std::move(content_provider_without_length));
  9614. req.is_chunked_content_provider_ = true;
  9615. req.set_header("Transfer-Encoding", "chunked");
  9616. } else {
  9617. req.body.assign(body, content_length);
  9618. }
  9619. }
  9620. if (content_receiver) {
  9621. req.content_receiver =
  9622. [content_receiver](const char *data, size_t data_length,
  9623. size_t /*offset*/, size_t /*total_length*/) {
  9624. return content_receiver(data, data_length);
  9625. };
  9626. }
  9627. auto res = detail::make_unique<Response>();
  9628. return send(req, *res, error) ? std::move(res) : nullptr;
  9629. }
  9630. inline Result ClientImpl::send_with_content_provider_and_receiver(
  9631. const std::string &method, const std::string &path, const Headers &headers,
  9632. const char *body, size_t content_length, ContentProvider content_provider,
  9633. ContentProviderWithoutLength content_provider_without_length,
  9634. const std::string &content_type, ContentReceiver content_receiver,
  9635. UploadProgress progress) {
  9636. Request req;
  9637. req.method = method;
  9638. req.headers = headers;
  9639. req.path = path;
  9640. req.upload_progress = std::move(progress);
  9641. if (max_timeout_msec_ > 0) {
  9642. req.start_time_ = std::chrono::steady_clock::now();
  9643. }
  9644. auto error = Error::Success;
  9645. auto res = send_with_content_provider_and_receiver(
  9646. req, body, content_length, std::move(content_provider),
  9647. std::move(content_provider_without_length), content_type,
  9648. std::move(content_receiver), error);
  9649. #ifdef CPPHTTPLIB_SSL_ENABLED
  9650. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  9651. last_backend_error_};
  9652. #else
  9653. return Result{std::move(res), error, std::move(req.headers)};
  9654. #endif
  9655. }
  9656. inline void ClientImpl::output_log(const Request &req,
  9657. const Response &res) const {
  9658. if (logger_) {
  9659. std::lock_guard<std::mutex> guard(logger_mutex_);
  9660. logger_(req, res);
  9661. }
  9662. }
  9663. inline void ClientImpl::output_error_log(const Error &err,
  9664. const Request *req) const {
  9665. if (error_logger_) {
  9666. std::lock_guard<std::mutex> guard(logger_mutex_);
  9667. error_logger_(err, req);
  9668. }
  9669. }
  9670. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  9671. Response &res, bool close_connection,
  9672. Error &error) {
  9673. // Auto-add Expect: 100-continue for large bodies
  9674. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  9675. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  9676. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  9677. req.set_header("Expect", "100-continue");
  9678. }
  9679. }
  9680. // Check for Expect: 100-continue
  9681. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  9682. // Send request (skip body if using Expect: 100-continue)
  9683. auto write_request_success =
  9684. write_request(strm, req, close_connection, error, expect_100_continue);
  9685. #ifdef CPPHTTPLIB_SSL_ENABLED
  9686. if (is_ssl()) {
  9687. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  9688. if (!is_proxy_enabled) {
  9689. if (detail::tls::tls_is_peer_closed(socket_.ssl, socket_.sock)) {
  9690. error = Error::SSLPeerCouldBeClosed_;
  9691. output_error_log(error, &req);
  9692. return false;
  9693. }
  9694. }
  9695. }
  9696. #endif
  9697. // Handle Expect: 100-continue with timeout
  9698. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  9699. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  9700. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  9701. auto ret = detail::select_read(strm.socket(), sec, usec);
  9702. if (ret <= 0) {
  9703. // Timeout or error: send body anyway (server didn't respond in time)
  9704. if (!write_request_body(strm, req, error)) { return false; }
  9705. expect_100_continue = false; // Switch to normal response handling
  9706. }
  9707. }
  9708. // Receive response and headers
  9709. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  9710. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  9711. !detail::read_headers(strm, res.headers)) {
  9712. if (write_request_success) { error = Error::Read; }
  9713. output_error_log(error, &req);
  9714. return false;
  9715. }
  9716. if (!write_request_success) { return false; }
  9717. // Handle Expect: 100-continue response
  9718. if (expect_100_continue) {
  9719. if (res.status == StatusCode::Continue_100) {
  9720. // Server accepted, send the body
  9721. if (!write_request_body(strm, req, error)) { return false; }
  9722. // Read the actual response
  9723. res.headers.clear();
  9724. res.body.clear();
  9725. if (!read_response_line(strm, req, res) ||
  9726. !detail::read_headers(strm, res.headers)) {
  9727. error = Error::Read;
  9728. output_error_log(error, &req);
  9729. return false;
  9730. }
  9731. }
  9732. // If not 100 Continue, server returned an error; proceed with that response
  9733. }
  9734. // Body
  9735. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  9736. req.method != "CONNECT") {
  9737. auto redirect = 300 < res.status && res.status < 400 &&
  9738. res.status != StatusCode::NotModified_304 &&
  9739. follow_location_;
  9740. if (req.response_handler && !redirect) {
  9741. if (!req.response_handler(res)) {
  9742. error = Error::Canceled;
  9743. output_error_log(error, &req);
  9744. return false;
  9745. }
  9746. }
  9747. auto out =
  9748. req.content_receiver
  9749. ? static_cast<ContentReceiverWithProgress>(
  9750. [&](const char *buf, size_t n, size_t off, size_t len) {
  9751. if (redirect) { return true; }
  9752. auto ret = req.content_receiver(buf, n, off, len);
  9753. if (!ret) {
  9754. error = Error::Canceled;
  9755. output_error_log(error, &req);
  9756. }
  9757. return ret;
  9758. })
  9759. : static_cast<ContentReceiverWithProgress>(
  9760. [&](const char *buf, size_t n, size_t /*off*/,
  9761. size_t /*len*/) {
  9762. assert(res.body.size() + n <= res.body.max_size());
  9763. res.body.append(buf, n);
  9764. return true;
  9765. });
  9766. auto progress = [&](size_t current, size_t total) {
  9767. if (!req.download_progress || redirect) { return true; }
  9768. auto ret = req.download_progress(current, total);
  9769. if (!ret) {
  9770. error = Error::Canceled;
  9771. output_error_log(error, &req);
  9772. }
  9773. return ret;
  9774. };
  9775. if (res.has_header("Content-Length")) {
  9776. if (!req.content_receiver) {
  9777. auto len = res.get_header_value_u64("Content-Length");
  9778. if (len > res.body.max_size()) {
  9779. error = Error::Read;
  9780. output_error_log(error, &req);
  9781. return false;
  9782. }
  9783. res.body.reserve(static_cast<size_t>(len));
  9784. }
  9785. }
  9786. if (res.status != StatusCode::NotModified_304) {
  9787. int dummy_status;
  9788. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  9789. dummy_status, std::move(progress),
  9790. std::move(out), decompress_)) {
  9791. if (error != Error::Canceled) { error = Error::Read; }
  9792. output_error_log(error, &req);
  9793. return false;
  9794. }
  9795. }
  9796. }
  9797. // Log
  9798. output_log(req, res);
  9799. return true;
  9800. }
  9801. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  9802. const std::string &boundary, const UploadFormDataItems &items,
  9803. const FormDataProviderItems &provider_items) const {
  9804. size_t cur_item = 0;
  9805. size_t cur_start = 0;
  9806. // cur_item and cur_start are copied to within the std::function and
  9807. // maintain state between successive calls
  9808. return [&, cur_item, cur_start](size_t offset,
  9809. DataSink &sink) mutable -> bool {
  9810. if (!offset && !items.empty()) {
  9811. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  9812. return true;
  9813. } else if (cur_item < provider_items.size()) {
  9814. if (!cur_start) {
  9815. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  9816. provider_items[cur_item], boundary);
  9817. offset += begin.size();
  9818. cur_start = offset;
  9819. sink.os << begin;
  9820. }
  9821. DataSink cur_sink;
  9822. auto has_data = true;
  9823. cur_sink.write = sink.write;
  9824. cur_sink.done = [&]() { has_data = false; };
  9825. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  9826. return false;
  9827. }
  9828. if (!has_data) {
  9829. sink.os << detail::serialize_multipart_formdata_item_end();
  9830. cur_item++;
  9831. cur_start = 0;
  9832. }
  9833. return true;
  9834. } else {
  9835. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  9836. sink.done();
  9837. return true;
  9838. }
  9839. };
  9840. }
  9841. inline bool ClientImpl::process_socket(
  9842. const Socket &socket,
  9843. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9844. std::function<bool(Stream &strm)> callback) {
  9845. return detail::process_client_socket(
  9846. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9847. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  9848. }
  9849. inline bool ClientImpl::is_ssl() const { return false; }
  9850. inline Result ClientImpl::Get(const std::string &path,
  9851. DownloadProgress progress) {
  9852. return Get(path, Headers(), std::move(progress));
  9853. }
  9854. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9855. const Headers &headers,
  9856. DownloadProgress progress) {
  9857. if (params.empty()) { return Get(path, headers); }
  9858. std::string path_with_query = append_query_params(path, params);
  9859. return Get(path_with_query, headers, std::move(progress));
  9860. }
  9861. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9862. DownloadProgress progress) {
  9863. Request req;
  9864. req.method = "GET";
  9865. req.path = path;
  9866. req.headers = headers;
  9867. req.download_progress = std::move(progress);
  9868. if (max_timeout_msec_ > 0) {
  9869. req.start_time_ = std::chrono::steady_clock::now();
  9870. }
  9871. return send_(std::move(req));
  9872. }
  9873. inline Result ClientImpl::Get(const std::string &path,
  9874. ContentReceiver content_receiver,
  9875. DownloadProgress progress) {
  9876. return Get(path, Headers(), nullptr, std::move(content_receiver),
  9877. std::move(progress));
  9878. }
  9879. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9880. ContentReceiver content_receiver,
  9881. DownloadProgress progress) {
  9882. return Get(path, headers, nullptr, std::move(content_receiver),
  9883. std::move(progress));
  9884. }
  9885. inline Result ClientImpl::Get(const std::string &path,
  9886. ResponseHandler response_handler,
  9887. ContentReceiver content_receiver,
  9888. DownloadProgress progress) {
  9889. return Get(path, Headers(), std::move(response_handler),
  9890. std::move(content_receiver), std::move(progress));
  9891. }
  9892. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9893. ResponseHandler response_handler,
  9894. ContentReceiver content_receiver,
  9895. DownloadProgress progress) {
  9896. Request req;
  9897. req.method = "GET";
  9898. req.path = path;
  9899. req.headers = headers;
  9900. req.response_handler = std::move(response_handler);
  9901. req.content_receiver =
  9902. [content_receiver](const char *data, size_t data_length,
  9903. size_t /*offset*/, size_t /*total_length*/) {
  9904. return content_receiver(data, data_length);
  9905. };
  9906. req.download_progress = std::move(progress);
  9907. if (max_timeout_msec_ > 0) {
  9908. req.start_time_ = std::chrono::steady_clock::now();
  9909. }
  9910. return send_(std::move(req));
  9911. }
  9912. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9913. const Headers &headers,
  9914. ContentReceiver content_receiver,
  9915. DownloadProgress progress) {
  9916. return Get(path, params, headers, nullptr, std::move(content_receiver),
  9917. std::move(progress));
  9918. }
  9919. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9920. const Headers &headers,
  9921. ResponseHandler response_handler,
  9922. ContentReceiver content_receiver,
  9923. DownloadProgress progress) {
  9924. if (params.empty()) {
  9925. return Get(path, headers, std::move(response_handler),
  9926. std::move(content_receiver), std::move(progress));
  9927. }
  9928. std::string path_with_query = append_query_params(path, params);
  9929. return Get(path_with_query, headers, std::move(response_handler),
  9930. std::move(content_receiver), std::move(progress));
  9931. }
  9932. inline Result ClientImpl::Head(const std::string &path) {
  9933. return Head(path, Headers());
  9934. }
  9935. inline Result ClientImpl::Head(const std::string &path,
  9936. const Headers &headers) {
  9937. Request req;
  9938. req.method = "HEAD";
  9939. req.headers = headers;
  9940. req.path = path;
  9941. if (max_timeout_msec_ > 0) {
  9942. req.start_time_ = std::chrono::steady_clock::now();
  9943. }
  9944. return send_(std::move(req));
  9945. }
  9946. inline Result ClientImpl::Post(const std::string &path) {
  9947. return Post(path, std::string(), std::string());
  9948. }
  9949. inline Result ClientImpl::Post(const std::string &path,
  9950. const Headers &headers) {
  9951. return Post(path, headers, nullptr, 0, std::string());
  9952. }
  9953. inline Result ClientImpl::Post(const std::string &path, const char *body,
  9954. size_t content_length,
  9955. const std::string &content_type,
  9956. UploadProgress progress) {
  9957. return Post(path, Headers(), body, content_length, content_type, progress);
  9958. }
  9959. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  9960. const std::string &content_type,
  9961. UploadProgress progress) {
  9962. return Post(path, Headers(), body, content_type, progress);
  9963. }
  9964. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  9965. return Post(path, Headers(), params);
  9966. }
  9967. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9968. ContentProvider content_provider,
  9969. const std::string &content_type,
  9970. UploadProgress progress) {
  9971. return Post(path, Headers(), content_length, std::move(content_provider),
  9972. content_type, progress);
  9973. }
  9974. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9975. ContentProvider content_provider,
  9976. const std::string &content_type,
  9977. ContentReceiver content_receiver,
  9978. UploadProgress progress) {
  9979. return Post(path, Headers(), content_length, std::move(content_provider),
  9980. content_type, std::move(content_receiver), progress);
  9981. }
  9982. inline Result ClientImpl::Post(const std::string &path,
  9983. ContentProviderWithoutLength content_provider,
  9984. const std::string &content_type,
  9985. UploadProgress progress) {
  9986. return Post(path, Headers(), std::move(content_provider), content_type,
  9987. progress);
  9988. }
  9989. inline Result ClientImpl::Post(const std::string &path,
  9990. ContentProviderWithoutLength content_provider,
  9991. const std::string &content_type,
  9992. ContentReceiver content_receiver,
  9993. UploadProgress progress) {
  9994. return Post(path, Headers(), std::move(content_provider), content_type,
  9995. std::move(content_receiver), progress);
  9996. }
  9997. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9998. const Params &params) {
  9999. auto query = detail::params_to_query_str(params);
  10000. return Post(path, headers, query, "application/x-www-form-urlencoded");
  10001. }
  10002. inline Result ClientImpl::Post(const std::string &path,
  10003. const UploadFormDataItems &items,
  10004. UploadProgress progress) {
  10005. return Post(path, Headers(), items, progress);
  10006. }
  10007. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10008. const UploadFormDataItems &items,
  10009. UploadProgress progress) {
  10010. const auto &boundary = detail::make_multipart_data_boundary();
  10011. const auto &content_type =
  10012. detail::serialize_multipart_formdata_get_content_type(boundary);
  10013. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10014. return Post(path, headers, body, content_type, progress);
  10015. }
  10016. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10017. const UploadFormDataItems &items,
  10018. const std::string &boundary,
  10019. UploadProgress progress) {
  10020. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10021. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10022. }
  10023. const auto &content_type =
  10024. detail::serialize_multipart_formdata_get_content_type(boundary);
  10025. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10026. return Post(path, headers, body, content_type, progress);
  10027. }
  10028. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10029. const char *body, size_t content_length,
  10030. const std::string &content_type,
  10031. UploadProgress progress) {
  10032. return send_with_content_provider_and_receiver(
  10033. "POST", path, headers, body, content_length, nullptr, nullptr,
  10034. content_type, nullptr, progress);
  10035. }
  10036. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10037. const std::string &body,
  10038. const std::string &content_type,
  10039. UploadProgress progress) {
  10040. return send_with_content_provider_and_receiver(
  10041. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  10042. content_type, nullptr, progress);
  10043. }
  10044. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10045. size_t content_length,
  10046. ContentProvider content_provider,
  10047. const std::string &content_type,
  10048. UploadProgress progress) {
  10049. return send_with_content_provider_and_receiver(
  10050. "POST", path, headers, nullptr, content_length,
  10051. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10052. }
  10053. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10054. size_t content_length,
  10055. ContentProvider content_provider,
  10056. const std::string &content_type,
  10057. ContentReceiver content_receiver,
  10058. DownloadProgress progress) {
  10059. return send_with_content_provider_and_receiver(
  10060. "POST", path, headers, nullptr, content_length,
  10061. std::move(content_provider), nullptr, content_type,
  10062. std::move(content_receiver), std::move(progress));
  10063. }
  10064. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10065. ContentProviderWithoutLength content_provider,
  10066. const std::string &content_type,
  10067. UploadProgress progress) {
  10068. return send_with_content_provider_and_receiver(
  10069. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10070. content_type, nullptr, progress);
  10071. }
  10072. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10073. ContentProviderWithoutLength content_provider,
  10074. const std::string &content_type,
  10075. ContentReceiver content_receiver,
  10076. DownloadProgress progress) {
  10077. return send_with_content_provider_and_receiver(
  10078. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10079. content_type, std::move(content_receiver), std::move(progress));
  10080. }
  10081. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10082. const UploadFormDataItems &items,
  10083. const FormDataProviderItems &provider_items,
  10084. UploadProgress progress) {
  10085. const auto &boundary = detail::make_multipart_data_boundary();
  10086. const auto &content_type =
  10087. detail::serialize_multipart_formdata_get_content_type(boundary);
  10088. return send_with_content_provider_and_receiver(
  10089. "POST", path, headers, nullptr, 0, nullptr,
  10090. get_multipart_content_provider(boundary, items, provider_items),
  10091. content_type, nullptr, progress);
  10092. }
  10093. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10094. const std::string &body,
  10095. const std::string &content_type,
  10096. ContentReceiver content_receiver,
  10097. DownloadProgress progress) {
  10098. Request req;
  10099. req.method = "POST";
  10100. req.path = path;
  10101. req.headers = headers;
  10102. req.body = body;
  10103. req.content_receiver =
  10104. [content_receiver](const char *data, size_t data_length,
  10105. size_t /*offset*/, size_t /*total_length*/) {
  10106. return content_receiver(data, data_length);
  10107. };
  10108. req.download_progress = std::move(progress);
  10109. if (max_timeout_msec_ > 0) {
  10110. req.start_time_ = std::chrono::steady_clock::now();
  10111. }
  10112. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10113. return send_(std::move(req));
  10114. }
  10115. inline Result ClientImpl::Put(const std::string &path) {
  10116. return Put(path, std::string(), std::string());
  10117. }
  10118. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  10119. return Put(path, headers, nullptr, 0, std::string());
  10120. }
  10121. inline Result ClientImpl::Put(const std::string &path, const char *body,
  10122. size_t content_length,
  10123. const std::string &content_type,
  10124. UploadProgress progress) {
  10125. return Put(path, Headers(), body, content_length, content_type, progress);
  10126. }
  10127. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  10128. const std::string &content_type,
  10129. UploadProgress progress) {
  10130. return Put(path, Headers(), body, content_type, progress);
  10131. }
  10132. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  10133. return Put(path, Headers(), params);
  10134. }
  10135. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10136. ContentProvider content_provider,
  10137. const std::string &content_type,
  10138. UploadProgress progress) {
  10139. return Put(path, Headers(), content_length, std::move(content_provider),
  10140. content_type, progress);
  10141. }
  10142. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10143. ContentProvider content_provider,
  10144. const std::string &content_type,
  10145. ContentReceiver content_receiver,
  10146. UploadProgress progress) {
  10147. return Put(path, Headers(), content_length, std::move(content_provider),
  10148. content_type, std::move(content_receiver), progress);
  10149. }
  10150. inline Result ClientImpl::Put(const std::string &path,
  10151. ContentProviderWithoutLength content_provider,
  10152. const std::string &content_type,
  10153. UploadProgress progress) {
  10154. return Put(path, Headers(), std::move(content_provider), content_type,
  10155. progress);
  10156. }
  10157. inline Result ClientImpl::Put(const std::string &path,
  10158. ContentProviderWithoutLength content_provider,
  10159. const std::string &content_type,
  10160. ContentReceiver content_receiver,
  10161. UploadProgress progress) {
  10162. return Put(path, Headers(), std::move(content_provider), content_type,
  10163. std::move(content_receiver), progress);
  10164. }
  10165. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10166. const Params &params) {
  10167. auto query = detail::params_to_query_str(params);
  10168. return Put(path, headers, query, "application/x-www-form-urlencoded");
  10169. }
  10170. inline Result ClientImpl::Put(const std::string &path,
  10171. const UploadFormDataItems &items,
  10172. UploadProgress progress) {
  10173. return Put(path, Headers(), items, progress);
  10174. }
  10175. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10176. const UploadFormDataItems &items,
  10177. UploadProgress progress) {
  10178. const auto &boundary = detail::make_multipart_data_boundary();
  10179. const auto &content_type =
  10180. detail::serialize_multipart_formdata_get_content_type(boundary);
  10181. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10182. return Put(path, headers, body, content_type, progress);
  10183. }
  10184. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10185. const UploadFormDataItems &items,
  10186. const std::string &boundary,
  10187. UploadProgress progress) {
  10188. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10189. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10190. }
  10191. const auto &content_type =
  10192. detail::serialize_multipart_formdata_get_content_type(boundary);
  10193. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10194. return Put(path, headers, body, content_type, progress);
  10195. }
  10196. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10197. const char *body, size_t content_length,
  10198. const std::string &content_type,
  10199. UploadProgress progress) {
  10200. return send_with_content_provider_and_receiver(
  10201. "PUT", path, headers, body, content_length, nullptr, nullptr,
  10202. content_type, nullptr, progress);
  10203. }
  10204. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10205. const std::string &body,
  10206. const std::string &content_type,
  10207. UploadProgress progress) {
  10208. return send_with_content_provider_and_receiver(
  10209. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  10210. content_type, nullptr, progress);
  10211. }
  10212. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10213. size_t content_length,
  10214. ContentProvider content_provider,
  10215. const std::string &content_type,
  10216. UploadProgress progress) {
  10217. return send_with_content_provider_and_receiver(
  10218. "PUT", path, headers, nullptr, content_length,
  10219. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10220. }
  10221. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10222. size_t content_length,
  10223. ContentProvider content_provider,
  10224. const std::string &content_type,
  10225. ContentReceiver content_receiver,
  10226. UploadProgress progress) {
  10227. return send_with_content_provider_and_receiver(
  10228. "PUT", path, headers, nullptr, content_length,
  10229. std::move(content_provider), nullptr, content_type,
  10230. std::move(content_receiver), progress);
  10231. }
  10232. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10233. ContentProviderWithoutLength content_provider,
  10234. const std::string &content_type,
  10235. UploadProgress progress) {
  10236. return send_with_content_provider_and_receiver(
  10237. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10238. content_type, nullptr, progress);
  10239. }
  10240. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10241. ContentProviderWithoutLength content_provider,
  10242. const std::string &content_type,
  10243. ContentReceiver content_receiver,
  10244. UploadProgress progress) {
  10245. return send_with_content_provider_and_receiver(
  10246. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10247. content_type, std::move(content_receiver), progress);
  10248. }
  10249. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10250. const UploadFormDataItems &items,
  10251. const FormDataProviderItems &provider_items,
  10252. UploadProgress progress) {
  10253. const auto &boundary = detail::make_multipart_data_boundary();
  10254. const auto &content_type =
  10255. detail::serialize_multipart_formdata_get_content_type(boundary);
  10256. return send_with_content_provider_and_receiver(
  10257. "PUT", path, headers, nullptr, 0, nullptr,
  10258. get_multipart_content_provider(boundary, items, provider_items),
  10259. content_type, nullptr, progress);
  10260. }
  10261. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10262. const std::string &body,
  10263. const std::string &content_type,
  10264. ContentReceiver content_receiver,
  10265. DownloadProgress progress) {
  10266. Request req;
  10267. req.method = "PUT";
  10268. req.path = path;
  10269. req.headers = headers;
  10270. req.body = body;
  10271. req.content_receiver =
  10272. [content_receiver](const char *data, size_t data_length,
  10273. size_t /*offset*/, size_t /*total_length*/) {
  10274. return content_receiver(data, data_length);
  10275. };
  10276. req.download_progress = std::move(progress);
  10277. if (max_timeout_msec_ > 0) {
  10278. req.start_time_ = std::chrono::steady_clock::now();
  10279. }
  10280. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10281. return send_(std::move(req));
  10282. }
  10283. inline Result ClientImpl::Patch(const std::string &path) {
  10284. return Patch(path, std::string(), std::string());
  10285. }
  10286. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10287. UploadProgress progress) {
  10288. return Patch(path, headers, nullptr, 0, std::string(), progress);
  10289. }
  10290. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  10291. size_t content_length,
  10292. const std::string &content_type,
  10293. UploadProgress progress) {
  10294. return Patch(path, Headers(), body, content_length, content_type, progress);
  10295. }
  10296. inline Result ClientImpl::Patch(const std::string &path,
  10297. const std::string &body,
  10298. const std::string &content_type,
  10299. UploadProgress progress) {
  10300. return Patch(path, Headers(), body, content_type, progress);
  10301. }
  10302. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  10303. return Patch(path, Headers(), params);
  10304. }
  10305. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10306. ContentProvider content_provider,
  10307. const std::string &content_type,
  10308. UploadProgress progress) {
  10309. return Patch(path, Headers(), content_length, std::move(content_provider),
  10310. content_type, progress);
  10311. }
  10312. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10313. ContentProvider content_provider,
  10314. const std::string &content_type,
  10315. ContentReceiver content_receiver,
  10316. UploadProgress progress) {
  10317. return Patch(path, Headers(), content_length, std::move(content_provider),
  10318. content_type, std::move(content_receiver), progress);
  10319. }
  10320. inline Result ClientImpl::Patch(const std::string &path,
  10321. ContentProviderWithoutLength content_provider,
  10322. const std::string &content_type,
  10323. UploadProgress progress) {
  10324. return Patch(path, Headers(), std::move(content_provider), content_type,
  10325. progress);
  10326. }
  10327. inline Result ClientImpl::Patch(const std::string &path,
  10328. ContentProviderWithoutLength content_provider,
  10329. const std::string &content_type,
  10330. ContentReceiver content_receiver,
  10331. UploadProgress progress) {
  10332. return Patch(path, Headers(), std::move(content_provider), content_type,
  10333. std::move(content_receiver), progress);
  10334. }
  10335. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10336. const Params &params) {
  10337. auto query = detail::params_to_query_str(params);
  10338. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  10339. }
  10340. inline Result ClientImpl::Patch(const std::string &path,
  10341. const UploadFormDataItems &items,
  10342. UploadProgress progress) {
  10343. return Patch(path, Headers(), items, progress);
  10344. }
  10345. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10346. const UploadFormDataItems &items,
  10347. UploadProgress progress) {
  10348. const auto &boundary = detail::make_multipart_data_boundary();
  10349. const auto &content_type =
  10350. detail::serialize_multipart_formdata_get_content_type(boundary);
  10351. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10352. return Patch(path, headers, body, content_type, progress);
  10353. }
  10354. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10355. const UploadFormDataItems &items,
  10356. const std::string &boundary,
  10357. UploadProgress progress) {
  10358. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10359. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10360. }
  10361. const auto &content_type =
  10362. detail::serialize_multipart_formdata_get_content_type(boundary);
  10363. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10364. return Patch(path, headers, body, content_type, progress);
  10365. }
  10366. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10367. const char *body, size_t content_length,
  10368. const std::string &content_type,
  10369. UploadProgress progress) {
  10370. return send_with_content_provider_and_receiver(
  10371. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  10372. content_type, nullptr, progress);
  10373. }
  10374. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10375. const std::string &body,
  10376. const std::string &content_type,
  10377. UploadProgress progress) {
  10378. return send_with_content_provider_and_receiver(
  10379. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  10380. content_type, nullptr, progress);
  10381. }
  10382. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10383. size_t content_length,
  10384. ContentProvider content_provider,
  10385. const std::string &content_type,
  10386. UploadProgress progress) {
  10387. return send_with_content_provider_and_receiver(
  10388. "PATCH", path, headers, nullptr, content_length,
  10389. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10390. }
  10391. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10392. size_t content_length,
  10393. ContentProvider content_provider,
  10394. const std::string &content_type,
  10395. ContentReceiver content_receiver,
  10396. UploadProgress progress) {
  10397. return send_with_content_provider_and_receiver(
  10398. "PATCH", path, headers, nullptr, content_length,
  10399. std::move(content_provider), nullptr, content_type,
  10400. std::move(content_receiver), progress);
  10401. }
  10402. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10403. ContentProviderWithoutLength content_provider,
  10404. const std::string &content_type,
  10405. UploadProgress progress) {
  10406. return send_with_content_provider_and_receiver(
  10407. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10408. content_type, nullptr, progress);
  10409. }
  10410. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10411. ContentProviderWithoutLength content_provider,
  10412. const std::string &content_type,
  10413. ContentReceiver content_receiver,
  10414. UploadProgress progress) {
  10415. return send_with_content_provider_and_receiver(
  10416. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10417. content_type, std::move(content_receiver), progress);
  10418. }
  10419. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10420. const UploadFormDataItems &items,
  10421. const FormDataProviderItems &provider_items,
  10422. UploadProgress progress) {
  10423. const auto &boundary = detail::make_multipart_data_boundary();
  10424. const auto &content_type =
  10425. detail::serialize_multipart_formdata_get_content_type(boundary);
  10426. return send_with_content_provider_and_receiver(
  10427. "PATCH", path, headers, nullptr, 0, nullptr,
  10428. get_multipart_content_provider(boundary, items, provider_items),
  10429. content_type, nullptr, progress);
  10430. }
  10431. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10432. const std::string &body,
  10433. const std::string &content_type,
  10434. ContentReceiver content_receiver,
  10435. DownloadProgress progress) {
  10436. Request req;
  10437. req.method = "PATCH";
  10438. req.path = path;
  10439. req.headers = headers;
  10440. req.body = body;
  10441. req.content_receiver =
  10442. [content_receiver](const char *data, size_t data_length,
  10443. size_t /*offset*/, size_t /*total_length*/) {
  10444. return content_receiver(data, data_length);
  10445. };
  10446. req.download_progress = std::move(progress);
  10447. if (max_timeout_msec_ > 0) {
  10448. req.start_time_ = std::chrono::steady_clock::now();
  10449. }
  10450. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10451. return send_(std::move(req));
  10452. }
  10453. inline Result ClientImpl::Delete(const std::string &path,
  10454. DownloadProgress progress) {
  10455. return Delete(path, Headers(), std::string(), std::string(), progress);
  10456. }
  10457. inline Result ClientImpl::Delete(const std::string &path,
  10458. const Headers &headers,
  10459. DownloadProgress progress) {
  10460. return Delete(path, headers, std::string(), std::string(), progress);
  10461. }
  10462. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  10463. size_t content_length,
  10464. const std::string &content_type,
  10465. DownloadProgress progress) {
  10466. return Delete(path, Headers(), body, content_length, content_type, progress);
  10467. }
  10468. inline Result ClientImpl::Delete(const std::string &path,
  10469. const std::string &body,
  10470. const std::string &content_type,
  10471. DownloadProgress progress) {
  10472. return Delete(path, Headers(), body.data(), body.size(), content_type,
  10473. progress);
  10474. }
  10475. inline Result ClientImpl::Delete(const std::string &path,
  10476. const Headers &headers,
  10477. const std::string &body,
  10478. const std::string &content_type,
  10479. DownloadProgress progress) {
  10480. return Delete(path, headers, body.data(), body.size(), content_type,
  10481. progress);
  10482. }
  10483. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  10484. DownloadProgress progress) {
  10485. return Delete(path, Headers(), params, progress);
  10486. }
  10487. inline Result ClientImpl::Delete(const std::string &path,
  10488. const Headers &headers, const Params &params,
  10489. DownloadProgress progress) {
  10490. auto query = detail::params_to_query_str(params);
  10491. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  10492. progress);
  10493. }
  10494. inline Result ClientImpl::Delete(const std::string &path,
  10495. const Headers &headers, const char *body,
  10496. size_t content_length,
  10497. const std::string &content_type,
  10498. DownloadProgress progress) {
  10499. Request req;
  10500. req.method = "DELETE";
  10501. req.headers = headers;
  10502. req.path = path;
  10503. req.download_progress = std::move(progress);
  10504. if (max_timeout_msec_ > 0) {
  10505. req.start_time_ = std::chrono::steady_clock::now();
  10506. }
  10507. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10508. req.body.assign(body, content_length);
  10509. return send_(std::move(req));
  10510. }
  10511. inline Result ClientImpl::Options(const std::string &path) {
  10512. return Options(path, Headers());
  10513. }
  10514. inline Result ClientImpl::Options(const std::string &path,
  10515. const Headers &headers) {
  10516. Request req;
  10517. req.method = "OPTIONS";
  10518. req.headers = headers;
  10519. req.path = path;
  10520. if (max_timeout_msec_ > 0) {
  10521. req.start_time_ = std::chrono::steady_clock::now();
  10522. }
  10523. return send_(std::move(req));
  10524. }
  10525. inline void ClientImpl::stop() {
  10526. std::lock_guard<std::mutex> guard(socket_mutex_);
  10527. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  10528. // do is to shutdown_socket, so that threads using this socket suddenly
  10529. // discover they can't read/write any more and error out. Everything else
  10530. // (closing the socket, shutting ssl down) is unsafe because these actions
  10531. // are not thread-safe.
  10532. if (socket_requests_in_flight_ > 0) {
  10533. shutdown_socket(socket_);
  10534. // Aside from that, we set a flag for the socket to be closed when we're
  10535. // done.
  10536. socket_should_be_closed_when_request_is_done_ = true;
  10537. return;
  10538. }
  10539. // Otherwise, still holding the mutex, we can shut everything down ourselves
  10540. shutdown_ssl(socket_, true);
  10541. shutdown_socket(socket_);
  10542. close_socket(socket_);
  10543. }
  10544. inline std::string ClientImpl::host() const { return host_; }
  10545. inline int ClientImpl::port() const { return port_; }
  10546. inline size_t ClientImpl::is_socket_open() const {
  10547. std::lock_guard<std::mutex> guard(socket_mutex_);
  10548. return socket_.is_open();
  10549. }
  10550. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  10551. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  10552. connection_timeout_sec_ = sec;
  10553. connection_timeout_usec_ = usec;
  10554. }
  10555. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  10556. read_timeout_sec_ = sec;
  10557. read_timeout_usec_ = usec;
  10558. }
  10559. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  10560. write_timeout_sec_ = sec;
  10561. write_timeout_usec_ = usec;
  10562. }
  10563. inline void ClientImpl::set_max_timeout(time_t msec) {
  10564. max_timeout_msec_ = msec;
  10565. }
  10566. inline void ClientImpl::set_basic_auth(const std::string &username,
  10567. const std::string &password) {
  10568. basic_auth_username_ = username;
  10569. basic_auth_password_ = password;
  10570. }
  10571. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  10572. bearer_token_auth_token_ = token;
  10573. }
  10574. #ifdef CPPHTTPLIB_SSL_ENABLED
  10575. inline void ClientImpl::set_digest_auth(const std::string &username,
  10576. const std::string &password) {
  10577. digest_auth_username_ = username;
  10578. digest_auth_password_ = password;
  10579. }
  10580. #endif
  10581. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  10582. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  10583. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  10584. inline void
  10585. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  10586. addr_map_ = std::move(addr_map);
  10587. }
  10588. inline void ClientImpl::set_default_headers(Headers headers) {
  10589. default_headers_ = std::move(headers);
  10590. }
  10591. inline void ClientImpl::set_header_writer(
  10592. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  10593. header_writer_ = writer;
  10594. }
  10595. inline void ClientImpl::set_address_family(int family) {
  10596. address_family_ = family;
  10597. }
  10598. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  10599. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  10600. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  10601. socket_options_ = std::move(socket_options);
  10602. }
  10603. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  10604. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  10605. inline void ClientImpl::set_interface(const std::string &intf) {
  10606. interface_ = intf;
  10607. }
  10608. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  10609. proxy_host_ = host;
  10610. proxy_port_ = port;
  10611. }
  10612. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  10613. const std::string &password) {
  10614. proxy_basic_auth_username_ = username;
  10615. proxy_basic_auth_password_ = password;
  10616. }
  10617. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  10618. proxy_bearer_token_auth_token_ = token;
  10619. }
  10620. #ifdef CPPHTTPLIB_SSL_ENABLED
  10621. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  10622. const std::string &ca_cert_dir_path) {
  10623. ca_cert_file_path_ = ca_cert_file_path;
  10624. ca_cert_dir_path_ = ca_cert_dir_path;
  10625. }
  10626. #endif
  10627. #ifdef CPPHTTPLIB_SSL_ENABLED
  10628. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  10629. const std::string &password) {
  10630. proxy_digest_auth_username_ = username;
  10631. proxy_digest_auth_password_ = password;
  10632. }
  10633. #endif
  10634. // ClientImpl::set_ca_cert_store is defined after TLS namespace (uses helpers)
  10635. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10636. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  10637. std::size_t size) const {
  10638. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  10639. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  10640. if (!mem) { return nullptr; }
  10641. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  10642. if (!inf) { return nullptr; }
  10643. auto cts = X509_STORE_new();
  10644. if (cts) {
  10645. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  10646. auto itmp = sk_X509_INFO_value(inf, i);
  10647. if (!itmp) { continue; }
  10648. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  10649. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  10650. }
  10651. }
  10652. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  10653. return cts;
  10654. }
  10655. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10656. #ifdef CPPHTTPLIB_SSL_ENABLED
  10657. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  10658. server_certificate_verification_ = enabled;
  10659. }
  10660. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  10661. server_hostname_verification_ = enabled;
  10662. }
  10663. #endif
  10664. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10665. inline void ClientImpl::set_server_certificate_verifier(
  10666. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  10667. server_certificate_verifier_ = verifier;
  10668. }
  10669. #endif
  10670. inline void ClientImpl::set_logger(Logger logger) {
  10671. logger_ = std::move(logger);
  10672. }
  10673. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  10674. error_logger_ = std::move(error_logger);
  10675. }
  10676. /*
  10677. * OpenSSL Backend Implementation
  10678. */
  10679. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10680. namespace detail {
  10681. namespace crypto {
  10682. inline size_t hash_size(HashAlgorithm algo) {
  10683. switch (algo) {
  10684. case HashAlgorithm::MD5: return 16;
  10685. case HashAlgorithm::SHA1: return 20;
  10686. case HashAlgorithm::SHA256: return 32;
  10687. case HashAlgorithm::SHA384: return 48;
  10688. case HashAlgorithm::SHA512: return 64;
  10689. default: return 0;
  10690. }
  10691. }
  10692. inline const EVP_MD *get_evp_md(HashAlgorithm algo) {
  10693. switch (algo) {
  10694. case HashAlgorithm::MD5: return EVP_md5();
  10695. case HashAlgorithm::SHA1: return EVP_sha1();
  10696. case HashAlgorithm::SHA256: return EVP_sha256();
  10697. case HashAlgorithm::SHA384: return EVP_sha384();
  10698. case HashAlgorithm::SHA512: return EVP_sha512();
  10699. default: return nullptr;
  10700. }
  10701. }
  10702. inline bool hash_raw(HashAlgorithm algo, const void *data, size_t len,
  10703. std::vector<uint8_t> &digest) {
  10704. auto md = get_evp_md(algo);
  10705. if (!md) { return false; }
  10706. auto ctx = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  10707. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  10708. if (!ctx) { return false; }
  10709. unsigned int hash_len = 0;
  10710. digest.resize(EVP_MAX_MD_SIZE);
  10711. if (EVP_DigestInit_ex(ctx.get(), md, nullptr) != 1) { return false; }
  10712. if (EVP_DigestUpdate(ctx.get(), data, len) != 1) { return false; }
  10713. if (EVP_DigestFinal_ex(ctx.get(), digest.data(), &hash_len) != 1) {
  10714. return false;
  10715. }
  10716. digest.resize(hash_len);
  10717. return true;
  10718. }
  10719. inline std::string hash(HashAlgorithm algo, const void *data, size_t len) {
  10720. std::vector<uint8_t> digest;
  10721. if (!hash_raw(algo, data, len, digest)) { return ""; }
  10722. std::stringstream ss;
  10723. for (auto byte : digest) {
  10724. ss << std::hex << std::setw(2) << std::setfill('0')
  10725. << static_cast<unsigned int>(byte);
  10726. }
  10727. return ss.str();
  10728. }
  10729. inline std::string hash(HashAlgorithm algo, const std::string &data) {
  10730. return hash(algo, data.c_str(), data.size());
  10731. }
  10732. } // namespace crypto
  10733. } // namespace detail
  10734. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10735. /*
  10736. * OpenSSL TLS Abstraction Layer Implementation
  10737. */
  10738. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10739. namespace detail {
  10740. namespace tls {
  10741. // OpenSSL-specific helpers for converting native types to PEM
  10742. inline std::string x509_to_pem(X509 *cert) {
  10743. if (!cert) return {};
  10744. BIO *bio = BIO_new(BIO_s_mem());
  10745. if (!bio) return {};
  10746. if (PEM_write_bio_X509(bio, cert) != 1) {
  10747. BIO_free(bio);
  10748. return {};
  10749. }
  10750. char *data = nullptr;
  10751. long len = BIO_get_mem_data(bio, &data);
  10752. std::string pem(data, static_cast<size_t>(len));
  10753. BIO_free(bio);
  10754. return pem;
  10755. }
  10756. inline std::string evp_pkey_to_pem(EVP_PKEY *key) {
  10757. if (!key) return {};
  10758. BIO *bio = BIO_new(BIO_s_mem());
  10759. if (!bio) return {};
  10760. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr,
  10761. nullptr) != 1) {
  10762. BIO_free(bio);
  10763. return {};
  10764. }
  10765. char *data = nullptr;
  10766. long len = BIO_get_mem_data(bio, &data);
  10767. std::string pem(data, static_cast<size_t>(len));
  10768. BIO_free(bio);
  10769. return pem;
  10770. }
  10771. inline std::string x509_store_to_pem(X509_STORE *store) {
  10772. if (!store) return {};
  10773. std::string pem;
  10774. auto objs = X509_STORE_get0_objects(store);
  10775. if (!objs) return {};
  10776. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  10777. auto obj = sk_X509_OBJECT_value(objs, i);
  10778. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  10779. auto cert = X509_OBJECT_get0_X509(obj);
  10780. if (cert) { pem += x509_to_pem(cert); }
  10781. }
  10782. }
  10783. return pem;
  10784. }
  10785. // Helper to map OpenSSL SSL_get_error to ErrorCode
  10786. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  10787. switch (ssl_error) {
  10788. case SSL_ERROR_NONE: return ErrorCode::Success;
  10789. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  10790. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  10791. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  10792. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  10793. case SSL_ERROR_SSL:
  10794. default: return ErrorCode::Fatal;
  10795. }
  10796. }
  10797. inline bool tls_global_init() {
  10798. // OpenSSL 3.0+: OPENSSL_init_ssl() is called automatically
  10799. return OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS |
  10800. OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  10801. nullptr) == 1;
  10802. }
  10803. inline void tls_global_cleanup() {
  10804. // OpenSSL 3.0+: cleanup is automatic
  10805. }
  10806. inline tls_ctx_t tls_create_client_context() {
  10807. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  10808. if (ctx) {
  10809. // Disable auto-retry to properly handle non-blocking I/O
  10810. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  10811. // Set minimum TLS version
  10812. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  10813. }
  10814. return static_cast<tls_ctx_t>(ctx);
  10815. }
  10816. inline void tls_free_context(tls_ctx_t ctx) {
  10817. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  10818. }
  10819. inline bool tls_set_min_version(tls_ctx_t ctx, int version) {
  10820. if (!ctx) return false;
  10821. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx), version) ==
  10822. 1;
  10823. }
  10824. inline bool tls_load_ca_pem(tls_ctx_t ctx, const char *pem, size_t len) {
  10825. if (!ctx || !pem || len == 0) return false;
  10826. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10827. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  10828. if (!store) return false;
  10829. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  10830. if (!bio) return false;
  10831. bool ok = true;
  10832. X509 *cert = nullptr;
  10833. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  10834. nullptr) {
  10835. if (X509_STORE_add_cert(store, cert) != 1) {
  10836. // Ignore duplicate errors
  10837. auto err = ERR_peek_last_error();
  10838. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  10839. ok = false;
  10840. }
  10841. }
  10842. X509_free(cert);
  10843. if (!ok) break;
  10844. }
  10845. BIO_free(bio);
  10846. // Clear any "no more certificates" errors
  10847. ERR_clear_error();
  10848. return ok;
  10849. }
  10850. inline bool tls_load_ca_file(tls_ctx_t ctx, const char *file_path) {
  10851. if (!ctx || !file_path) return false;
  10852. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  10853. nullptr) == 1;
  10854. }
  10855. inline bool tls_load_ca_dir(tls_ctx_t ctx, const char *dir_path) {
  10856. if (!ctx || !dir_path) return false;
  10857. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  10858. dir_path) == 1;
  10859. }
  10860. inline bool tls_load_system_certs(tls_ctx_t ctx) {
  10861. if (!ctx) return false;
  10862. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10863. #ifdef _WIN32
  10864. // Windows: Load from system certificate store
  10865. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  10866. if (!store) return false;
  10867. auto hStore = CertOpenSystemStoreW(NULL, L"ROOT");
  10868. if (!hStore) return false;
  10869. bool loaded_any = false;
  10870. PCCERT_CONTEXT pContext = nullptr;
  10871. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  10872. nullptr) {
  10873. const unsigned char *data = pContext->pbCertEncoded;
  10874. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  10875. if (x509) {
  10876. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  10877. X509_free(x509);
  10878. }
  10879. }
  10880. CertCloseStore(hStore, 0);
  10881. return loaded_any;
  10882. #elif defined(__APPLE__)
  10883. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  10884. // macOS: Load from Keychain
  10885. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  10886. if (!store) return false;
  10887. CFArrayRef certs = nullptr;
  10888. if (SecTrustCopyAnchorCertificates(&certs) != errSecSuccess || !certs) {
  10889. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10890. }
  10891. bool loaded_any = false;
  10892. auto count = CFArrayGetCount(certs);
  10893. for (CFIndex i = 0; i < count; i++) {
  10894. auto cert = reinterpret_cast<SecCertificateRef>(
  10895. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  10896. CFDataRef der = SecCertificateCopyData(cert);
  10897. if (der) {
  10898. const unsigned char *data = CFDataGetBytePtr(der);
  10899. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  10900. if (x509) {
  10901. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  10902. X509_free(x509);
  10903. }
  10904. CFRelease(der);
  10905. }
  10906. }
  10907. CFRelease(certs);
  10908. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10909. #else
  10910. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10911. #endif
  10912. #else
  10913. // Other Unix: use default verify paths
  10914. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10915. #endif
  10916. }
  10917. inline bool tls_set_client_cert_pem(tls_ctx_t ctx, const char *cert,
  10918. const char *key, const char *password) {
  10919. if (!ctx || !cert || !key) return false;
  10920. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10921. // Load certificate
  10922. auto cert_bio = BIO_new_mem_buf(cert, -1);
  10923. if (!cert_bio) return false;
  10924. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  10925. BIO_free(cert_bio);
  10926. if (!x509) return false;
  10927. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  10928. X509_free(x509);
  10929. if (!cert_ok) return false;
  10930. // Load private key
  10931. auto key_bio = BIO_new_mem_buf(key, -1);
  10932. if (!key_bio) return false;
  10933. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  10934. password ? const_cast<char *>(password)
  10935. : nullptr);
  10936. BIO_free(key_bio);
  10937. if (!pkey) return false;
  10938. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  10939. EVP_PKEY_free(pkey);
  10940. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  10941. }
  10942. inline bool tls_set_client_cert_file(tls_ctx_t ctx, const char *cert_path,
  10943. const char *key_path,
  10944. const char *password) {
  10945. if (!ctx || !cert_path || !key_path) return false;
  10946. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10947. if (password && password[0] != '\0') {
  10948. SSL_CTX_set_default_passwd_cb_userdata(
  10949. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  10950. }
  10951. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  10952. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  10953. }
  10954. inline tls_ctx_t tls_create_server_context() {
  10955. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  10956. if (ctx) {
  10957. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  10958. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  10959. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  10960. }
  10961. return static_cast<tls_ctx_t>(ctx);
  10962. }
  10963. inline bool tls_set_server_cert_pem(tls_ctx_t ctx, const char *cert,
  10964. const char *key, const char *password) {
  10965. // Same implementation as client cert
  10966. return tls_set_client_cert_pem(ctx, cert, key, password);
  10967. }
  10968. inline bool tls_set_server_cert_file(tls_ctx_t ctx, const char *cert_path,
  10969. const char *key_path,
  10970. const char *password) {
  10971. // Same implementation as client cert file
  10972. return tls_set_client_cert_file(ctx, cert_path, key_path, password);
  10973. }
  10974. inline bool tls_set_client_ca_file(tls_ctx_t ctx, const char *ca_file,
  10975. const char *ca_dir) {
  10976. if (!ctx) return false;
  10977. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10978. if (ca_file || ca_dir) {
  10979. if (SSL_CTX_load_verify_locations(ssl_ctx, ca_file, ca_dir) != 1) {
  10980. return false;
  10981. }
  10982. }
  10983. // Set CA list for client certificate request
  10984. if (ca_file) {
  10985. auto list = SSL_load_client_CA_file(ca_file);
  10986. if (list) { SSL_CTX_set_client_CA_list(ssl_ctx, list); }
  10987. }
  10988. return true;
  10989. }
  10990. inline void tls_set_verify_client(tls_ctx_t ctx, bool require) {
  10991. if (!ctx) return;
  10992. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  10993. require
  10994. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  10995. : SSL_VERIFY_NONE,
  10996. nullptr);
  10997. }
  10998. inline tls_session_t tls_create_session(tls_ctx_t ctx, socket_t sock) {
  10999. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  11000. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11001. SSL *ssl = SSL_new(ssl_ctx);
  11002. if (!ssl) return nullptr;
  11003. // Disable auto-retry for proper non-blocking I/O handling
  11004. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  11005. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  11006. if (!bio) {
  11007. SSL_free(ssl);
  11008. return nullptr;
  11009. }
  11010. SSL_set_bio(ssl, bio, bio);
  11011. return static_cast<tls_session_t>(ssl);
  11012. }
  11013. inline void tls_free_session(tls_session_t session) {
  11014. if (session) { SSL_free(static_cast<SSL *>(session)); }
  11015. }
  11016. inline bool tls_set_sni(tls_session_t session, const char *hostname) {
  11017. if (!session || !hostname) return false;
  11018. auto ssl = static_cast<SSL *>(session);
  11019. // Set SNI (Server Name Indication) only - does not enable verification
  11020. #if defined(OPENSSL_IS_BORINGSSL)
  11021. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  11022. #else
  11023. // Direct call instead of macro to suppress -Wold-style-cast warning
  11024. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  11025. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  11026. #endif
  11027. }
  11028. inline bool tls_set_hostname(tls_session_t session, const char *hostname) {
  11029. if (!session || !hostname) return false;
  11030. auto ssl = static_cast<SSL *>(session);
  11031. // Set SNI (Server Name Indication)
  11032. if (!tls_set_sni(session, hostname)) { return false; }
  11033. // Enable hostname verification
  11034. auto param = SSL_get0_param(ssl);
  11035. if (!param) return false;
  11036. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  11037. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  11038. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  11039. return true;
  11040. }
  11041. inline TlsError tls_connect(tls_session_t session) {
  11042. if (!session) { return TlsError(); }
  11043. auto ssl = static_cast<SSL *>(session);
  11044. auto ret = SSL_connect(ssl);
  11045. TlsError err;
  11046. if (ret == 1) {
  11047. err.code = ErrorCode::Success;
  11048. } else {
  11049. auto ssl_err = SSL_get_error(ssl, ret);
  11050. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11051. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11052. }
  11053. return err;
  11054. }
  11055. inline TlsError tls_accept(tls_session_t session) {
  11056. if (!session) { return TlsError(); }
  11057. auto ssl = static_cast<SSL *>(session);
  11058. auto ret = SSL_accept(ssl);
  11059. TlsError err;
  11060. if (ret == 1) {
  11061. err.code = ErrorCode::Success;
  11062. } else {
  11063. auto ssl_err = SSL_get_error(ssl, ret);
  11064. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11065. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11066. }
  11067. return err;
  11068. }
  11069. inline bool tls_connect_nonblocking(tls_session_t session, socket_t sock,
  11070. time_t timeout_sec, time_t timeout_usec,
  11071. TlsError *err) {
  11072. if (!session) {
  11073. if (err) { err->code = ErrorCode::Fatal; }
  11074. return false;
  11075. }
  11076. auto ssl = static_cast<SSL *>(session);
  11077. auto bio = SSL_get_rbio(ssl);
  11078. // Set non-blocking mode for handshake
  11079. set_nonblocking(sock, true);
  11080. if (bio) { BIO_set_nbio(bio, 1); }
  11081. auto cleanup = scope_exit([&]() {
  11082. // Restore blocking mode after handshake
  11083. if (bio) { BIO_set_nbio(bio, 0); }
  11084. set_nonblocking(sock, false);
  11085. });
  11086. auto res = 0;
  11087. while ((res = SSL_connect(ssl)) != 1) {
  11088. auto ssl_err = SSL_get_error(ssl, res);
  11089. switch (ssl_err) {
  11090. case SSL_ERROR_WANT_READ:
  11091. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  11092. break;
  11093. case SSL_ERROR_WANT_WRITE:
  11094. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  11095. break;
  11096. default: break;
  11097. }
  11098. if (err) {
  11099. err->code = map_ssl_error(ssl_err, err->sys_errno);
  11100. if (err->code == ErrorCode::Fatal) {
  11101. err->backend_code = ERR_get_error();
  11102. }
  11103. }
  11104. return false;
  11105. }
  11106. if (err) { err->code = ErrorCode::Success; }
  11107. return true;
  11108. }
  11109. inline bool tls_accept_nonblocking(tls_session_t session, socket_t sock,
  11110. time_t timeout_sec, time_t timeout_usec,
  11111. TlsError *err) {
  11112. if (!session) {
  11113. if (err) { err->code = ErrorCode::Fatal; }
  11114. return false;
  11115. }
  11116. auto ssl = static_cast<SSL *>(session);
  11117. auto bio = SSL_get_rbio(ssl);
  11118. // Set non-blocking mode for handshake
  11119. set_nonblocking(sock, true);
  11120. if (bio) { BIO_set_nbio(bio, 1); }
  11121. auto cleanup = scope_exit([&]() {
  11122. // Restore blocking mode after handshake
  11123. if (bio) { BIO_set_nbio(bio, 0); }
  11124. set_nonblocking(sock, false);
  11125. });
  11126. auto res = 0;
  11127. while ((res = SSL_accept(ssl)) != 1) {
  11128. auto ssl_err = SSL_get_error(ssl, res);
  11129. switch (ssl_err) {
  11130. case SSL_ERROR_WANT_READ:
  11131. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  11132. break;
  11133. case SSL_ERROR_WANT_WRITE:
  11134. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  11135. break;
  11136. default: break;
  11137. }
  11138. if (err) {
  11139. err->code = map_ssl_error(ssl_err, err->sys_errno);
  11140. if (err->code == ErrorCode::Fatal) {
  11141. err->backend_code = ERR_get_error();
  11142. }
  11143. }
  11144. return false;
  11145. }
  11146. if (err) { err->code = ErrorCode::Success; }
  11147. return true;
  11148. }
  11149. inline ssize_t tls_read(tls_session_t session, void *buf, size_t len,
  11150. TlsError &err) {
  11151. if (!session || !buf) {
  11152. err.code = ErrorCode::Fatal;
  11153. return -1;
  11154. }
  11155. auto ssl = static_cast<SSL *>(session);
  11156. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  11157. if (ret > 0) {
  11158. err.code = ErrorCode::Success;
  11159. return ret;
  11160. }
  11161. auto ssl_err = SSL_get_error(ssl, ret);
  11162. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11163. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11164. return -1;
  11165. }
  11166. inline ssize_t tls_write(tls_session_t session, const void *buf, size_t len,
  11167. TlsError &err) {
  11168. if (!session || !buf) {
  11169. err.code = ErrorCode::Fatal;
  11170. return -1;
  11171. }
  11172. auto ssl = static_cast<SSL *>(session);
  11173. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  11174. if (ret > 0) {
  11175. err.code = ErrorCode::Success;
  11176. return ret;
  11177. }
  11178. auto ssl_err = SSL_get_error(ssl, ret);
  11179. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11180. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11181. return -1;
  11182. }
  11183. inline int tls_pending(tls_session_t session) {
  11184. if (!session) return 0;
  11185. return SSL_pending(static_cast<SSL *>(session));
  11186. }
  11187. inline void tls_shutdown(tls_session_t session, bool graceful) {
  11188. if (!session) return;
  11189. auto ssl = static_cast<SSL *>(session);
  11190. if (graceful) {
  11191. // First call sends close_notify
  11192. if (SSL_shutdown(ssl) == 0) {
  11193. // Second call waits for peer's close_notify
  11194. SSL_shutdown(ssl);
  11195. }
  11196. }
  11197. }
  11198. inline bool tls_is_peer_closed(tls_session_t session, socket_t sock) {
  11199. if (!session) return true;
  11200. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  11201. set_nonblocking(sock, true);
  11202. auto se = scope_exit([&]() { set_nonblocking(sock, false); });
  11203. auto ssl = static_cast<SSL *>(session);
  11204. char buf;
  11205. auto ret = SSL_peek(ssl, &buf, 1);
  11206. if (ret > 0) return false;
  11207. auto err = SSL_get_error(ssl, ret);
  11208. return err == SSL_ERROR_ZERO_RETURN;
  11209. }
  11210. inline tls_cert_t tls_get_peer_cert(tls_session_t session) {
  11211. if (!session) return nullptr;
  11212. return static_cast<tls_cert_t>(
  11213. SSL_get1_peer_certificate(static_cast<SSL *>(session)));
  11214. }
  11215. inline void tls_free_cert(tls_cert_t cert) {
  11216. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  11217. }
  11218. inline bool tls_verify_hostname(tls_cert_t cert, const char *hostname) {
  11219. if (!cert || !hostname) return false;
  11220. auto x509 = static_cast<X509 *>(cert);
  11221. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  11222. }
  11223. inline long tls_get_verify_result(tls_session_t session) {
  11224. if (!session) return X509_V_ERR_UNSPECIFIED;
  11225. return SSL_get_verify_result(static_cast<SSL *>(session));
  11226. }
  11227. inline std::string tls_get_cert_subject_cn(tls_cert_t cert) {
  11228. if (!cert) return "";
  11229. auto x509 = static_cast<X509 *>(cert);
  11230. auto subject_name = X509_get_subject_name(x509);
  11231. if (!subject_name) return "";
  11232. char buf[256];
  11233. auto len =
  11234. X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf, sizeof(buf));
  11235. if (len < 0) return "";
  11236. return std::string(buf, static_cast<size_t>(len));
  11237. }
  11238. inline std::string tls_get_cert_issuer_name(tls_cert_t cert) {
  11239. if (!cert) return "";
  11240. auto x509 = static_cast<X509 *>(cert);
  11241. auto issuer_name = X509_get_issuer_name(x509);
  11242. if (!issuer_name) return "";
  11243. char buf[256];
  11244. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  11245. return std::string(buf);
  11246. }
  11247. inline bool tls_get_cert_sans(tls_cert_t cert, std::vector<TlsSanEntry> &sans) {
  11248. sans.clear();
  11249. if (!cert) return false;
  11250. auto x509 = static_cast<X509 *>(cert);
  11251. auto names = static_cast<GENERAL_NAMES *>(
  11252. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  11253. if (!names) return true; // No SANs is valid
  11254. auto count = sk_GENERAL_NAME_num(names);
  11255. for (int i = 0; i < count; i++) {
  11256. auto gen = sk_GENERAL_NAME_value(names, i);
  11257. if (!gen) continue;
  11258. TlsSanEntry entry;
  11259. switch (gen->type) {
  11260. case GEN_DNS:
  11261. entry.type = SanType::DNS;
  11262. if (gen->d.dNSName) {
  11263. entry.value = std::string(
  11264. reinterpret_cast<const char *>(
  11265. ASN1_STRING_get0_data(gen->d.dNSName)),
  11266. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  11267. }
  11268. break;
  11269. case GEN_IPADD:
  11270. entry.type = SanType::IP;
  11271. if (gen->d.iPAddress) {
  11272. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  11273. auto len = ASN1_STRING_length(gen->d.iPAddress);
  11274. if (len == 4) {
  11275. // IPv4
  11276. char buf[INET_ADDRSTRLEN];
  11277. inet_ntop(AF_INET, data, buf, sizeof(buf));
  11278. entry.value = buf;
  11279. } else if (len == 16) {
  11280. // IPv6
  11281. char buf[INET6_ADDRSTRLEN];
  11282. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  11283. entry.value = buf;
  11284. }
  11285. }
  11286. break;
  11287. case GEN_EMAIL:
  11288. entry.type = SanType::EMAIL;
  11289. if (gen->d.rfc822Name) {
  11290. entry.value = std::string(
  11291. reinterpret_cast<const char *>(
  11292. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  11293. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  11294. }
  11295. break;
  11296. case GEN_URI:
  11297. entry.type = SanType::URI;
  11298. if (gen->d.uniformResourceIdentifier) {
  11299. entry.value = std::string(
  11300. reinterpret_cast<const char *>(
  11301. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  11302. static_cast<size_t>(
  11303. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  11304. }
  11305. break;
  11306. default: entry.type = SanType::OTHER; break;
  11307. }
  11308. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  11309. }
  11310. GENERAL_NAMES_free(names);
  11311. return true;
  11312. }
  11313. inline bool tls_get_cert_validity(tls_cert_t cert, time_t &not_before,
  11314. time_t &not_after) {
  11315. if (!cert) return false;
  11316. auto x509 = static_cast<X509 *>(cert);
  11317. auto nb = X509_get0_notBefore(x509);
  11318. auto na = X509_get0_notAfter(x509);
  11319. if (!nb || !na) return false;
  11320. // Convert ASN1_TIME to time_t
  11321. struct tm tm_nb = {}, tm_na = {};
  11322. if (ASN1_TIME_to_tm(nb, &tm_nb) != 1) return false;
  11323. if (ASN1_TIME_to_tm(na, &tm_na) != 1) return false;
  11324. #ifdef _WIN32
  11325. not_before = _mkgmtime(&tm_nb);
  11326. not_after = _mkgmtime(&tm_na);
  11327. #else
  11328. not_before = timegm(&tm_nb);
  11329. not_after = timegm(&tm_na);
  11330. #endif
  11331. return true;
  11332. }
  11333. inline std::string tls_get_cert_serial(tls_cert_t cert) {
  11334. if (!cert) return "";
  11335. auto x509 = static_cast<X509 *>(cert);
  11336. auto serial = X509_get_serialNumber(x509);
  11337. if (!serial) return "";
  11338. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  11339. if (!bn) return "";
  11340. auto hex = BN_bn2hex(bn);
  11341. BN_free(bn);
  11342. if (!hex) return "";
  11343. std::string result(hex);
  11344. OPENSSL_free(hex);
  11345. return result;
  11346. }
  11347. inline const char *tls_get_sni(tls_session_t session) {
  11348. if (!session) return nullptr;
  11349. auto ssl = static_cast<SSL *>(session);
  11350. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  11351. }
  11352. inline uint64_t tls_peek_error() { return ERR_peek_last_error(); }
  11353. inline uint64_t tls_get_error() { return ERR_get_error(); }
  11354. inline std::string tls_error_string(uint64_t code) {
  11355. char buf[256];
  11356. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  11357. return std::string(buf);
  11358. }
  11359. inline tls_ca_store_t tls_create_ca_store(const char *pem, size_t len) {
  11360. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  11361. if (!mem) { return nullptr; }
  11362. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  11363. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  11364. if (!inf) { return nullptr; }
  11365. auto store = X509_STORE_new();
  11366. if (store) {
  11367. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  11368. auto itmp = sk_X509_INFO_value(inf, i);
  11369. if (!itmp) { continue; }
  11370. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  11371. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  11372. }
  11373. }
  11374. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  11375. return static_cast<tls_ca_store_t>(store);
  11376. }
  11377. inline void tls_free_ca_store(tls_ca_store_t store) {
  11378. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  11379. }
  11380. inline bool tls_set_ca_store(tls_ctx_t ctx, tls_ca_store_t store) {
  11381. if (!ctx || !store) { return false; }
  11382. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11383. auto x509_store = static_cast<X509_STORE *>(store);
  11384. // Check if same store is already set
  11385. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  11386. // SSL_CTX_set_cert_store takes ownership and frees the old store
  11387. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  11388. return true;
  11389. }
  11390. inline size_t tls_get_ca_certs(tls_ctx_t ctx, std::vector<tls_cert_t> &certs) {
  11391. certs.clear();
  11392. if (!ctx) { return 0; }
  11393. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11394. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  11395. if (!store) { return 0; }
  11396. auto objs = X509_STORE_get0_objects(store);
  11397. if (!objs) { return 0; }
  11398. int count = sk_X509_OBJECT_num(objs);
  11399. for (int i = 0; i < count; i++) {
  11400. auto obj = sk_X509_OBJECT_value(objs, i);
  11401. if (!obj) { continue; }
  11402. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  11403. auto x509 = X509_OBJECT_get0_X509(obj);
  11404. if (x509) {
  11405. // Increment reference count so caller can free it
  11406. X509_up_ref(x509);
  11407. certs.push_back(static_cast<tls_cert_t>(x509));
  11408. }
  11409. }
  11410. }
  11411. return certs.size();
  11412. }
  11413. inline std::vector<std::string> tls_get_ca_names(tls_ctx_t ctx) {
  11414. std::vector<std::string> names;
  11415. if (!ctx) { return names; }
  11416. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11417. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  11418. if (!store) { return names; }
  11419. auto objs = X509_STORE_get0_objects(store);
  11420. if (!objs) { return names; }
  11421. int count = sk_X509_OBJECT_num(objs);
  11422. for (int i = 0; i < count; i++) {
  11423. auto obj = sk_X509_OBJECT_value(objs, i);
  11424. if (!obj) { continue; }
  11425. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  11426. auto x509 = X509_OBJECT_get0_X509(obj);
  11427. if (x509) {
  11428. auto subject = X509_get_subject_name(x509);
  11429. if (subject) {
  11430. char buf[512];
  11431. X509_NAME_oneline(subject, buf, sizeof(buf));
  11432. names.push_back(buf);
  11433. }
  11434. }
  11435. }
  11436. }
  11437. return names;
  11438. }
  11439. inline bool tls_update_server_cert(tls_ctx_t ctx, const char *cert_pem,
  11440. const char *key_pem, const char *password) {
  11441. if (!ctx || !cert_pem || !key_pem) { return false; }
  11442. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11443. // Load certificate from PEM
  11444. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  11445. if (!cert_bio) { return false; }
  11446. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  11447. BIO_free(cert_bio);
  11448. if (!cert) { return false; }
  11449. // Load private key from PEM
  11450. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  11451. if (!key_bio) {
  11452. X509_free(cert);
  11453. return false;
  11454. }
  11455. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  11456. password ? const_cast<char *>(password)
  11457. : nullptr);
  11458. BIO_free(key_bio);
  11459. if (!key) {
  11460. X509_free(cert);
  11461. return false;
  11462. }
  11463. // Update certificate and key
  11464. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  11465. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  11466. X509_free(cert);
  11467. EVP_PKEY_free(key);
  11468. return ret;
  11469. }
  11470. inline bool tls_update_server_client_ca(tls_ctx_t ctx, const char *ca_pem) {
  11471. if (!ctx || !ca_pem) { return false; }
  11472. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11473. // Create new X509_STORE from PEM
  11474. auto store = tls_create_ca_store(ca_pem, strlen(ca_pem));
  11475. if (!store) { return false; }
  11476. // SSL_CTX_set_cert_store takes ownership
  11477. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  11478. return true;
  11479. }
  11480. // Thread-local storage for verify callback
  11481. inline TlsVerifyCallback &get_verify_callback() {
  11482. static thread_local TlsVerifyCallback callback;
  11483. return callback;
  11484. }
  11485. // OpenSSL verify callback wrapper
  11486. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  11487. auto &callback = get_verify_callback();
  11488. if (!callback) { return preverify_ok; }
  11489. // Get SSL object from X509_STORE_CTX
  11490. auto ssl = static_cast<SSL *>(
  11491. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  11492. if (!ssl) { return preverify_ok; }
  11493. // Get peer certificate
  11494. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  11495. if (!cert) { return preverify_ok; }
  11496. // Call user callback
  11497. return callback(static_cast<tls_session_t>(ssl),
  11498. static_cast<tls_cert_t>(cert))
  11499. ? 1
  11500. : 0;
  11501. }
  11502. inline bool tls_set_verify_callback(tls_ctx_t ctx, TlsVerifyCallback callback) {
  11503. if (!ctx) { return false; }
  11504. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11505. get_verify_callback() = std::move(callback);
  11506. if (get_verify_callback()) {
  11507. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, openssl_verify_callback);
  11508. } else {
  11509. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  11510. }
  11511. return true;
  11512. }
  11513. // Thread-local storage for extended verify callback
  11514. inline TlsVerifyCallbackEx &get_verify_callback_ex() {
  11515. static thread_local TlsVerifyCallbackEx callback;
  11516. return callback;
  11517. }
  11518. // OpenSSL extended verify callback wrapper
  11519. inline int openssl_verify_callback_ex(int preverify_ok, X509_STORE_CTX *ctx) {
  11520. auto &callback = get_verify_callback_ex();
  11521. if (!callback) { return preverify_ok; }
  11522. // Get SSL object from X509_STORE_CTX
  11523. auto ssl = static_cast<SSL *>(
  11524. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  11525. if (!ssl) { return preverify_ok; }
  11526. // Get current certificate and depth
  11527. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  11528. int depth = X509_STORE_CTX_get_error_depth(ctx);
  11529. int error = X509_STORE_CTX_get_error(ctx);
  11530. // Build context
  11531. TlsVerifyContext verify_ctx;
  11532. verify_ctx.session = static_cast<tls_session_t>(ssl);
  11533. verify_ctx.cert = static_cast<tls_cert_t>(cert);
  11534. verify_ctx.depth = depth;
  11535. verify_ctx.preverify_ok = (preverify_ok != 0);
  11536. verify_ctx.error_code = error;
  11537. verify_ctx.error_string =
  11538. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  11539. return callback(verify_ctx) ? 1 : 0;
  11540. }
  11541. inline bool tls_set_verify_callback_ex(tls_ctx_t ctx,
  11542. TlsVerifyCallbackEx callback) {
  11543. if (!ctx) { return false; }
  11544. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11545. get_verify_callback_ex() = std::move(callback);
  11546. if (get_verify_callback_ex()) {
  11547. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, openssl_verify_callback_ex);
  11548. } else {
  11549. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  11550. }
  11551. return true;
  11552. }
  11553. inline long tls_get_verify_error(tls_session_t session) {
  11554. if (!session) { return -1; }
  11555. auto ssl = static_cast<SSL *>(session);
  11556. return SSL_get_verify_result(ssl);
  11557. }
  11558. inline std::string tls_verify_error_string(long error_code) {
  11559. if (error_code == X509_V_OK) { return ""; }
  11560. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  11561. return str ? str : "unknown error";
  11562. }
  11563. // OpenSSL-specific helpers for public API wrappers
  11564. inline tls_ctx_t create_server_context_from_x509(X509 *cert, EVP_PKEY *key,
  11565. X509_STORE *client_ca_store,
  11566. int &out_error) {
  11567. out_error = 0;
  11568. auto cert_pem = x509_to_pem(cert);
  11569. auto key_pem = evp_pkey_to_pem(key);
  11570. if (cert_pem.empty() || key_pem.empty()) {
  11571. out_error = static_cast<int>(ERR_get_error());
  11572. return nullptr;
  11573. }
  11574. auto ctx = tls_create_server_context();
  11575. if (!ctx) {
  11576. out_error = static_cast<int>(tls_get_error());
  11577. return nullptr;
  11578. }
  11579. if (!tls_set_server_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  11580. nullptr)) {
  11581. out_error = static_cast<int>(tls_get_error());
  11582. tls_free_context(ctx);
  11583. return nullptr;
  11584. }
  11585. if (client_ca_store) {
  11586. auto ca_pem = x509_store_to_pem(client_ca_store);
  11587. if (!ca_pem.empty()) {
  11588. auto ca_store = tls_create_ca_store(ca_pem.c_str(), ca_pem.size());
  11589. if (ca_store && tls_set_ca_store(ctx, ca_store)) {
  11590. tls_set_verify_client(ctx, true);
  11591. } else {
  11592. out_error = static_cast<int>(tls_get_error());
  11593. }
  11594. }
  11595. X509_STORE_free(client_ca_store);
  11596. }
  11597. return ctx;
  11598. }
  11599. inline void update_server_certs_from_x509(tls_ctx_t ctx, X509 *cert,
  11600. EVP_PKEY *key,
  11601. X509_STORE *client_ca_store) {
  11602. auto cert_pem = x509_to_pem(cert);
  11603. auto key_pem = evp_pkey_to_pem(key);
  11604. if (!cert_pem.empty() && !key_pem.empty()) {
  11605. tls_update_server_cert(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr);
  11606. }
  11607. if (client_ca_store) {
  11608. auto ca_pem = x509_store_to_pem(client_ca_store);
  11609. if (!ca_pem.empty()) { tls_update_server_client_ca(ctx, ca_pem.c_str()); }
  11610. X509_STORE_free(client_ca_store);
  11611. }
  11612. }
  11613. inline tls_ctx_t create_client_context_from_x509(X509 *cert, EVP_PKEY *key,
  11614. const char *password,
  11615. unsigned long &out_error) {
  11616. out_error = 0;
  11617. auto ctx = tls_create_client_context();
  11618. if (!ctx) {
  11619. out_error = static_cast<unsigned long>(tls_get_error());
  11620. return nullptr;
  11621. }
  11622. if (cert && key) {
  11623. auto cert_pem = x509_to_pem(cert);
  11624. auto key_pem = evp_pkey_to_pem(key);
  11625. if (cert_pem.empty() || key_pem.empty()) {
  11626. out_error = ERR_get_error();
  11627. tls_free_context(ctx);
  11628. return nullptr;
  11629. }
  11630. if (!tls_set_client_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  11631. password)) {
  11632. out_error = static_cast<unsigned long>(tls_get_error());
  11633. tls_free_context(ctx);
  11634. return nullptr;
  11635. }
  11636. }
  11637. return ctx;
  11638. }
  11639. } // namespace tls
  11640. } // namespace detail
  11641. // ClientImpl::set_ca_cert_store - defined here to use tls::x509_store_to_pem
  11642. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  11643. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  11644. ca_cert_pem_ = detail::tls::x509_store_to_pem(ca_cert_store);
  11645. ca_cert_store_ = ca_cert_store;
  11646. }
  11647. }
  11648. /*
  11649. * OpenSSL-specific SSLServer/SSLClient Implementation
  11650. */
  11651. inline bool SSLClient::check_host_name(const char *pattern,
  11652. size_t pattern_len) const {
  11653. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  11654. // Wildcard match
  11655. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  11656. std::vector<std::string> pattern_components;
  11657. detail::split(&pattern[0], &pattern[pattern_len], '.',
  11658. [&](const char *b, const char *e) {
  11659. pattern_components.emplace_back(b, e);
  11660. });
  11661. if (host_components_.size() != pattern_components.size()) { return false; }
  11662. auto itr = pattern_components.begin();
  11663. for (const auto &h : host_components_) {
  11664. auto &p = *itr;
  11665. if (p != h && p != "*") {
  11666. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  11667. !p.compare(0, p.size() - 1, h));
  11668. if (!partial_match) { return false; }
  11669. }
  11670. ++itr;
  11671. }
  11672. return true;
  11673. }
  11674. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  11675. X509_STORE *client_ca_cert_store) {
  11676. ctx_ = detail::tls::create_server_context_from_x509(
  11677. cert, private_key, client_ca_cert_store, last_ssl_error_);
  11678. }
  11679. inline SSLServer::SSLServer(
  11680. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  11681. // Use abstract API to create context
  11682. ctx_ = detail::tls::tls_create_server_context();
  11683. if (ctx_) {
  11684. // Pass to OpenSSL-specific callback (ctx_ is SSL_CTX* internally)
  11685. auto ssl_ctx = static_cast<SSL_CTX *>(ctx_);
  11686. if (!setup_ssl_ctx_callback(*ssl_ctx)) {
  11687. detail::tls::tls_free_context(ctx_);
  11688. ctx_ = nullptr;
  11689. }
  11690. }
  11691. }
  11692. inline SSL_CTX *SSLServer::ssl_context() const {
  11693. return static_cast<SSL_CTX *>(ctx_);
  11694. }
  11695. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  11696. X509_STORE *client_ca_cert_store) {
  11697. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11698. detail::tls::update_server_certs_from_x509(ctx_, cert, private_key,
  11699. client_ca_cert_store);
  11700. }
  11701. inline STACK_OF(X509_NAME) * SSLServer::extract_ca_names_from_x509_store(
  11702. X509_STORE *store) {
  11703. if (!store) { return nullptr; }
  11704. auto ca_list = sk_X509_NAME_new_null();
  11705. if (!ca_list) { return nullptr; }
  11706. // Get all objects from the store
  11707. auto objs = X509_STORE_get0_objects(store);
  11708. if (!objs) {
  11709. sk_X509_NAME_free(ca_list);
  11710. return nullptr;
  11711. }
  11712. // Iterate through objects and extract certificate subject names
  11713. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  11714. auto obj = sk_X509_OBJECT_value(objs, i);
  11715. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  11716. auto cert = X509_OBJECT_get0_X509(obj);
  11717. if (cert) {
  11718. auto subject = X509_get_subject_name(cert);
  11719. if (subject) {
  11720. auto name_dup = X509_NAME_dup(subject);
  11721. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  11722. }
  11723. }
  11724. }
  11725. }
  11726. // If no names were extracted, free the list and return nullptr
  11727. if (sk_X509_NAME_num(ca_list) == 0) {
  11728. sk_X509_NAME_free(ca_list);
  11729. return nullptr;
  11730. }
  11731. return ca_list;
  11732. }
  11733. // SSL HTTP client implementation
  11734. inline SSLClient::SSLClient(const std::string &host)
  11735. : SSLClient(host, 443, std::string(), std::string()) {}
  11736. inline SSLClient::SSLClient(const std::string &host, int port)
  11737. : SSLClient(host, port, std::string(), std::string()) {}
  11738. inline SSLClient::SSLClient(const std::string &host, int port,
  11739. const std::string &client_cert_path,
  11740. const std::string &client_key_path,
  11741. const std::string &private_key_password)
  11742. : ClientImpl(host, port, client_cert_path, client_key_path) {
  11743. ctx_ = detail::tls::tls_create_client_context();
  11744. // TODO: Add tls_set_min_protocol_version() to TLS abstraction API
  11745. // SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  11746. detail::split(&host_[0], &host_[host_.size()], '.',
  11747. [&](const char *b, const char *e) {
  11748. host_components_.emplace_back(b, e);
  11749. });
  11750. if (!client_cert_path.empty() && !client_key_path.empty()) {
  11751. const char *password =
  11752. private_key_password.empty() ? nullptr : private_key_password.c_str();
  11753. if (!detail::tls::tls_set_client_cert_file(ctx_, client_cert_path.c_str(),
  11754. client_key_path.c_str(),
  11755. password)) {
  11756. last_backend_error_ = ERR_get_error();
  11757. detail::tls::tls_free_context(ctx_);
  11758. ctx_ = nullptr;
  11759. }
  11760. }
  11761. }
  11762. inline SSLClient::SSLClient(const std::string &host, int port,
  11763. X509 *client_cert, EVP_PKEY *client_key,
  11764. const std::string &private_key_password)
  11765. : ClientImpl(host, port) {
  11766. const char *password =
  11767. private_key_password.empty() ? nullptr : private_key_password.c_str();
  11768. ctx_ = detail::tls::create_client_context_from_x509(
  11769. client_cert, client_key, password, last_backend_error_);
  11770. detail::split(&host_[0], &host_[host_.size()], '.',
  11771. [&](const char *b, const char *e) {
  11772. host_components_.emplace_back(b, e);
  11773. });
  11774. }
  11775. inline SSLClient::SSLClient(const std::string &host, int port,
  11776. const PemMemory &pem)
  11777. : ClientImpl(host, port) {
  11778. ctx_ = detail::tls::tls_create_client_context();
  11779. detail::split(&host_[0], &host_[host_.size()], '.',
  11780. [&](const char *b, const char *e) {
  11781. host_components_.emplace_back(b, e);
  11782. });
  11783. if (ctx_ && pem.cert_pem && pem.key_pem) {
  11784. if (!detail::tls::tls_set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  11785. pem.private_key_password)) {
  11786. last_backend_error_ = detail::tls::tls_get_error();
  11787. detail::tls::tls_free_context(ctx_);
  11788. ctx_ = nullptr;
  11789. }
  11790. }
  11791. }
  11792. inline void SSLClient::set_ca_cert_store(void *ca_cert_store) {
  11793. if (ca_cert_store && ctx_) {
  11794. // tls_set_ca_store takes ownership of ca_cert_store
  11795. detail::tls::tls_set_ca_store(ctx_, ca_cert_store);
  11796. } else if (ca_cert_store) {
  11797. detail::tls::tls_free_ca_store(ca_cert_store);
  11798. }
  11799. }
  11800. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  11801. std::size_t size) {
  11802. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  11803. set_ca_cert_store(detail::tls::tls_create_ca_store(ca_cert, size));
  11804. }
  11805. inline void
  11806. SSLClient::set_server_certificate_verifier(TlsVerifyCallback verifier) {
  11807. if (!ctx_) { return; }
  11808. detail::tls::tls_set_verify_callback(
  11809. ctx_, [verifier](detail::tls::tls_session_t session,
  11810. detail::tls::tls_cert_t cert) {
  11811. return verifier(session, cert);
  11812. });
  11813. }
  11814. inline long SSLClient::get_openssl_verify_result() const {
  11815. return verify_result_;
  11816. }
  11817. inline SSL_CTX *SSLClient::ssl_context() const {
  11818. return static_cast<SSL_CTX *>(ctx_);
  11819. }
  11820. inline bool SSLClient::load_certs() {
  11821. auto ret = true;
  11822. std::call_once(initialize_cert_, [&]() {
  11823. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11824. if (!ca_cert_file_path_.empty()) {
  11825. if (!detail::tls::tls_load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  11826. last_backend_error_ = ERR_get_error();
  11827. ret = false;
  11828. }
  11829. } else if (!ca_cert_dir_path_.empty()) {
  11830. if (!detail::tls::tls_load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  11831. last_backend_error_ = ERR_get_error();
  11832. ret = false;
  11833. }
  11834. } else {
  11835. // Load system certificates
  11836. if (!detail::tls::tls_load_system_certs(ctx_)) {
  11837. last_backend_error_ = ERR_get_error();
  11838. // Ignore error and continue - some systems may not have certs
  11839. }
  11840. }
  11841. });
  11842. return ret;
  11843. }
  11844. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  11845. using namespace detail::tls;
  11846. // Load CA certificates if server verification is enabled
  11847. if (server_certificate_verification_) {
  11848. if (!load_certs()) {
  11849. error = Error::SSLLoadingCerts;
  11850. output_error_log(error, nullptr);
  11851. return false;
  11852. }
  11853. }
  11854. // Create TLS session (uses ctx_ which has SSL_VERIFY_NONE by default)
  11855. tls_session_t session = nullptr;
  11856. {
  11857. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11858. session = tls_create_session(ctx_, socket.sock);
  11859. }
  11860. if (!session) {
  11861. error = Error::SSLConnection;
  11862. last_backend_error_ = ERR_get_error();
  11863. return false;
  11864. }
  11865. // Use scope_exit to ensure session is freed on error paths
  11866. bool success = false;
  11867. auto session_guard = detail::scope_exit([&] {
  11868. if (!success) { tls_free_session(session); }
  11869. });
  11870. // Set SNI before handshake (only if host is not IP address)
  11871. if (!detail::is_ip_address(host_)) {
  11872. if (!tls_set_sni(session, host_.c_str())) {
  11873. error = Error::SSLConnection;
  11874. last_backend_error_ = ERR_get_error();
  11875. return false;
  11876. }
  11877. }
  11878. // Perform non-blocking TLS handshake with timeout
  11879. TlsError tls_err;
  11880. if (!tls_connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  11881. connection_timeout_usec_, &tls_err)) {
  11882. // Map TlsError to legacy ssl_error for backward compatibility
  11883. if (tls_err.code == ErrorCode::WantRead) {
  11884. last_ssl_error_ = SSL_ERROR_WANT_READ;
  11885. } else if (tls_err.code == ErrorCode::WantWrite) {
  11886. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  11887. } else {
  11888. last_ssl_error_ = SSL_ERROR_SSL;
  11889. }
  11890. error = Error::SSLConnection;
  11891. output_error_log(error, nullptr);
  11892. return false;
  11893. }
  11894. // Server certificate verification
  11895. if (server_certificate_verification_) {
  11896. // Cast to SSL* for backward compatibility with verifier callback
  11897. auto ssl = static_cast<SSL *>(session);
  11898. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  11899. if (server_certificate_verifier_) {
  11900. verification_status = server_certificate_verifier_(ssl);
  11901. }
  11902. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  11903. last_backend_error_ = ERR_get_error();
  11904. error = Error::SSLServerVerification;
  11905. output_error_log(error, nullptr);
  11906. return false;
  11907. }
  11908. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  11909. verify_result_ = tls_get_verify_result(session);
  11910. if (verify_result_ != X509_V_OK) {
  11911. last_backend_error_ = static_cast<unsigned long>(verify_result_);
  11912. error = Error::SSLServerVerification;
  11913. output_error_log(error, nullptr);
  11914. return false;
  11915. }
  11916. auto server_cert = tls_get_peer_cert(session);
  11917. if (!server_cert) {
  11918. last_backend_error_ = ERR_get_error();
  11919. error = Error::SSLServerVerification;
  11920. output_error_log(error, nullptr);
  11921. return false;
  11922. }
  11923. auto cert_guard = detail::scope_exit([&] { tls_free_cert(server_cert); });
  11924. if (server_hostname_verification_) {
  11925. // verify_host() expects X509*, so cast from tls_cert_t
  11926. if (!verify_host(static_cast<X509 *>(server_cert))) {
  11927. last_backend_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  11928. error = Error::SSLServerHostnameVerification;
  11929. output_error_log(error, nullptr);
  11930. return false;
  11931. }
  11932. }
  11933. }
  11934. }
  11935. success = true;
  11936. socket.ssl = session;
  11937. return true;
  11938. }
  11939. inline bool SSLClient::verify_host(X509 *server_cert) const {
  11940. /* Quote from RFC2818 section 3.1 "Server Identity"
  11941. If a subjectAltName extension of type dNSName is present, that MUST
  11942. be used as the identity. Otherwise, the (most specific) Common Name
  11943. field in the Subject field of the certificate MUST be used. Although
  11944. the use of the Common Name is existing practice, it is deprecated and
  11945. Certification Authorities are encouraged to use the dNSName instead.
  11946. Matching is performed using the matching rules specified by
  11947. [RFC2459]. If more than one identity of a given type is present in
  11948. the certificate (e.g., more than one dNSName name, a match in any one
  11949. of the set is considered acceptable.) Names may contain the wildcard
  11950. character * which is considered to match any single domain name
  11951. component or component fragment. E.g., *.a.com matches foo.a.com but
  11952. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  11953. In some cases, the URI is specified as an IP address rather than a
  11954. hostname. In this case, the iPAddress subjectAltName must be present
  11955. in the certificate and must exactly match the IP in the URI.
  11956. */
  11957. return verify_host_with_subject_alt_name(server_cert) ||
  11958. verify_host_with_common_name(server_cert);
  11959. }
  11960. inline bool
  11961. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  11962. auto ret = false;
  11963. auto type = GEN_DNS;
  11964. struct in6_addr addr6 = {};
  11965. struct in_addr addr = {};
  11966. size_t addr_len = 0;
  11967. #ifndef __MINGW32__
  11968. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  11969. type = GEN_IPADD;
  11970. addr_len = sizeof(struct in6_addr);
  11971. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  11972. type = GEN_IPADD;
  11973. addr_len = sizeof(struct in_addr);
  11974. }
  11975. #endif
  11976. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  11977. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  11978. if (alt_names) {
  11979. auto dsn_matched = false;
  11980. auto ip_matched = false;
  11981. auto count = sk_GENERAL_NAME_num(alt_names);
  11982. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  11983. auto val = sk_GENERAL_NAME_value(alt_names, i);
  11984. if (!val || val->type != type) { continue; }
  11985. auto name =
  11986. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  11987. if (name == nullptr) { continue; }
  11988. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  11989. switch (type) {
  11990. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  11991. case GEN_IPADD:
  11992. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  11993. ip_matched = true;
  11994. }
  11995. break;
  11996. }
  11997. }
  11998. if (dsn_matched || ip_matched) { ret = true; }
  11999. }
  12000. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  12001. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  12002. return ret;
  12003. }
  12004. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  12005. const auto subject_name = X509_get_subject_name(server_cert);
  12006. if (subject_name != nullptr) {
  12007. char name[BUFSIZ];
  12008. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  12009. name, sizeof(name));
  12010. if (name_len != -1) {
  12011. return check_host_name(name, static_cast<size_t>(name_len));
  12012. }
  12013. }
  12014. return false;
  12015. }
  12016. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  12017. /*
  12018. * Mbed TLS Backend Implementation
  12019. */
  12020. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  12021. namespace detail {
  12022. namespace crypto {
  12023. inline size_t hash_size(HashAlgorithm algo) {
  12024. switch (algo) {
  12025. case HashAlgorithm::MD5: return 16;
  12026. case HashAlgorithm::SHA1: return 20;
  12027. case HashAlgorithm::SHA256: return 32;
  12028. case HashAlgorithm::SHA384: return 48;
  12029. case HashAlgorithm::SHA512: return 64;
  12030. default: return 0;
  12031. }
  12032. }
  12033. inline bool hash_raw(HashAlgorithm algo, const void *data, size_t len,
  12034. std::vector<uint8_t> &digest) {
  12035. size_t dsize = hash_size(algo);
  12036. if (dsize == 0) { return false; }
  12037. digest.resize(dsize);
  12038. int ret = 0;
  12039. switch (algo) {
  12040. case HashAlgorithm::MD5:
  12041. #if MBEDTLS_VERSION_MAJOR >= 3
  12042. ret = mbedtls_md5(static_cast<const unsigned char *>(data), len,
  12043. digest.data());
  12044. #else
  12045. ret = mbedtls_md5_ret(static_cast<const unsigned char *>(data), len,
  12046. digest.data());
  12047. #endif
  12048. break;
  12049. case HashAlgorithm::SHA1:
  12050. #if MBEDTLS_VERSION_MAJOR >= 3
  12051. ret = mbedtls_sha1(static_cast<const unsigned char *>(data), len,
  12052. digest.data());
  12053. #else
  12054. ret = mbedtls_sha1_ret(static_cast<const unsigned char *>(data), len,
  12055. digest.data());
  12056. #endif
  12057. break;
  12058. case HashAlgorithm::SHA256:
  12059. #if MBEDTLS_VERSION_MAJOR >= 3
  12060. ret = mbedtls_sha256(static_cast<const unsigned char *>(data), len,
  12061. digest.data(), 0);
  12062. #else
  12063. ret = mbedtls_sha256_ret(static_cast<const unsigned char *>(data), len,
  12064. digest.data(), 0);
  12065. #endif
  12066. break;
  12067. case HashAlgorithm::SHA384:
  12068. #if MBEDTLS_VERSION_MAJOR >= 3
  12069. ret = mbedtls_sha512(static_cast<const unsigned char *>(data), len,
  12070. digest.data(), 1); // is384 = 1
  12071. #else
  12072. ret = mbedtls_sha512_ret(static_cast<const unsigned char *>(data), len,
  12073. digest.data(), 1); // is384 = 1
  12074. #endif
  12075. break;
  12076. case HashAlgorithm::SHA512:
  12077. #if MBEDTLS_VERSION_MAJOR >= 3
  12078. ret = mbedtls_sha512(static_cast<const unsigned char *>(data), len,
  12079. digest.data(), 0);
  12080. #else
  12081. ret = mbedtls_sha512_ret(static_cast<const unsigned char *>(data), len,
  12082. digest.data(), 0);
  12083. #endif
  12084. break;
  12085. }
  12086. return ret == 0;
  12087. }
  12088. inline std::string hash(HashAlgorithm algo, const void *data, size_t len) {
  12089. std::vector<uint8_t> digest;
  12090. if (!hash_raw(algo, data, len, digest)) { return ""; }
  12091. std::stringstream ss;
  12092. for (auto byte : digest) {
  12093. ss << std::hex << std::setw(2) << std::setfill('0')
  12094. << static_cast<unsigned int>(byte);
  12095. }
  12096. return ss.str();
  12097. }
  12098. inline std::string hash(HashAlgorithm algo, const std::string &data) {
  12099. return hash(algo, data.c_str(), data.size());
  12100. }
  12101. } // namespace crypto
  12102. /*
  12103. * Mbed TLS TLS Abstraction Layer Implementation
  12104. */
  12105. namespace tls {
  12106. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  12107. // cert/key)
  12108. struct MbedTlsContext {
  12109. mbedtls_ssl_config conf;
  12110. mbedtls_entropy_context entropy;
  12111. mbedtls_ctr_drbg_context ctr_drbg;
  12112. mbedtls_x509_crt ca_chain;
  12113. mbedtls_x509_crt own_cert;
  12114. mbedtls_pk_context own_key;
  12115. bool is_server = false;
  12116. bool verify_client = false;
  12117. bool has_verify_callback = false;
  12118. MbedTlsContext() {
  12119. mbedtls_ssl_config_init(&conf);
  12120. mbedtls_entropy_init(&entropy);
  12121. mbedtls_ctr_drbg_init(&ctr_drbg);
  12122. mbedtls_x509_crt_init(&ca_chain);
  12123. mbedtls_x509_crt_init(&own_cert);
  12124. mbedtls_pk_init(&own_key);
  12125. }
  12126. ~MbedTlsContext() {
  12127. mbedtls_pk_free(&own_key);
  12128. mbedtls_x509_crt_free(&own_cert);
  12129. mbedtls_x509_crt_free(&ca_chain);
  12130. mbedtls_ctr_drbg_free(&ctr_drbg);
  12131. mbedtls_entropy_free(&entropy);
  12132. mbedtls_ssl_config_free(&conf);
  12133. }
  12134. // Non-copyable
  12135. MbedTlsContext(const MbedTlsContext &) = delete;
  12136. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  12137. };
  12138. // Mbed TLS session wrapper
  12139. struct MbedTlsSession {
  12140. mbedtls_ssl_context ssl;
  12141. socket_t sock = INVALID_SOCKET;
  12142. std::string hostname; // For client: set via tls_set_sni
  12143. std::string sni_hostname; // For server: received from client via SNI callback
  12144. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  12145. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  12146. // Non-copyable
  12147. MbedTlsSession(const MbedTlsSession &) = delete;
  12148. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  12149. };
  12150. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  12151. // queue)
  12152. inline int &mbedtls_last_error() {
  12153. static thread_local int err = 0;
  12154. return err;
  12155. }
  12156. // Helper to map Mbed TLS error to ErrorCode
  12157. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  12158. if (ret == 0) { return ErrorCode::Success; }
  12159. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  12160. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  12161. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  12162. return ErrorCode::PeerClosed;
  12163. }
  12164. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  12165. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  12166. out_errno = errno;
  12167. return ErrorCode::SyscallError;
  12168. }
  12169. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  12170. return ErrorCode::CertVerifyFailed;
  12171. }
  12172. return ErrorCode::Fatal;
  12173. }
  12174. inline bool tls_global_init() {
  12175. // Mbed TLS doesn't require global initialization
  12176. return true;
  12177. }
  12178. inline void tls_global_cleanup() {
  12179. // Mbed TLS doesn't require global cleanup
  12180. }
  12181. // BIO-like send callback for Mbed TLS
  12182. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  12183. size_t len) {
  12184. auto sock = *static_cast<socket_t *>(ctx);
  12185. #ifdef _WIN32
  12186. auto ret =
  12187. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  12188. if (ret == SOCKET_ERROR) {
  12189. int err = WSAGetLastError();
  12190. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  12191. return MBEDTLS_ERR_NET_SEND_FAILED;
  12192. }
  12193. #else
  12194. auto ret = send(sock, buf, len, 0);
  12195. if (ret < 0) {
  12196. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  12197. return MBEDTLS_ERR_SSL_WANT_WRITE;
  12198. }
  12199. return MBEDTLS_ERR_NET_SEND_FAILED;
  12200. }
  12201. #endif
  12202. return static_cast<int>(ret);
  12203. }
  12204. // BIO-like recv callback for Mbed TLS
  12205. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  12206. auto sock = *static_cast<socket_t *>(ctx);
  12207. #ifdef _WIN32
  12208. auto ret =
  12209. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  12210. if (ret == SOCKET_ERROR) {
  12211. int err = WSAGetLastError();
  12212. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  12213. return MBEDTLS_ERR_NET_RECV_FAILED;
  12214. }
  12215. #else
  12216. auto ret = recv(sock, buf, len, 0);
  12217. if (ret < 0) {
  12218. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  12219. return MBEDTLS_ERR_SSL_WANT_READ;
  12220. }
  12221. return MBEDTLS_ERR_NET_RECV_FAILED;
  12222. }
  12223. #endif
  12224. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  12225. return static_cast<int>(ret);
  12226. }
  12227. inline tls_ctx_t tls_create_client_context() {
  12228. auto ctx = new (std::nothrow) MbedTlsContext();
  12229. if (!ctx) { return nullptr; }
  12230. ctx->is_server = false;
  12231. // Seed the random number generator
  12232. const char *pers = "httplib_client";
  12233. int ret = mbedtls_ctr_drbg_seed(
  12234. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  12235. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  12236. if (ret != 0) {
  12237. mbedtls_last_error() = ret;
  12238. delete ctx;
  12239. return nullptr;
  12240. }
  12241. // Set up SSL config for client
  12242. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  12243. MBEDTLS_SSL_TRANSPORT_STREAM,
  12244. MBEDTLS_SSL_PRESET_DEFAULT);
  12245. if (ret != 0) {
  12246. mbedtls_last_error() = ret;
  12247. delete ctx;
  12248. return nullptr;
  12249. }
  12250. // Set random number generator
  12251. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  12252. // Default: verify peer certificate
  12253. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  12254. // Set minimum TLS version to 1.2
  12255. #if MBEDTLS_VERSION_MAJOR >= 3
  12256. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  12257. #else
  12258. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  12259. MBEDTLS_SSL_MINOR_VERSION_3);
  12260. #endif
  12261. return static_cast<tls_ctx_t>(ctx);
  12262. }
  12263. // Forward declaration for SNI callback (defined later)
  12264. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  12265. const unsigned char *name, size_t name_len);
  12266. inline tls_ctx_t tls_create_server_context() {
  12267. auto ctx = new (std::nothrow) MbedTlsContext();
  12268. if (!ctx) { return nullptr; }
  12269. ctx->is_server = true;
  12270. // Seed the random number generator
  12271. const char *pers = "httplib_server";
  12272. int ret = mbedtls_ctr_drbg_seed(
  12273. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  12274. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  12275. if (ret != 0) {
  12276. mbedtls_last_error() = ret;
  12277. delete ctx;
  12278. return nullptr;
  12279. }
  12280. // Set up SSL config for server
  12281. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  12282. MBEDTLS_SSL_TRANSPORT_STREAM,
  12283. MBEDTLS_SSL_PRESET_DEFAULT);
  12284. if (ret != 0) {
  12285. mbedtls_last_error() = ret;
  12286. delete ctx;
  12287. return nullptr;
  12288. }
  12289. // Set random number generator
  12290. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  12291. // Default: don't verify client
  12292. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  12293. // Set minimum TLS version to 1.2
  12294. #if MBEDTLS_VERSION_MAJOR >= 3
  12295. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  12296. #else
  12297. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  12298. MBEDTLS_SSL_MINOR_VERSION_3);
  12299. #endif
  12300. // Set SNI callback to capture client's SNI hostname
  12301. mbedtls_ssl_conf_sni(&ctx->conf, mbedtls_sni_callback, nullptr);
  12302. return static_cast<tls_ctx_t>(ctx);
  12303. }
  12304. inline void tls_free_context(tls_ctx_t ctx) {
  12305. if (ctx) { delete static_cast<MbedTlsContext *>(ctx); }
  12306. }
  12307. inline bool tls_set_min_version(tls_ctx_t ctx, int version) {
  12308. if (!ctx) { return false; }
  12309. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12310. // Map OpenSSL-style version constants to Mbed TLS
  12311. // TLS1_2_VERSION = 0x0303, TLS1_3_VERSION = 0x0304
  12312. #if MBEDTLS_VERSION_MAJOR >= 3
  12313. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  12314. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  12315. if (version >= 0x0304) {
  12316. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  12317. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  12318. #endif
  12319. }
  12320. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  12321. #else
  12322. // Mbed TLS 2.x uses major/minor version numbers
  12323. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  12324. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  12325. if (version >= 0x0304) {
  12326. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  12327. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  12328. #else
  12329. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  12330. #endif
  12331. }
  12332. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  12333. #endif
  12334. return true;
  12335. }
  12336. inline bool tls_load_ca_pem(tls_ctx_t ctx, const char *pem, size_t len) {
  12337. if (!ctx || !pem) { return false; }
  12338. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12339. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  12340. // Add null terminator if not present
  12341. std::string pem_str(pem, len);
  12342. int ret = mbedtls_x509_crt_parse(
  12343. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  12344. pem_str.size() + 1);
  12345. if (ret != 0) {
  12346. mbedtls_last_error() = ret;
  12347. return false;
  12348. }
  12349. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  12350. return true;
  12351. }
  12352. inline bool tls_load_ca_file(tls_ctx_t ctx, const char *file_path) {
  12353. if (!ctx || !file_path) { return false; }
  12354. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12355. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  12356. if (ret != 0) {
  12357. mbedtls_last_error() = ret;
  12358. return false;
  12359. }
  12360. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  12361. return true;
  12362. }
  12363. inline bool tls_load_ca_dir(tls_ctx_t ctx, const char *dir_path) {
  12364. if (!ctx || !dir_path) { return false; }
  12365. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12366. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  12367. if (ret < 0) { // Returns number of certs on success, negative on error
  12368. mbedtls_last_error() = ret;
  12369. return false;
  12370. }
  12371. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  12372. return true;
  12373. }
  12374. inline bool tls_load_system_certs(tls_ctx_t ctx) {
  12375. if (!ctx) { return false; }
  12376. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12377. bool loaded = false;
  12378. #ifdef _WIN32
  12379. // Load from Windows certificate store
  12380. HCERTSTORE hStore = CertOpenSystemStoreW(0, L"ROOT");
  12381. if (hStore) {
  12382. PCCERT_CONTEXT pContext = nullptr;
  12383. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  12384. nullptr) {
  12385. int ret = mbedtls_x509_crt_parse_der(
  12386. &mctx->ca_chain, pContext->pbCertEncoded, pContext->cbCertEncoded);
  12387. if (ret == 0) { loaded = true; }
  12388. }
  12389. CertCloseStore(hStore, 0);
  12390. }
  12391. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  12392. // Load from macOS Keychain
  12393. CFArrayRef certs = nullptr;
  12394. OSStatus status = SecTrustCopyAnchorCertificates(&certs);
  12395. if (status == errSecSuccess && certs) {
  12396. CFIndex count = CFArrayGetCount(certs);
  12397. for (CFIndex i = 0; i < count; i++) {
  12398. SecCertificateRef cert =
  12399. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  12400. CFDataRef data = SecCertificateCopyData(cert);
  12401. if (data) {
  12402. int ret = mbedtls_x509_crt_parse_der(
  12403. &mctx->ca_chain, CFDataGetBytePtr(data),
  12404. static_cast<size_t>(CFDataGetLength(data)));
  12405. if (ret == 0) { loaded = true; }
  12406. CFRelease(data);
  12407. }
  12408. }
  12409. CFRelease(certs);
  12410. }
  12411. #else
  12412. // Try common CA certificate locations on Linux/Unix
  12413. static const char *ca_paths[] = {
  12414. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  12415. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  12416. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  12417. "/etc/pki/tls/cacert.pem", // OpenELEC
  12418. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  12419. nullptr};
  12420. for (const char **path = ca_paths; *path; ++path) {
  12421. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path);
  12422. if (ret >= 0) {
  12423. loaded = true;
  12424. break;
  12425. }
  12426. }
  12427. // Also try the CA directory
  12428. if (!loaded) {
  12429. static const char *ca_dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  12430. "/etc/pki/tls/certs", // RHEL/CentOS
  12431. "/usr/share/ca-certificates", nullptr};
  12432. for (const char **dir = ca_dirs; *dir; ++dir) {
  12433. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir);
  12434. if (ret >= 0) {
  12435. loaded = true;
  12436. break;
  12437. }
  12438. }
  12439. }
  12440. #endif
  12441. if (loaded) {
  12442. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  12443. }
  12444. return loaded;
  12445. }
  12446. inline bool tls_set_client_cert_pem(tls_ctx_t ctx, const char *cert,
  12447. const char *key, const char *password) {
  12448. if (!ctx || !cert || !key) { return false; }
  12449. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12450. // Parse certificate
  12451. std::string cert_str(cert);
  12452. int ret = mbedtls_x509_crt_parse(
  12453. &mctx->own_cert,
  12454. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  12455. cert_str.size() + 1);
  12456. if (ret != 0) {
  12457. mbedtls_last_error() = ret;
  12458. return false;
  12459. }
  12460. // Parse private key
  12461. std::string key_str(key);
  12462. const unsigned char *pwd =
  12463. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  12464. size_t pwd_len = password ? strlen(password) : 0;
  12465. #if MBEDTLS_VERSION_MAJOR >= 3
  12466. ret = mbedtls_pk_parse_key(
  12467. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  12468. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  12469. &mctx->ctr_drbg);
  12470. #else
  12471. ret = mbedtls_pk_parse_key(
  12472. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  12473. key_str.size() + 1, pwd, pwd_len);
  12474. #endif
  12475. if (ret != 0) {
  12476. mbedtls_last_error() = ret;
  12477. return false;
  12478. }
  12479. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  12480. if (ret != 0) {
  12481. mbedtls_last_error() = ret;
  12482. return false;
  12483. }
  12484. return true;
  12485. }
  12486. inline bool tls_set_client_cert_file(tls_ctx_t ctx, const char *cert_path,
  12487. const char *key_path,
  12488. const char *password) {
  12489. if (!ctx || !cert_path || !key_path) { return false; }
  12490. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12491. // Parse certificate file
  12492. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  12493. if (ret != 0) {
  12494. mbedtls_last_error() = ret;
  12495. return false;
  12496. }
  12497. // Parse private key file
  12498. #if MBEDTLS_VERSION_MAJOR >= 3
  12499. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  12500. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  12501. #else
  12502. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  12503. #endif
  12504. if (ret != 0) {
  12505. mbedtls_last_error() = ret;
  12506. return false;
  12507. }
  12508. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  12509. if (ret != 0) {
  12510. mbedtls_last_error() = ret;
  12511. return false;
  12512. }
  12513. return true;
  12514. }
  12515. inline bool tls_set_server_cert_pem(tls_ctx_t ctx, const char *cert,
  12516. const char *key, const char *password) {
  12517. // Same as client cert for Mbed TLS
  12518. return tls_set_client_cert_pem(ctx, cert, key, password);
  12519. }
  12520. inline bool tls_set_server_cert_file(tls_ctx_t ctx, const char *cert_path,
  12521. const char *key_path,
  12522. const char *password) {
  12523. // Same as client cert for Mbed TLS
  12524. return tls_set_client_cert_file(ctx, cert_path, key_path, password);
  12525. }
  12526. inline bool tls_set_client_ca_file(tls_ctx_t ctx, const char *ca_file,
  12527. const char *ca_dir) {
  12528. if (!ctx) { return false; }
  12529. bool success = true;
  12530. if (ca_file && *ca_file) {
  12531. if (!tls_load_ca_file(ctx, ca_file)) { success = false; }
  12532. }
  12533. if (ca_dir && *ca_dir) {
  12534. if (!tls_load_ca_dir(ctx, ca_dir)) { success = false; }
  12535. }
  12536. return success;
  12537. }
  12538. inline void tls_set_verify_client(tls_ctx_t ctx, bool require) {
  12539. if (!ctx) { return; }
  12540. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12541. mctx->verify_client = require;
  12542. if (require) {
  12543. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  12544. } else {
  12545. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  12546. // is called (matching OpenSSL behavior). Otherwise use NONE.
  12547. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  12548. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  12549. : MBEDTLS_SSL_VERIFY_NONE);
  12550. }
  12551. }
  12552. // Thread-local storage for SNI captured during handshake
  12553. // This is needed because the SNI callback doesn't have a way to pass
  12554. // session-specific data before the session is fully set up
  12555. inline std::string &mbedtls_pending_sni() {
  12556. static thread_local std::string sni;
  12557. return sni;
  12558. }
  12559. // SNI callback for Mbed TLS server to capture client's SNI hostname
  12560. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  12561. const unsigned char *name, size_t name_len) {
  12562. (void)p_ctx;
  12563. (void)ssl;
  12564. // Store SNI name in thread-local storage
  12565. // It will be retrieved and stored in the session after handshake
  12566. if (name && name_len > 0) {
  12567. mbedtls_pending_sni().assign(reinterpret_cast<const char *>(name),
  12568. name_len);
  12569. } else {
  12570. mbedtls_pending_sni().clear();
  12571. }
  12572. return 0; // Accept any SNI
  12573. }
  12574. inline tls_session_t tls_create_session(tls_ctx_t ctx, socket_t sock) {
  12575. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  12576. auto mctx = static_cast<MbedTlsContext *>(ctx);
  12577. auto session = new (std::nothrow) MbedTlsSession();
  12578. if (!session) { return nullptr; }
  12579. session->sock = sock;
  12580. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  12581. if (ret != 0) {
  12582. mbedtls_last_error() = ret;
  12583. delete session;
  12584. return nullptr;
  12585. }
  12586. // Set BIO callbacks
  12587. mbedtls_ssl_set_bio(&session->ssl, &session->sock, mbedtls_net_send_cb,
  12588. mbedtls_net_recv_cb, nullptr);
  12589. return static_cast<tls_session_t>(session);
  12590. }
  12591. inline void tls_free_session(tls_session_t session) {
  12592. if (session) { delete static_cast<MbedTlsSession *>(session); }
  12593. }
  12594. inline bool tls_set_sni(tls_session_t session, const char *hostname) {
  12595. if (!session || !hostname) { return false; }
  12596. auto msession = static_cast<MbedTlsSession *>(session);
  12597. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  12598. if (ret != 0) {
  12599. mbedtls_last_error() = ret;
  12600. return false;
  12601. }
  12602. msession->hostname = hostname;
  12603. return true;
  12604. }
  12605. inline bool tls_set_hostname(tls_session_t session, const char *hostname) {
  12606. // In Mbed TLS, set_hostname also sets up hostname verification
  12607. return tls_set_sni(session, hostname);
  12608. }
  12609. inline TlsError tls_connect(tls_session_t session) {
  12610. TlsError err;
  12611. if (!session) {
  12612. err.code = ErrorCode::Fatal;
  12613. return err;
  12614. }
  12615. auto msession = static_cast<MbedTlsSession *>(session);
  12616. int ret = mbedtls_ssl_handshake(&msession->ssl);
  12617. if (ret == 0) {
  12618. err.code = ErrorCode::Success;
  12619. } else {
  12620. err.code = map_mbedtls_error(ret, err.sys_errno);
  12621. err.backend_code = static_cast<uint64_t>(-ret);
  12622. mbedtls_last_error() = ret;
  12623. }
  12624. return err;
  12625. }
  12626. inline TlsError tls_accept(tls_session_t session) {
  12627. // Same as connect for Mbed TLS - handshake works for both client and server
  12628. auto result = tls_connect(session);
  12629. // After successful handshake, capture SNI from thread-local storage
  12630. if (result.code == ErrorCode::Success && session) {
  12631. auto msession = static_cast<MbedTlsSession *>(session);
  12632. msession->sni_hostname = std::move(mbedtls_pending_sni());
  12633. mbedtls_pending_sni().clear();
  12634. }
  12635. return result;
  12636. }
  12637. inline bool tls_connect_nonblocking(tls_session_t session, socket_t sock,
  12638. time_t timeout_sec, time_t timeout_usec,
  12639. TlsError *err) {
  12640. if (!session) {
  12641. if (err) { err->code = ErrorCode::Fatal; }
  12642. return false;
  12643. }
  12644. auto msession = static_cast<MbedTlsSession *>(session);
  12645. // Set socket to non-blocking mode
  12646. set_nonblocking(sock, true);
  12647. auto cleanup = scope_exit([&]() { set_nonblocking(sock, false); });
  12648. int ret;
  12649. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  12650. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  12651. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  12652. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  12653. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  12654. }
  12655. // Error or timeout
  12656. if (err) {
  12657. err->code = map_mbedtls_error(ret, err->sys_errno);
  12658. err->backend_code = static_cast<uint64_t>(-ret);
  12659. }
  12660. mbedtls_last_error() = ret;
  12661. return false;
  12662. }
  12663. if (err) { err->code = ErrorCode::Success; }
  12664. return true;
  12665. }
  12666. inline bool tls_accept_nonblocking(tls_session_t session, socket_t sock,
  12667. time_t timeout_sec, time_t timeout_usec,
  12668. TlsError *err) {
  12669. // Same implementation as connect for Mbed TLS
  12670. bool result =
  12671. tls_connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  12672. // After successful handshake, capture SNI from thread-local storage
  12673. if (result && session) {
  12674. auto msession = static_cast<MbedTlsSession *>(session);
  12675. msession->sni_hostname = std::move(mbedtls_pending_sni());
  12676. mbedtls_pending_sni().clear();
  12677. }
  12678. return result;
  12679. }
  12680. inline ssize_t tls_read(tls_session_t session, void *buf, size_t len,
  12681. TlsError &err) {
  12682. if (!session || !buf) {
  12683. err.code = ErrorCode::Fatal;
  12684. return -1;
  12685. }
  12686. auto msession = static_cast<MbedTlsSession *>(session);
  12687. int ret =
  12688. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  12689. if (ret > 0) {
  12690. err.code = ErrorCode::Success;
  12691. return static_cast<ssize_t>(ret);
  12692. }
  12693. if (ret == 0) {
  12694. err.code = ErrorCode::PeerClosed;
  12695. return 0;
  12696. }
  12697. err.code = map_mbedtls_error(ret, err.sys_errno);
  12698. err.backend_code = static_cast<uint64_t>(-ret);
  12699. mbedtls_last_error() = ret;
  12700. return -1;
  12701. }
  12702. inline ssize_t tls_write(tls_session_t session, const void *buf, size_t len,
  12703. TlsError &err) {
  12704. if (!session || !buf) {
  12705. err.code = ErrorCode::Fatal;
  12706. return -1;
  12707. }
  12708. auto msession = static_cast<MbedTlsSession *>(session);
  12709. int ret = mbedtls_ssl_write(&msession->ssl,
  12710. static_cast<const unsigned char *>(buf), len);
  12711. if (ret > 0) {
  12712. err.code = ErrorCode::Success;
  12713. return static_cast<ssize_t>(ret);
  12714. }
  12715. if (ret == 0) {
  12716. err.code = ErrorCode::PeerClosed;
  12717. return 0;
  12718. }
  12719. err.code = map_mbedtls_error(ret, err.sys_errno);
  12720. err.backend_code = static_cast<uint64_t>(-ret);
  12721. mbedtls_last_error() = ret;
  12722. return -1;
  12723. }
  12724. inline int tls_pending(tls_session_t session) {
  12725. if (!session) { return 0; }
  12726. auto msession = static_cast<MbedTlsSession *>(session);
  12727. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  12728. }
  12729. inline void tls_shutdown(tls_session_t session, bool graceful) {
  12730. if (!session) { return; }
  12731. auto msession = static_cast<MbedTlsSession *>(session);
  12732. if (graceful) {
  12733. // Try to send close_notify, but don't block forever
  12734. int ret;
  12735. int attempts = 0;
  12736. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  12737. attempts < 3) {
  12738. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  12739. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  12740. break;
  12741. }
  12742. attempts++;
  12743. }
  12744. }
  12745. }
  12746. inline bool tls_is_peer_closed(tls_session_t session, socket_t sock) {
  12747. if (!session || sock == INVALID_SOCKET) { return true; }
  12748. auto msession = static_cast<MbedTlsSession *>(session);
  12749. // Check if there's already decrypted data available in the TLS buffer
  12750. // If so, the connection is definitely alive
  12751. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  12752. // Set socket to non-blocking to avoid blocking on read
  12753. set_nonblocking(sock, true);
  12754. auto cleanup = scope_exit([&]() { set_nonblocking(sock, false); });
  12755. // Try a 1-byte read to check connection status
  12756. // Note: This will consume the byte if data is available, but for the
  12757. // purpose of checking if peer is closed, this should be acceptable
  12758. // since we're only called when we expect the connection might be closing
  12759. unsigned char buf;
  12760. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  12761. // If we got data or WANT_READ (would block), connection is alive
  12762. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  12763. // If we get a peer close notify or a connection reset, the peer is closed
  12764. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  12765. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  12766. }
  12767. inline tls_cert_t tls_get_peer_cert(tls_session_t session) {
  12768. if (!session) { return nullptr; }
  12769. auto msession = static_cast<MbedTlsSession *>(session);
  12770. // Mbed TLS returns a pointer to the peer cert chain, no need to free
  12771. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  12772. return const_cast<mbedtls_x509_crt *>(cert);
  12773. }
  12774. inline void tls_free_cert(tls_cert_t cert) {
  12775. // Mbed TLS: peer certificate is owned by the SSL context, don't free
  12776. (void)cert;
  12777. }
  12778. namespace {
  12779. // Helper function to match hostname with pattern (supports wildcards)
  12780. inline bool match_hostname(const std::string &pattern,
  12781. const std::string &hostname) {
  12782. if (pattern == hostname) { return true; }
  12783. // Wildcard matching: *.example.com matches foo.example.com
  12784. if (pattern.size() > 2 && pattern[0] == '*' && pattern[1] == '.') {
  12785. std::string suffix = pattern.substr(1); // .example.com
  12786. size_t dot_pos = hostname.find('.');
  12787. if (dot_pos != std::string::npos) {
  12788. std::string host_suffix = hostname.substr(dot_pos);
  12789. if (host_suffix == suffix) { return true; }
  12790. }
  12791. }
  12792. return false;
  12793. }
  12794. } // namespace
  12795. // Check if a string is an IPv4 address
  12796. inline bool is_ipv4_address(const std::string &str) {
  12797. int dots = 0;
  12798. for (char c : str) {
  12799. if (c == '.') {
  12800. dots++;
  12801. } else if (!isdigit(static_cast<unsigned char>(c))) {
  12802. return false;
  12803. }
  12804. }
  12805. return dots == 3;
  12806. }
  12807. // Parse IPv4 address string to bytes
  12808. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  12809. int parts[4];
  12810. if (sscanf(str.c_str(), "%d.%d.%d.%d", &parts[0], &parts[1], &parts[2],
  12811. &parts[3]) != 4) {
  12812. return false;
  12813. }
  12814. for (int i = 0; i < 4; i++) {
  12815. if (parts[i] < 0 || parts[i] > 255) return false;
  12816. out[i] = static_cast<unsigned char>(parts[i]);
  12817. }
  12818. return true;
  12819. }
  12820. inline bool tls_verify_hostname(tls_cert_t cert, const char *hostname) {
  12821. if (!cert || !hostname) { return false; }
  12822. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  12823. std::string host_str(hostname);
  12824. // Check if hostname is an IP address
  12825. bool is_ip = is_ipv4_address(host_str);
  12826. unsigned char ip_bytes[4];
  12827. if (is_ip) { parse_ipv4(host_str, ip_bytes); }
  12828. // Check Subject Alternative Names (SAN)
  12829. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  12830. // - DNS names: raw string bytes
  12831. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  12832. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  12833. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  12834. const unsigned char *p = san->buf.p;
  12835. size_t len = san->buf.len;
  12836. if (is_ip) {
  12837. // Check if this SAN is an IPv4 address (4 bytes)
  12838. if (len == 4 && memcmp(p, ip_bytes, 4) == 0) { return true; }
  12839. // Check if this SAN is an IPv6 address (16 bytes) - skip for now
  12840. } else {
  12841. // Check if this SAN is a DNS name (printable ASCII string)
  12842. bool is_dns = len > 0;
  12843. for (size_t i = 0; i < len && is_dns; i++) {
  12844. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  12845. }
  12846. if (is_dns) {
  12847. std::string san_name(reinterpret_cast<const char *>(p), len);
  12848. if (match_hostname(san_name, host_str)) { return true; }
  12849. }
  12850. }
  12851. san = san->next;
  12852. }
  12853. // Fallback: Check Common Name (CN) in subject
  12854. char cn[256];
  12855. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  12856. if (ret > 0) {
  12857. std::string cn_str(cn);
  12858. // Look for "CN=" in the DN string
  12859. size_t cn_pos = cn_str.find("CN=");
  12860. if (cn_pos != std::string::npos) {
  12861. size_t start = cn_pos + 3;
  12862. size_t end = cn_str.find(',', start);
  12863. std::string cn_value =
  12864. cn_str.substr(start, end == std::string::npos ? end : end - start);
  12865. if (match_hostname(cn_value, host_str)) { return true; }
  12866. }
  12867. }
  12868. return false;
  12869. }
  12870. inline long tls_get_verify_result(tls_session_t session) {
  12871. if (!session) { return -1; }
  12872. auto msession = static_cast<MbedTlsSession *>(session);
  12873. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  12874. // Return 0 (X509_V_OK equivalent) if verification passed
  12875. return flags == 0 ? 0 : static_cast<long>(flags);
  12876. }
  12877. inline std::string tls_get_cert_subject_cn(tls_cert_t cert) {
  12878. if (!cert) return "";
  12879. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12880. // Find the CN in the subject
  12881. const mbedtls_x509_name *name = &x509->subject;
  12882. while (name != nullptr) {
  12883. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  12884. return std::string(reinterpret_cast<const char *>(name->val.p),
  12885. name->val.len);
  12886. }
  12887. name = name->next;
  12888. }
  12889. return "";
  12890. }
  12891. inline std::string tls_get_cert_issuer_name(tls_cert_t cert) {
  12892. if (!cert) return "";
  12893. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12894. // Build a human-readable issuer name string
  12895. char buf[512];
  12896. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  12897. if (ret < 0) return "";
  12898. return std::string(buf);
  12899. }
  12900. inline bool tls_get_cert_sans(tls_cert_t cert, std::vector<TlsSanEntry> &sans) {
  12901. sans.clear();
  12902. if (!cert) return false;
  12903. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12904. // Parse the Subject Alternative Name extension
  12905. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  12906. while (cur != nullptr) {
  12907. if (cur->buf.len > 0) {
  12908. // Mbed TLS stores SAN as ASN.1 sequences
  12909. // The tag byte indicates the type
  12910. const unsigned char *p = cur->buf.p;
  12911. size_t len = cur->buf.len;
  12912. // First byte is the tag
  12913. unsigned char tag = *p;
  12914. p++;
  12915. len--;
  12916. // Parse length (simple single-byte length assumed)
  12917. if (len > 0 && *p < 0x80) {
  12918. size_t value_len = *p;
  12919. p++;
  12920. len--;
  12921. if (value_len <= len) {
  12922. TlsSanEntry entry;
  12923. // ASN.1 context tags for GeneralName
  12924. switch (tag & 0x1F) {
  12925. case 2: // dNSName
  12926. entry.type = SanType::DNS;
  12927. entry.value =
  12928. std::string(reinterpret_cast<const char *>(p), value_len);
  12929. break;
  12930. case 7: // iPAddress
  12931. entry.type = SanType::IP;
  12932. if (value_len == 4) {
  12933. // IPv4
  12934. char buf[16];
  12935. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  12936. entry.value = buf;
  12937. } else if (value_len == 16) {
  12938. // IPv6
  12939. char buf[64];
  12940. snprintf(buf, sizeof(buf),
  12941. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  12942. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  12943. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  12944. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  12945. entry.value = buf;
  12946. }
  12947. break;
  12948. case 1: // rfc822Name (email)
  12949. entry.type = SanType::EMAIL;
  12950. entry.value =
  12951. std::string(reinterpret_cast<const char *>(p), value_len);
  12952. break;
  12953. case 6: // uniformResourceIdentifier
  12954. entry.type = SanType::URI;
  12955. entry.value =
  12956. std::string(reinterpret_cast<const char *>(p), value_len);
  12957. break;
  12958. default: entry.type = SanType::OTHER; break;
  12959. }
  12960. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  12961. }
  12962. }
  12963. }
  12964. cur = cur->next;
  12965. }
  12966. return true;
  12967. }
  12968. inline bool tls_get_cert_validity(tls_cert_t cert, time_t &not_before,
  12969. time_t &not_after) {
  12970. if (!cert) return false;
  12971. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12972. // Convert mbedtls_x509_time to time_t
  12973. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  12974. struct tm tm_time = {};
  12975. tm_time.tm_year = t.year - 1900;
  12976. tm_time.tm_mon = t.mon - 1;
  12977. tm_time.tm_mday = t.day;
  12978. tm_time.tm_hour = t.hour;
  12979. tm_time.tm_min = t.min;
  12980. tm_time.tm_sec = t.sec;
  12981. #ifdef _WIN32
  12982. return _mkgmtime(&tm_time);
  12983. #else
  12984. return timegm(&tm_time);
  12985. #endif
  12986. };
  12987. not_before = to_time_t(x509->valid_from);
  12988. not_after = to_time_t(x509->valid_to);
  12989. return true;
  12990. }
  12991. inline std::string tls_get_cert_serial(tls_cert_t cert) {
  12992. if (!cert) return "";
  12993. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12994. // Convert serial number to hex string
  12995. std::string result;
  12996. result.reserve(x509->serial.len * 2);
  12997. for (size_t i = 0; i < x509->serial.len; i++) {
  12998. char hex[3];
  12999. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  13000. result += hex;
  13001. }
  13002. return result;
  13003. }
  13004. inline const char *tls_get_sni(tls_session_t session) {
  13005. if (!session) return nullptr;
  13006. auto msession = static_cast<MbedTlsSession *>(session);
  13007. // For server: return SNI received from client during handshake
  13008. if (!msession->sni_hostname.empty()) {
  13009. return msession->sni_hostname.c_str();
  13010. }
  13011. // For client: return the hostname set via tls_set_sni
  13012. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  13013. return nullptr;
  13014. }
  13015. inline uint64_t tls_peek_error() {
  13016. // Mbed TLS doesn't have an error queue, return the last error
  13017. return static_cast<uint64_t>(-mbedtls_last_error());
  13018. }
  13019. inline uint64_t tls_get_error() {
  13020. // Mbed TLS doesn't have an error queue, return and clear the last error
  13021. uint64_t err = static_cast<uint64_t>(-mbedtls_last_error());
  13022. mbedtls_last_error() = 0;
  13023. return err;
  13024. }
  13025. inline std::string tls_error_string(uint64_t code) {
  13026. char buf[256];
  13027. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  13028. return std::string(buf);
  13029. }
  13030. inline tls_ca_store_t tls_create_ca_store(const char *pem, size_t len) {
  13031. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  13032. if (!ca_chain) { return nullptr; }
  13033. mbedtls_x509_crt_init(ca_chain);
  13034. // mbedtls_x509_crt_parse expects null-terminated PEM
  13035. int ret = mbedtls_x509_crt_parse(ca_chain,
  13036. reinterpret_cast<const unsigned char *>(pem),
  13037. len + 1); // +1 for null terminator
  13038. if (ret != 0) {
  13039. // Try without +1 in case PEM is already null-terminated
  13040. ret = mbedtls_x509_crt_parse(
  13041. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  13042. if (ret != 0) {
  13043. mbedtls_x509_crt_free(ca_chain);
  13044. delete ca_chain;
  13045. return nullptr;
  13046. }
  13047. }
  13048. return static_cast<tls_ca_store_t>(ca_chain);
  13049. }
  13050. inline void tls_free_ca_store(tls_ca_store_t store) {
  13051. if (store) {
  13052. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  13053. mbedtls_x509_crt_free(ca_chain);
  13054. delete ca_chain;
  13055. }
  13056. }
  13057. inline bool tls_set_ca_store(tls_ctx_t ctx, tls_ca_store_t store) {
  13058. if (!ctx || !store) { return false; }
  13059. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  13060. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  13061. // Free existing CA chain
  13062. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  13063. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  13064. // Copy the CA chain (deep copy)
  13065. // Parse from the raw data of the source cert
  13066. mbedtls_x509_crt *src = ca_chain;
  13067. while (src != nullptr) {
  13068. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  13069. src->raw.len);
  13070. if (ret != 0) { return false; }
  13071. src = src->next;
  13072. }
  13073. // Update the SSL config to use the new CA chain
  13074. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  13075. return true;
  13076. }
  13077. inline size_t tls_get_ca_certs(tls_ctx_t ctx, std::vector<tls_cert_t> &certs) {
  13078. certs.clear();
  13079. if (!ctx) { return 0; }
  13080. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  13081. // Iterate through the CA chain
  13082. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  13083. while (cert != nullptr && cert->raw.len > 0) {
  13084. // Create a copy of the certificate for the caller
  13085. auto *copy = new mbedtls_x509_crt;
  13086. mbedtls_x509_crt_init(copy);
  13087. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  13088. if (ret == 0) {
  13089. certs.push_back(static_cast<tls_cert_t>(copy));
  13090. } else {
  13091. mbedtls_x509_crt_free(copy);
  13092. delete copy;
  13093. }
  13094. cert = cert->next;
  13095. }
  13096. return certs.size();
  13097. }
  13098. inline std::vector<std::string> tls_get_ca_names(tls_ctx_t ctx) {
  13099. std::vector<std::string> names;
  13100. if (!ctx) { return names; }
  13101. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  13102. // Iterate through the CA chain
  13103. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  13104. while (cert != nullptr && cert->raw.len > 0) {
  13105. char buf[512];
  13106. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  13107. if (ret > 0) { names.push_back(buf); }
  13108. cert = cert->next;
  13109. }
  13110. return names;
  13111. }
  13112. inline bool tls_update_server_cert(tls_ctx_t ctx, const char *cert_pem,
  13113. const char *key_pem, const char *password) {
  13114. if (!ctx || !cert_pem || !key_pem) { return false; }
  13115. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  13116. // Free existing certificate and key
  13117. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  13118. mbedtls_pk_free(&mbed_ctx->own_key);
  13119. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  13120. mbedtls_pk_init(&mbed_ctx->own_key);
  13121. // Parse certificate PEM
  13122. int ret = mbedtls_x509_crt_parse(
  13123. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  13124. strlen(cert_pem) + 1);
  13125. if (ret != 0) {
  13126. mbedtls_last_error() = ret;
  13127. return false;
  13128. }
  13129. // Parse private key PEM
  13130. #if MBEDTLS_VERSION_MAJOR >= 3
  13131. ret = mbedtls_pk_parse_key(
  13132. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  13133. strlen(key_pem) + 1,
  13134. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  13135. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  13136. &mbed_ctx->ctr_drbg);
  13137. #else
  13138. ret = mbedtls_pk_parse_key(
  13139. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  13140. strlen(key_pem) + 1,
  13141. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  13142. password ? strlen(password) : 0);
  13143. #endif
  13144. if (ret != 0) {
  13145. mbedtls_last_error() = ret;
  13146. return false;
  13147. }
  13148. // Configure SSL to use the new certificate and key
  13149. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  13150. &mbed_ctx->own_key);
  13151. if (ret != 0) {
  13152. mbedtls_last_error() = ret;
  13153. return false;
  13154. }
  13155. return true;
  13156. }
  13157. inline bool tls_update_server_client_ca(tls_ctx_t ctx, const char *ca_pem) {
  13158. if (!ctx || !ca_pem) { return false; }
  13159. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  13160. // Free existing CA chain
  13161. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  13162. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  13163. // Parse CA PEM
  13164. int ret = mbedtls_x509_crt_parse(
  13165. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  13166. strlen(ca_pem) + 1);
  13167. if (ret != 0) {
  13168. mbedtls_last_error() = ret;
  13169. return false;
  13170. }
  13171. // Update SSL config to use new CA chain
  13172. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  13173. return true;
  13174. }
  13175. // Thread-local storage for verify callback (MbedTLS)
  13176. inline TlsVerifyCallback &get_mbedtls_verify_callback() {
  13177. static thread_local TlsVerifyCallback callback;
  13178. return callback;
  13179. }
  13180. // MbedTLS verify callback wrapper
  13181. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt, int depth,
  13182. uint32_t *flags) {
  13183. (void)depth;
  13184. auto &callback = get_mbedtls_verify_callback();
  13185. if (!callback) { return 0; } // Continue with default verification
  13186. // data points to the MbedTlsSession
  13187. auto *session = static_cast<MbedTlsSession *>(data);
  13188. // Call user callback
  13189. bool accepted = callback(static_cast<tls_session_t>(session),
  13190. static_cast<tls_cert_t>(crt));
  13191. if (accepted) {
  13192. *flags = 0; // Clear all error flags
  13193. return 0;
  13194. }
  13195. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  13196. }
  13197. inline bool tls_set_verify_callback(tls_ctx_t ctx, TlsVerifyCallback callback) {
  13198. if (!ctx) { return false; }
  13199. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  13200. get_mbedtls_verify_callback() = std::move(callback);
  13201. mbed_ctx->has_verify_callback =
  13202. static_cast<bool>(get_mbedtls_verify_callback());
  13203. if (mbed_ctx->has_verify_callback) {
  13204. // Set OPTIONAL mode to ensure callback is called even when verification
  13205. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  13206. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  13207. mbedtls_ssl_conf_verify(&mbed_ctx->conf, mbedtls_verify_callback, nullptr);
  13208. } else {
  13209. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  13210. }
  13211. return true;
  13212. }
  13213. // Thread-local storage for extended verify callback
  13214. inline TlsVerifyCallbackEx &get_mbedtls_verify_callback_ex() {
  13215. static thread_local TlsVerifyCallbackEx callback;
  13216. return callback;
  13217. }
  13218. // Thread-local for depth tracking (Mbed TLS doesn't provide depth directly)
  13219. inline int &get_mbedtls_verify_depth() {
  13220. static thread_local int depth = 0;
  13221. return depth;
  13222. }
  13223. // Mbed TLS extended verify callback wrapper
  13224. inline int mbedtls_verify_callback_ex(void *data, mbedtls_x509_crt *crt,
  13225. int cert_depth, uint32_t *flags) {
  13226. auto &callback = get_mbedtls_verify_callback_ex();
  13227. if (!callback) { return 0; }
  13228. auto *session = static_cast<MbedTlsSession *>(data);
  13229. // Build context
  13230. TlsVerifyContext verify_ctx;
  13231. verify_ctx.session = static_cast<tls_session_t>(session);
  13232. verify_ctx.cert = static_cast<tls_cert_t>(crt);
  13233. verify_ctx.depth = cert_depth;
  13234. verify_ctx.preverify_ok = (*flags == 0);
  13235. verify_ctx.error_code = static_cast<long>(*flags);
  13236. // Convert Mbed TLS flags to error string
  13237. static thread_local char error_buf[256];
  13238. if (*flags != 0) {
  13239. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  13240. verify_ctx.error_string = error_buf;
  13241. } else {
  13242. verify_ctx.error_string = nullptr;
  13243. }
  13244. bool accepted = callback(verify_ctx);
  13245. if (accepted) {
  13246. *flags = 0;
  13247. return 0;
  13248. }
  13249. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  13250. }
  13251. inline bool tls_set_verify_callback_ex(tls_ctx_t ctx,
  13252. TlsVerifyCallbackEx callback) {
  13253. if (!ctx) { return false; }
  13254. auto *mbed_ctx = static_cast<MbedTlsContext *>(ctx);
  13255. get_mbedtls_verify_callback_ex() = std::move(callback);
  13256. mbed_ctx->has_verify_callback =
  13257. static_cast<bool>(get_mbedtls_verify_callback_ex());
  13258. if (mbed_ctx->has_verify_callback) {
  13259. // Set OPTIONAL mode to ensure callback is called even when verification
  13260. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  13261. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  13262. mbedtls_ssl_conf_verify(&mbed_ctx->conf, mbedtls_verify_callback_ex,
  13263. nullptr);
  13264. } else {
  13265. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  13266. }
  13267. return true;
  13268. }
  13269. inline long tls_get_verify_error(tls_session_t session) {
  13270. if (!session) { return -1; }
  13271. auto *msession = static_cast<MbedTlsSession *>(session);
  13272. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  13273. }
  13274. inline std::string tls_verify_error_string(long error_code) {
  13275. if (error_code == 0) { return ""; }
  13276. char buf[256];
  13277. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  13278. static_cast<uint32_t>(error_code));
  13279. // Remove trailing newline if present
  13280. std::string result(buf);
  13281. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  13282. result.pop_back();
  13283. }
  13284. return result;
  13285. }
  13286. } // namespace tls
  13287. } // namespace detail
  13288. /*
  13289. * Mbed TLS-specific SSLServer/SSLClient Implementation
  13290. */
  13291. inline SSLClient::SSLClient(const std::string &host)
  13292. : SSLClient(host, 443, std::string(), std::string()) {}
  13293. inline SSLClient::SSLClient(const std::string &host, int port)
  13294. : SSLClient(host, port, std::string(), std::string()) {}
  13295. inline SSLClient::SSLClient(const std::string &host, int port,
  13296. const std::string &client_cert_path,
  13297. const std::string &client_key_path,
  13298. const std::string &private_key_password)
  13299. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13300. using namespace detail::tls;
  13301. ctx_ = tls_create_client_context();
  13302. if (!ctx_) { return; }
  13303. // Set minimum TLS version to 1.2
  13304. tls_set_min_version(ctx_, 0x0303); // TLS 1.2
  13305. detail::split(&host_[0], &host_[host_.size()], '.',
  13306. [&](const char *b, const char *e) {
  13307. host_components_.emplace_back(b, e);
  13308. });
  13309. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13310. const char *password =
  13311. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13312. if (!tls_set_client_cert_file(ctx_, client_cert_path.c_str(),
  13313. client_key_path.c_str(), password)) {
  13314. last_backend_error_ = tls_get_error();
  13315. tls_free_context(ctx_);
  13316. ctx_ = nullptr;
  13317. }
  13318. }
  13319. }
  13320. inline SSLClient::SSLClient(const std::string &host, int port,
  13321. const PemMemory &pem)
  13322. : ClientImpl(host, port) {
  13323. using namespace detail::tls;
  13324. ctx_ = tls_create_client_context();
  13325. if (!ctx_) { return; }
  13326. // Set minimum TLS version to 1.2
  13327. tls_set_min_version(ctx_, 0x0303); // TLS 1.2
  13328. detail::split(&host_[0], &host_[host_.size()], '.',
  13329. [&](const char *b, const char *e) {
  13330. host_components_.emplace_back(b, e);
  13331. });
  13332. if (pem.cert_pem && pem.key_pem) {
  13333. if (!tls_set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13334. pem.private_key_password)) {
  13335. last_backend_error_ = tls_get_error();
  13336. tls_free_context(ctx_);
  13337. ctx_ = nullptr;
  13338. }
  13339. }
  13340. }
  13341. inline void SSLClient::set_ca_cert_store(void *ca_cert_store) {
  13342. if (ca_cert_store && ctx_) {
  13343. // tls_set_ca_store takes ownership of ca_cert_store
  13344. detail::tls::tls_set_ca_store(ctx_, ca_cert_store);
  13345. } else if (ca_cert_store) {
  13346. detail::tls::tls_free_ca_store(ca_cert_store);
  13347. }
  13348. }
  13349. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13350. std::size_t size) {
  13351. if (ctx_ && ca_cert && size > 0) {
  13352. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13353. detail::tls::tls_load_ca_pem(ctx_, ca_cert, size);
  13354. }
  13355. }
  13356. inline void
  13357. SSLClient::set_server_certificate_verifier(TlsVerifyCallback verifier) {
  13358. if (!ctx_) { return; }
  13359. detail::tls::tls_set_verify_callback(
  13360. ctx_, [verifier](detail::tls::tls_session_t session,
  13361. detail::tls::tls_cert_t cert) {
  13362. return verifier(session, cert);
  13363. });
  13364. }
  13365. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13366. using namespace detail::tls;
  13367. // Load system certificates if no CA certs were explicitly set
  13368. if (ca_cert_file_path_.empty() && ca_cert_dir_path_.empty()) {
  13369. tls_load_system_certs(ctx_);
  13370. }
  13371. // Load CA certificates from file/dir if specified
  13372. if (!ca_cert_file_path_.empty()) {
  13373. if (!tls_load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  13374. last_backend_error_ = tls_get_error();
  13375. error = Error::SSLLoadingCerts;
  13376. return false;
  13377. }
  13378. }
  13379. if (!ca_cert_dir_path_.empty()) {
  13380. if (!tls_load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  13381. last_backend_error_ = tls_get_error();
  13382. error = Error::SSLLoadingCerts;
  13383. return false;
  13384. }
  13385. }
  13386. // For IP addresses, we need special handling in mbedTLS:
  13387. // - RFC 6066 prohibits sending IP addresses in SNI
  13388. // - mbedTLS 3.x requires hostname for cert verification (VERIFY_REQUIRED)
  13389. // - Solution: Use VERIFY_OPTIONAL for IP addresses and verify manually
  13390. bool is_ip = detail::is_ip_address(host_);
  13391. if (is_ip && server_certificate_verification_) {
  13392. // Use OPTIONAL mode so mbedTLS doesn't require hostname
  13393. tls_set_verify_client(ctx_, false);
  13394. } else {
  13395. tls_set_verify_client(ctx_, server_certificate_verification_);
  13396. }
  13397. auto session = tls_create_session(ctx_, socket.sock);
  13398. if (!session) {
  13399. last_backend_error_ = tls_get_error();
  13400. error = Error::SSLConnection;
  13401. return false;
  13402. }
  13403. // Use scope_exit to ensure session is freed on error paths
  13404. bool success = false;
  13405. auto session_guard = detail::scope_exit([&] {
  13406. if (!success) { tls_free_session(session); }
  13407. });
  13408. // Set hostname for SNI (only for non-IP addresses per RFC 6066)
  13409. if (!is_ip) {
  13410. if (!tls_set_hostname(session, host_.c_str())) {
  13411. last_backend_error_ = tls_get_error();
  13412. error = Error::SSLConnection;
  13413. return false;
  13414. }
  13415. }
  13416. // Perform TLS handshake
  13417. TlsError tls_err;
  13418. if (!tls_connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13419. connection_timeout_usec_, &tls_err)) {
  13420. last_ssl_error_ = static_cast<int>(tls_err.code);
  13421. last_backend_error_ = tls_err.backend_code;
  13422. // Map TLS error codes to appropriate Error types
  13423. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13424. error = Error::SSLServerVerification;
  13425. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13426. error = Error::SSLServerHostnameVerification;
  13427. } else {
  13428. error = Error::SSLConnection;
  13429. }
  13430. return false;
  13431. }
  13432. // Verify server certificate
  13433. if (server_certificate_verification_) {
  13434. auto verify_result = tls_get_verify_result(session);
  13435. if (verify_result != 0) {
  13436. last_backend_error_ = static_cast<unsigned long>(verify_result);
  13437. error = Error::SSLServerVerification;
  13438. return false;
  13439. }
  13440. auto cert = tls_get_peer_cert(session);
  13441. if (!cert) {
  13442. last_backend_error_ = tls_get_error();
  13443. error = Error::SSLServerVerification;
  13444. return false;
  13445. }
  13446. auto cert_guard = detail::scope_exit([&] { tls_free_cert(cert); });
  13447. if (server_hostname_verification_) {
  13448. if (!tls_verify_hostname(cert, host_.c_str())) {
  13449. // Use a well-known error code for hostname mismatch
  13450. last_backend_error_ = 0x4000A000; // Custom code for hostname mismatch
  13451. error = Error::SSLServerHostnameVerification;
  13452. return false;
  13453. }
  13454. }
  13455. }
  13456. success = true;
  13457. socket.ssl = session;
  13458. return true;
  13459. }
  13460. inline mbedtls_ssl_config *SSLServer::ssl_config() const {
  13461. auto ctx = static_cast<detail::tls::MbedTlsContext *>(ctx_);
  13462. return ctx ? &ctx->conf : nullptr;
  13463. }
  13464. inline SSLServer::SSLServer(
  13465. const std::function<bool(mbedtls_ssl_config &conf)> &setup_callback) {
  13466. using namespace detail::tls;
  13467. ctx_ = tls_create_server_context();
  13468. if (ctx_) {
  13469. auto mbedtls_ctx = static_cast<MbedTlsContext *>(ctx_);
  13470. if (!setup_callback(mbedtls_ctx->conf)) {
  13471. tls_free_context(ctx_);
  13472. ctx_ = nullptr;
  13473. }
  13474. }
  13475. }
  13476. inline mbedtls_ssl_config *SSLClient::ssl_config() const {
  13477. auto ctx = static_cast<detail::tls::MbedTlsContext *>(ctx_);
  13478. return ctx ? &ctx->conf : nullptr;
  13479. }
  13480. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  13481. /*
  13482. * SSL/TLS Common Implementation
  13483. */
  13484. // ClientConnection destructor (defined here because tls namespace
  13485. // is now available)
  13486. inline ClientConnection::~ClientConnection() {
  13487. #ifdef CPPHTTPLIB_SSL_ENABLED
  13488. if (session) {
  13489. detail::tls::tls_shutdown(session, true);
  13490. detail::tls::tls_free_session(session);
  13491. session = nullptr;
  13492. }
  13493. #endif
  13494. if (sock != INVALID_SOCKET) {
  13495. detail::close_socket(sock);
  13496. sock = INVALID_SOCKET;
  13497. }
  13498. }
  13499. #ifdef CPPHTTPLIB_SSL_ENABLED
  13500. namespace detail {
  13501. inline bool is_ip_address(const std::string &host) {
  13502. struct in_addr addr4;
  13503. struct in6_addr addr6;
  13504. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  13505. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  13506. }
  13507. template <typename T>
  13508. inline bool process_server_socket_ssl(
  13509. const std::atomic<socket_t> &svr_sock, tls::tls_session_t session,
  13510. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  13511. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  13512. time_t write_timeout_usec, T callback) {
  13513. return process_server_socket_core(
  13514. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  13515. [&](bool close_connection, bool &connection_closed) {
  13516. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  13517. write_timeout_sec, write_timeout_usec);
  13518. return callback(strm, close_connection, connection_closed);
  13519. });
  13520. }
  13521. template <typename T>
  13522. inline bool process_client_socket_ssl(
  13523. tls::tls_session_t session, socket_t sock, time_t read_timeout_sec,
  13524. time_t read_timeout_usec, time_t write_timeout_sec,
  13525. time_t write_timeout_usec, time_t max_timeout_msec,
  13526. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  13527. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  13528. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  13529. start_time);
  13530. return callback(strm);
  13531. }
  13532. // SSL socket stream implementation
  13533. inline SSLSocketStream::SSLSocketStream(
  13534. socket_t sock, tls::tls_session_t session, time_t read_timeout_sec,
  13535. time_t read_timeout_usec, time_t write_timeout_sec,
  13536. time_t write_timeout_usec, time_t max_timeout_msec,
  13537. std::chrono::time_point<std::chrono::steady_clock> start_time)
  13538. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  13539. read_timeout_usec_(read_timeout_usec),
  13540. write_timeout_sec_(write_timeout_sec),
  13541. write_timeout_usec_(write_timeout_usec),
  13542. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  13543. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13544. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  13545. // Note: tls_create_session() also clears this, but SSLClient currently
  13546. // uses ssl_new() which does not. Until full TLS API migration is complete,
  13547. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  13548. // SSL session was created.
  13549. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  13550. #endif
  13551. }
  13552. inline SSLSocketStream::~SSLSocketStream() = default;
  13553. inline bool SSLSocketStream::is_readable() const {
  13554. return tls::tls_pending(session_) > 0;
  13555. }
  13556. inline bool SSLSocketStream::wait_readable() const {
  13557. if (max_timeout_msec_ <= 0) {
  13558. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  13559. }
  13560. time_t read_timeout_sec;
  13561. time_t read_timeout_usec;
  13562. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  13563. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  13564. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  13565. }
  13566. inline bool SSLSocketStream::wait_writable() const {
  13567. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  13568. is_socket_alive(sock_) && !tls::tls_is_peer_closed(session_, sock_);
  13569. }
  13570. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  13571. if (tls::tls_pending(session_) > 0) {
  13572. tls::TlsError err;
  13573. auto ret = tls::tls_read(session_, ptr, size, err);
  13574. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  13575. error_ = Error::ConnectionClosed;
  13576. }
  13577. return ret;
  13578. } else if (wait_readable()) {
  13579. tls::TlsError err;
  13580. auto ret = tls::tls_read(session_, ptr, size, err);
  13581. if (ret < 0) {
  13582. auto n = 1000;
  13583. #ifdef _WIN32
  13584. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  13585. (err.code == tls::ErrorCode::SyscallError &&
  13586. WSAGetLastError() == WSAETIMEDOUT))) {
  13587. #else
  13588. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  13589. #endif
  13590. if (tls::tls_pending(session_) > 0) {
  13591. return tls::tls_read(session_, ptr, size, err);
  13592. } else if (wait_readable()) {
  13593. std::this_thread::sleep_for(std::chrono::microseconds{10});
  13594. ret = tls::tls_read(session_, ptr, size, err);
  13595. if (ret >= 0) { return ret; }
  13596. } else {
  13597. break;
  13598. }
  13599. }
  13600. assert(ret < 0);
  13601. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  13602. error_ = Error::ConnectionClosed;
  13603. }
  13604. return ret;
  13605. } else {
  13606. error_ = Error::Timeout;
  13607. return -1;
  13608. }
  13609. }
  13610. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  13611. if (wait_writable()) {
  13612. auto handle_size =
  13613. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  13614. tls::TlsError err;
  13615. auto ret = tls::tls_write(session_, ptr, handle_size, err);
  13616. if (ret < 0) {
  13617. auto n = 1000;
  13618. #ifdef _WIN32
  13619. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  13620. (err.code == tls::ErrorCode::SyscallError &&
  13621. WSAGetLastError() == WSAETIMEDOUT))) {
  13622. #else
  13623. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  13624. #endif
  13625. if (wait_writable()) {
  13626. std::this_thread::sleep_for(std::chrono::microseconds{10});
  13627. ret = tls::tls_write(session_, ptr, handle_size, err);
  13628. if (ret >= 0) { return ret; }
  13629. } else {
  13630. break;
  13631. }
  13632. }
  13633. assert(ret < 0);
  13634. }
  13635. return ret;
  13636. }
  13637. return -1;
  13638. }
  13639. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  13640. int &port) const {
  13641. detail::get_remote_ip_and_port(sock_, ip, port);
  13642. }
  13643. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  13644. int &port) const {
  13645. detail::get_local_ip_and_port(sock_, ip, port);
  13646. }
  13647. inline socket_t SSLSocketStream::socket() const { return sock_; }
  13648. inline time_t SSLSocketStream::duration() const {
  13649. return std::chrono::duration_cast<std::chrono::milliseconds>(
  13650. std::chrono::steady_clock::now() - start_time_)
  13651. .count();
  13652. }
  13653. } // namespace detail
  13654. #ifdef CPPHTTPLIB_SSL_ENABLED
  13655. // SSL HTTP server implementation (common for OpenSSL and Mbed TLS)
  13656. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13657. const char *client_ca_cert_file_path,
  13658. const char *client_ca_cert_dir_path,
  13659. const char *private_key_password) {
  13660. using namespace detail::tls;
  13661. ctx_ = tls_create_server_context();
  13662. if (!ctx_) { return; }
  13663. // Load server certificate and private key
  13664. if (!tls_set_server_cert_file(ctx_, cert_path, private_key_path,
  13665. private_key_password)) {
  13666. last_ssl_error_ = static_cast<int>(tls_get_error());
  13667. tls_free_context(ctx_);
  13668. ctx_ = nullptr;
  13669. return;
  13670. }
  13671. // Load client CA certificates for client authentication
  13672. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13673. if (!tls_set_client_ca_file(ctx_, client_ca_cert_file_path,
  13674. client_ca_cert_dir_path)) {
  13675. last_ssl_error_ = static_cast<int>(tls_get_error());
  13676. tls_free_context(ctx_);
  13677. ctx_ = nullptr;
  13678. return;
  13679. }
  13680. // Enable client certificate verification
  13681. tls_set_verify_client(ctx_, true);
  13682. }
  13683. }
  13684. inline SSLServer::SSLServer(const PemMemory &pem) {
  13685. using namespace detail::tls;
  13686. ctx_ = tls_create_server_context();
  13687. if (ctx_) {
  13688. if (!tls_set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13689. pem.private_key_password)) {
  13690. last_ssl_error_ = static_cast<int>(tls_get_error());
  13691. tls_free_context(ctx_);
  13692. ctx_ = nullptr;
  13693. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13694. if (!tls_load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13695. last_ssl_error_ = static_cast<int>(tls_get_error());
  13696. tls_free_context(ctx_);
  13697. ctx_ = nullptr;
  13698. } else {
  13699. tls_set_verify_client(ctx_, true);
  13700. }
  13701. }
  13702. }
  13703. }
  13704. inline SSLServer::SSLServer(
  13705. const std::function<bool(void *ctx)> &setup_callback) {
  13706. using namespace detail::tls;
  13707. ctx_ = tls_create_server_context();
  13708. if (ctx_) {
  13709. if (!setup_callback(ctx_)) {
  13710. tls_free_context(ctx_);
  13711. ctx_ = nullptr;
  13712. }
  13713. }
  13714. }
  13715. inline SSLServer::~SSLServer() {
  13716. if (ctx_) { detail::tls::tls_free_context(ctx_); }
  13717. }
  13718. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13719. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13720. using namespace detail::tls;
  13721. // Create TLS session with mutex protection
  13722. tls_session_t session = nullptr;
  13723. {
  13724. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13725. session = tls_create_session(static_cast<tls_ctx_t>(ctx_), sock);
  13726. }
  13727. if (!session) {
  13728. last_ssl_error_ = static_cast<int>(tls_get_error());
  13729. detail::shutdown_socket(sock);
  13730. detail::close_socket(sock);
  13731. return false;
  13732. }
  13733. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13734. bool handshake_done = false;
  13735. bool ret = false;
  13736. auto cleanup = detail::scope_exit([&] {
  13737. // Shutdown gracefully if handshake succeeded and processing was successful
  13738. if (handshake_done) { tls_shutdown(session, ret); }
  13739. tls_free_session(session);
  13740. detail::shutdown_socket(sock);
  13741. detail::close_socket(sock);
  13742. });
  13743. // Perform TLS accept handshake with timeout
  13744. TlsError tls_err;
  13745. if (!tls_accept_nonblocking(session, sock, read_timeout_sec_,
  13746. read_timeout_usec_, &tls_err)) {
  13747. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13748. // Map TlsError to legacy ssl_error for backward compatibility
  13749. if (tls_err.code == ErrorCode::WantRead) {
  13750. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13751. } else if (tls_err.code == ErrorCode::WantWrite) {
  13752. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13753. } else {
  13754. last_ssl_error_ = SSL_ERROR_SSL;
  13755. }
  13756. #else
  13757. last_ssl_error_ = static_cast<int>(tls_get_error());
  13758. #endif
  13759. return false;
  13760. }
  13761. handshake_done = true;
  13762. std::string remote_addr;
  13763. int remote_port = 0;
  13764. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13765. std::string local_addr;
  13766. int local_port = 0;
  13767. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13768. ret = detail::process_server_socket_ssl(
  13769. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13770. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13771. write_timeout_usec_,
  13772. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13773. return process_request(strm, remote_addr, remote_port, local_addr,
  13774. local_port, close_connection, connection_closed,
  13775. [&](Request &req) { req.ssl = session; });
  13776. });
  13777. return ret;
  13778. }
  13779. inline SSLClient::~SSLClient() {
  13780. if (ctx_) { detail::tls::tls_free_context(ctx_); }
  13781. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13782. // base function rather than the derived function once we get to the
  13783. // base class destructor, and won't free the SSL (causing a leak).
  13784. shutdown_ssl_impl(socket_, true);
  13785. }
  13786. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13787. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13788. shutdown_ssl_impl(socket, shutdown_gracefully);
  13789. }
  13790. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13791. bool shutdown_gracefully) {
  13792. if (socket.sock == INVALID_SOCKET) {
  13793. assert(socket.ssl == nullptr);
  13794. return;
  13795. }
  13796. if (socket.ssl) {
  13797. detail::tls::tls_shutdown(socket.ssl, shutdown_gracefully);
  13798. {
  13799. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13800. detail::tls::tls_free_session(socket.ssl);
  13801. }
  13802. socket.ssl = nullptr;
  13803. }
  13804. assert(socket.ssl == nullptr);
  13805. }
  13806. inline bool SSLClient::process_socket(
  13807. const Socket &socket,
  13808. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13809. std::function<bool(Stream &strm)> callback) {
  13810. assert(socket.ssl);
  13811. return detail::process_client_socket_ssl(
  13812. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13813. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13814. std::move(callback));
  13815. }
  13816. inline bool SSLClient::is_ssl() const { return true; }
  13817. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13818. if (!is_valid()) {
  13819. error = Error::SSLConnection;
  13820. return false;
  13821. }
  13822. return ClientImpl::create_and_connect_socket(socket, error);
  13823. }
  13824. // Assumes that socket_mutex_ is locked and that there are no requests in
  13825. // flight
  13826. inline bool SSLClient::connect_with_proxy(
  13827. Socket &socket,
  13828. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13829. Response &res, bool &success, Error &error) {
  13830. success = true;
  13831. Response proxy_res;
  13832. if (!detail::process_client_socket(
  13833. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13834. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13835. start_time, [&](Stream &strm) {
  13836. Request req2;
  13837. req2.method = "CONNECT";
  13838. req2.path =
  13839. detail::make_host_and_port_string_always_port(host_, port_);
  13840. if (max_timeout_msec_ > 0) {
  13841. req2.start_time_ = std::chrono::steady_clock::now();
  13842. }
  13843. return process_request(strm, req2, proxy_res, false, error);
  13844. })) {
  13845. // Thread-safe to close everything because we are assuming there are no
  13846. // requests in flight
  13847. shutdown_ssl(socket, true);
  13848. shutdown_socket(socket);
  13849. close_socket(socket);
  13850. success = false;
  13851. return false;
  13852. }
  13853. #ifdef CPPHTTPLIB_SSL_ENABLED
  13854. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13855. if (!proxy_digest_auth_username_.empty() &&
  13856. !proxy_digest_auth_password_.empty()) {
  13857. std::map<std::string, std::string> auth;
  13858. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13859. // Close the current socket and create a new one for the authenticated
  13860. // request
  13861. shutdown_ssl(socket, true);
  13862. shutdown_socket(socket);
  13863. close_socket(socket);
  13864. // Create a new socket for the authenticated CONNECT request
  13865. if (!ensure_socket_connection(socket, error)) {
  13866. success = false;
  13867. output_error_log(error, nullptr);
  13868. return false;
  13869. }
  13870. proxy_res = Response();
  13871. if (!detail::process_client_socket(
  13872. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13873. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13874. start_time, [&](Stream &strm) {
  13875. Request req3;
  13876. req3.method = "CONNECT";
  13877. req3.path = detail::make_host_and_port_string_always_port(
  13878. host_, port_);
  13879. req3.headers.insert(detail::make_digest_authentication_header(
  13880. req3, auth, 1, detail::random_string(10),
  13881. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13882. true));
  13883. if (max_timeout_msec_ > 0) {
  13884. req3.start_time_ = std::chrono::steady_clock::now();
  13885. }
  13886. return process_request(strm, req3, proxy_res, false, error);
  13887. })) {
  13888. // Thread-safe to close everything because we are assuming there are
  13889. // no requests in flight
  13890. shutdown_ssl(socket, true);
  13891. shutdown_socket(socket);
  13892. close_socket(socket);
  13893. success = false;
  13894. return false;
  13895. }
  13896. }
  13897. }
  13898. }
  13899. #endif
  13900. // If status code is not 200, proxy request is failed.
  13901. // Set error to ProxyConnection and return proxy response
  13902. // as the response of the request
  13903. if (proxy_res.status != StatusCode::OK_200) {
  13904. error = Error::ProxyConnection;
  13905. output_error_log(error, nullptr);
  13906. res = std::move(proxy_res);
  13907. // Thread-safe to close everything because we are assuming there are
  13908. // no requests in flight
  13909. shutdown_ssl(socket, true);
  13910. shutdown_socket(socket);
  13911. close_socket(socket);
  13912. return false;
  13913. }
  13914. return true;
  13915. }
  13916. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13917. const char *key_pem,
  13918. const char *password) {
  13919. if (!ctx_) { return false; }
  13920. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13921. return detail::tls::tls_update_server_cert(ctx_, cert_pem, key_pem, password);
  13922. }
  13923. inline bool SSLServer::update_client_ca_pem(const char *ca_pem) {
  13924. if (!ctx_) { return false; }
  13925. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13926. return detail::tls::tls_update_server_client_ca(ctx_, ca_pem);
  13927. }
  13928. #endif // CPPHTTPLIB_SSL_ENABLED
  13929. #endif // CPPHTTPLIB_SSL_ENABLED
  13930. // Universal client implementation
  13931. inline Client::Client(const std::string &scheme_host_port)
  13932. : Client(scheme_host_port, std::string(), std::string()) {}
  13933. inline Client::Client(const std::string &scheme_host_port,
  13934. const std::string &client_cert_path,
  13935. const std::string &client_key_path) {
  13936. const static std::regex re(
  13937. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  13938. std::smatch m;
  13939. if (std::regex_match(scheme_host_port, m, re)) {
  13940. auto scheme = m[1].str();
  13941. #ifdef CPPHTTPLIB_SSL_ENABLED
  13942. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  13943. #else
  13944. if (!scheme.empty() && scheme != "http") {
  13945. #endif
  13946. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13947. std::string msg = "'" + scheme + "' scheme is not supported.";
  13948. throw std::invalid_argument(msg);
  13949. #endif
  13950. return;
  13951. }
  13952. auto is_ssl = scheme == "https";
  13953. auto host = m[2].str();
  13954. if (host.empty()) { host = m[3].str(); }
  13955. auto port_str = m[4].str();
  13956. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  13957. if (is_ssl) {
  13958. #ifdef CPPHTTPLIB_SSL_ENABLED
  13959. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  13960. client_key_path);
  13961. is_ssl_ = is_ssl;
  13962. #endif
  13963. } else {
  13964. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  13965. client_key_path);
  13966. }
  13967. } else {
  13968. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  13969. // if port param below changes.
  13970. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  13971. client_cert_path, client_key_path);
  13972. }
  13973. } // namespace detail
  13974. inline Client::Client(const std::string &host, int port)
  13975. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  13976. inline Client::Client(const std::string &host, int port,
  13977. const std::string &client_cert_path,
  13978. const std::string &client_key_path)
  13979. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  13980. client_key_path)) {}
  13981. inline Client::~Client() = default;
  13982. inline bool Client::is_valid() const {
  13983. return cli_ != nullptr && cli_->is_valid();
  13984. }
  13985. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  13986. return cli_->Get(path, std::move(progress));
  13987. }
  13988. inline Result Client::Get(const std::string &path, const Headers &headers,
  13989. DownloadProgress progress) {
  13990. return cli_->Get(path, headers, std::move(progress));
  13991. }
  13992. inline Result Client::Get(const std::string &path,
  13993. ContentReceiver content_receiver,
  13994. DownloadProgress progress) {
  13995. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  13996. }
  13997. inline Result Client::Get(const std::string &path, const Headers &headers,
  13998. ContentReceiver content_receiver,
  13999. DownloadProgress progress) {
  14000. return cli_->Get(path, headers, std::move(content_receiver),
  14001. std::move(progress));
  14002. }
  14003. inline Result Client::Get(const std::string &path,
  14004. ResponseHandler response_handler,
  14005. ContentReceiver content_receiver,
  14006. DownloadProgress progress) {
  14007. return cli_->Get(path, std::move(response_handler),
  14008. std::move(content_receiver), std::move(progress));
  14009. }
  14010. inline Result Client::Get(const std::string &path, const Headers &headers,
  14011. ResponseHandler response_handler,
  14012. ContentReceiver content_receiver,
  14013. DownloadProgress progress) {
  14014. return cli_->Get(path, headers, std::move(response_handler),
  14015. std::move(content_receiver), std::move(progress));
  14016. }
  14017. inline Result Client::Get(const std::string &path, const Params &params,
  14018. const Headers &headers, DownloadProgress progress) {
  14019. return cli_->Get(path, params, headers, std::move(progress));
  14020. }
  14021. inline Result Client::Get(const std::string &path, const Params &params,
  14022. const Headers &headers,
  14023. ContentReceiver content_receiver,
  14024. DownloadProgress progress) {
  14025. return cli_->Get(path, params, headers, std::move(content_receiver),
  14026. std::move(progress));
  14027. }
  14028. inline Result Client::Get(const std::string &path, const Params &params,
  14029. const Headers &headers,
  14030. ResponseHandler response_handler,
  14031. ContentReceiver content_receiver,
  14032. DownloadProgress progress) {
  14033. return cli_->Get(path, params, headers, std::move(response_handler),
  14034. std::move(content_receiver), std::move(progress));
  14035. }
  14036. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  14037. inline Result Client::Head(const std::string &path, const Headers &headers) {
  14038. return cli_->Head(path, headers);
  14039. }
  14040. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  14041. inline Result Client::Post(const std::string &path, const Headers &headers) {
  14042. return cli_->Post(path, headers);
  14043. }
  14044. inline Result Client::Post(const std::string &path, const char *body,
  14045. size_t content_length,
  14046. const std::string &content_type,
  14047. UploadProgress progress) {
  14048. return cli_->Post(path, body, content_length, content_type, progress);
  14049. }
  14050. inline Result Client::Post(const std::string &path, const Headers &headers,
  14051. const char *body, size_t content_length,
  14052. const std::string &content_type,
  14053. UploadProgress progress) {
  14054. return cli_->Post(path, headers, body, content_length, content_type,
  14055. progress);
  14056. }
  14057. inline Result Client::Post(const std::string &path, const std::string &body,
  14058. const std::string &content_type,
  14059. UploadProgress progress) {
  14060. return cli_->Post(path, body, content_type, progress);
  14061. }
  14062. inline Result Client::Post(const std::string &path, const Headers &headers,
  14063. const std::string &body,
  14064. const std::string &content_type,
  14065. UploadProgress progress) {
  14066. return cli_->Post(path, headers, body, content_type, progress);
  14067. }
  14068. inline Result Client::Post(const std::string &path, size_t content_length,
  14069. ContentProvider content_provider,
  14070. const std::string &content_type,
  14071. UploadProgress progress) {
  14072. return cli_->Post(path, content_length, std::move(content_provider),
  14073. content_type, progress);
  14074. }
  14075. inline Result Client::Post(const std::string &path, size_t content_length,
  14076. ContentProvider content_provider,
  14077. const std::string &content_type,
  14078. ContentReceiver content_receiver,
  14079. UploadProgress progress) {
  14080. return cli_->Post(path, content_length, std::move(content_provider),
  14081. content_type, std::move(content_receiver), progress);
  14082. }
  14083. inline Result Client::Post(const std::string &path,
  14084. ContentProviderWithoutLength content_provider,
  14085. const std::string &content_type,
  14086. UploadProgress progress) {
  14087. return cli_->Post(path, std::move(content_provider), content_type, progress);
  14088. }
  14089. inline Result Client::Post(const std::string &path,
  14090. ContentProviderWithoutLength content_provider,
  14091. const std::string &content_type,
  14092. ContentReceiver content_receiver,
  14093. UploadProgress progress) {
  14094. return cli_->Post(path, std::move(content_provider), content_type,
  14095. std::move(content_receiver), progress);
  14096. }
  14097. inline Result Client::Post(const std::string &path, const Headers &headers,
  14098. size_t content_length,
  14099. ContentProvider content_provider,
  14100. const std::string &content_type,
  14101. UploadProgress progress) {
  14102. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14103. content_type, progress);
  14104. }
  14105. inline Result Client::Post(const std::string &path, const Headers &headers,
  14106. size_t content_length,
  14107. ContentProvider content_provider,
  14108. const std::string &content_type,
  14109. ContentReceiver content_receiver,
  14110. DownloadProgress progress) {
  14111. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14112. content_type, std::move(content_receiver), progress);
  14113. }
  14114. inline Result Client::Post(const std::string &path, const Headers &headers,
  14115. ContentProviderWithoutLength content_provider,
  14116. const std::string &content_type,
  14117. UploadProgress progress) {
  14118. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14119. progress);
  14120. }
  14121. inline Result Client::Post(const std::string &path, const Headers &headers,
  14122. ContentProviderWithoutLength content_provider,
  14123. const std::string &content_type,
  14124. ContentReceiver content_receiver,
  14125. DownloadProgress progress) {
  14126. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14127. std::move(content_receiver), progress);
  14128. }
  14129. inline Result Client::Post(const std::string &path, const Params &params) {
  14130. return cli_->Post(path, params);
  14131. }
  14132. inline Result Client::Post(const std::string &path, const Headers &headers,
  14133. const Params &params) {
  14134. return cli_->Post(path, headers, params);
  14135. }
  14136. inline Result Client::Post(const std::string &path,
  14137. const UploadFormDataItems &items,
  14138. UploadProgress progress) {
  14139. return cli_->Post(path, items, progress);
  14140. }
  14141. inline Result Client::Post(const std::string &path, const Headers &headers,
  14142. const UploadFormDataItems &items,
  14143. UploadProgress progress) {
  14144. return cli_->Post(path, headers, items, progress);
  14145. }
  14146. inline Result Client::Post(const std::string &path, const Headers &headers,
  14147. const UploadFormDataItems &items,
  14148. const std::string &boundary,
  14149. UploadProgress progress) {
  14150. return cli_->Post(path, headers, items, boundary, progress);
  14151. }
  14152. inline Result Client::Post(const std::string &path, const Headers &headers,
  14153. const UploadFormDataItems &items,
  14154. const FormDataProviderItems &provider_items,
  14155. UploadProgress progress) {
  14156. return cli_->Post(path, headers, items, provider_items, progress);
  14157. }
  14158. inline Result Client::Post(const std::string &path, const Headers &headers,
  14159. const std::string &body,
  14160. const std::string &content_type,
  14161. ContentReceiver content_receiver,
  14162. DownloadProgress progress) {
  14163. return cli_->Post(path, headers, body, content_type,
  14164. std::move(content_receiver), progress);
  14165. }
  14166. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  14167. inline Result Client::Put(const std::string &path, const Headers &headers) {
  14168. return cli_->Put(path, headers);
  14169. }
  14170. inline Result Client::Put(const std::string &path, const char *body,
  14171. size_t content_length,
  14172. const std::string &content_type,
  14173. UploadProgress progress) {
  14174. return cli_->Put(path, body, content_length, content_type, progress);
  14175. }
  14176. inline Result Client::Put(const std::string &path, const Headers &headers,
  14177. const char *body, size_t content_length,
  14178. const std::string &content_type,
  14179. UploadProgress progress) {
  14180. return cli_->Put(path, headers, body, content_length, content_type, progress);
  14181. }
  14182. inline Result Client::Put(const std::string &path, const std::string &body,
  14183. const std::string &content_type,
  14184. UploadProgress progress) {
  14185. return cli_->Put(path, body, content_type, progress);
  14186. }
  14187. inline Result Client::Put(const std::string &path, const Headers &headers,
  14188. const std::string &body,
  14189. const std::string &content_type,
  14190. UploadProgress progress) {
  14191. return cli_->Put(path, headers, body, content_type, progress);
  14192. }
  14193. inline Result Client::Put(const std::string &path, size_t content_length,
  14194. ContentProvider content_provider,
  14195. const std::string &content_type,
  14196. UploadProgress progress) {
  14197. return cli_->Put(path, content_length, std::move(content_provider),
  14198. content_type, progress);
  14199. }
  14200. inline Result Client::Put(const std::string &path, size_t content_length,
  14201. ContentProvider content_provider,
  14202. const std::string &content_type,
  14203. ContentReceiver content_receiver,
  14204. UploadProgress progress) {
  14205. return cli_->Put(path, content_length, std::move(content_provider),
  14206. content_type, std::move(content_receiver), progress);
  14207. }
  14208. inline Result Client::Put(const std::string &path,
  14209. ContentProviderWithoutLength content_provider,
  14210. const std::string &content_type,
  14211. UploadProgress progress) {
  14212. return cli_->Put(path, std::move(content_provider), content_type, progress);
  14213. }
  14214. inline Result Client::Put(const std::string &path,
  14215. ContentProviderWithoutLength content_provider,
  14216. const std::string &content_type,
  14217. ContentReceiver content_receiver,
  14218. UploadProgress progress) {
  14219. return cli_->Put(path, std::move(content_provider), content_type,
  14220. std::move(content_receiver), progress);
  14221. }
  14222. inline Result Client::Put(const std::string &path, const Headers &headers,
  14223. size_t content_length,
  14224. ContentProvider content_provider,
  14225. const std::string &content_type,
  14226. UploadProgress progress) {
  14227. return cli_->Put(path, headers, content_length, std::move(content_provider),
  14228. content_type, progress);
  14229. }
  14230. inline Result Client::Put(const std::string &path, const Headers &headers,
  14231. size_t content_length,
  14232. ContentProvider content_provider,
  14233. const std::string &content_type,
  14234. ContentReceiver content_receiver,
  14235. UploadProgress progress) {
  14236. return cli_->Put(path, headers, content_length, std::move(content_provider),
  14237. content_type, std::move(content_receiver), progress);
  14238. }
  14239. inline Result Client::Put(const std::string &path, const Headers &headers,
  14240. ContentProviderWithoutLength content_provider,
  14241. const std::string &content_type,
  14242. UploadProgress progress) {
  14243. return cli_->Put(path, headers, std::move(content_provider), content_type,
  14244. progress);
  14245. }
  14246. inline Result Client::Put(const std::string &path, const Headers &headers,
  14247. ContentProviderWithoutLength content_provider,
  14248. const std::string &content_type,
  14249. ContentReceiver content_receiver,
  14250. UploadProgress progress) {
  14251. return cli_->Put(path, headers, std::move(content_provider), content_type,
  14252. std::move(content_receiver), progress);
  14253. }
  14254. inline Result Client::Put(const std::string &path, const Params &params) {
  14255. return cli_->Put(path, params);
  14256. }
  14257. inline Result Client::Put(const std::string &path, const Headers &headers,
  14258. const Params &params) {
  14259. return cli_->Put(path, headers, params);
  14260. }
  14261. inline Result Client::Put(const std::string &path,
  14262. const UploadFormDataItems &items,
  14263. UploadProgress progress) {
  14264. return cli_->Put(path, items, progress);
  14265. }
  14266. inline Result Client::Put(const std::string &path, const Headers &headers,
  14267. const UploadFormDataItems &items,
  14268. UploadProgress progress) {
  14269. return cli_->Put(path, headers, items, progress);
  14270. }
  14271. inline Result Client::Put(const std::string &path, const Headers &headers,
  14272. const UploadFormDataItems &items,
  14273. const std::string &boundary,
  14274. UploadProgress progress) {
  14275. return cli_->Put(path, headers, items, boundary, progress);
  14276. }
  14277. inline Result Client::Put(const std::string &path, const Headers &headers,
  14278. const UploadFormDataItems &items,
  14279. const FormDataProviderItems &provider_items,
  14280. UploadProgress progress) {
  14281. return cli_->Put(path, headers, items, provider_items, progress);
  14282. }
  14283. inline Result Client::Put(const std::string &path, const Headers &headers,
  14284. const std::string &body,
  14285. const std::string &content_type,
  14286. ContentReceiver content_receiver,
  14287. DownloadProgress progress) {
  14288. return cli_->Put(path, headers, body, content_type, content_receiver,
  14289. progress);
  14290. }
  14291. inline Result Client::Patch(const std::string &path) {
  14292. return cli_->Patch(path);
  14293. }
  14294. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  14295. return cli_->Patch(path, headers);
  14296. }
  14297. inline Result Client::Patch(const std::string &path, const char *body,
  14298. size_t content_length,
  14299. const std::string &content_type,
  14300. UploadProgress progress) {
  14301. return cli_->Patch(path, body, content_length, content_type, progress);
  14302. }
  14303. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14304. const char *body, size_t content_length,
  14305. const std::string &content_type,
  14306. UploadProgress progress) {
  14307. return cli_->Patch(path, headers, body, content_length, content_type,
  14308. progress);
  14309. }
  14310. inline Result Client::Patch(const std::string &path, const std::string &body,
  14311. const std::string &content_type,
  14312. UploadProgress progress) {
  14313. return cli_->Patch(path, body, content_type, progress);
  14314. }
  14315. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14316. const std::string &body,
  14317. const std::string &content_type,
  14318. UploadProgress progress) {
  14319. return cli_->Patch(path, headers, body, content_type, progress);
  14320. }
  14321. inline Result Client::Patch(const std::string &path, size_t content_length,
  14322. ContentProvider content_provider,
  14323. const std::string &content_type,
  14324. UploadProgress progress) {
  14325. return cli_->Patch(path, content_length, std::move(content_provider),
  14326. content_type, progress);
  14327. }
  14328. inline Result Client::Patch(const std::string &path, size_t content_length,
  14329. ContentProvider content_provider,
  14330. const std::string &content_type,
  14331. ContentReceiver content_receiver,
  14332. UploadProgress progress) {
  14333. return cli_->Patch(path, content_length, std::move(content_provider),
  14334. content_type, std::move(content_receiver), progress);
  14335. }
  14336. inline Result Client::Patch(const std::string &path,
  14337. ContentProviderWithoutLength content_provider,
  14338. const std::string &content_type,
  14339. UploadProgress progress) {
  14340. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  14341. }
  14342. inline Result Client::Patch(const std::string &path,
  14343. ContentProviderWithoutLength content_provider,
  14344. const std::string &content_type,
  14345. ContentReceiver content_receiver,
  14346. UploadProgress progress) {
  14347. return cli_->Patch(path, std::move(content_provider), content_type,
  14348. std::move(content_receiver), progress);
  14349. }
  14350. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14351. size_t content_length,
  14352. ContentProvider content_provider,
  14353. const std::string &content_type,
  14354. UploadProgress progress) {
  14355. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  14356. content_type, progress);
  14357. }
  14358. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14359. size_t content_length,
  14360. ContentProvider content_provider,
  14361. const std::string &content_type,
  14362. ContentReceiver content_receiver,
  14363. UploadProgress progress) {
  14364. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  14365. content_type, std::move(content_receiver), progress);
  14366. }
  14367. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14368. ContentProviderWithoutLength content_provider,
  14369. const std::string &content_type,
  14370. UploadProgress progress) {
  14371. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  14372. progress);
  14373. }
  14374. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14375. ContentProviderWithoutLength content_provider,
  14376. const std::string &content_type,
  14377. ContentReceiver content_receiver,
  14378. UploadProgress progress) {
  14379. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  14380. std::move(content_receiver), progress);
  14381. }
  14382. inline Result Client::Patch(const std::string &path, const Params &params) {
  14383. return cli_->Patch(path, params);
  14384. }
  14385. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14386. const Params &params) {
  14387. return cli_->Patch(path, headers, params);
  14388. }
  14389. inline Result Client::Patch(const std::string &path,
  14390. const UploadFormDataItems &items,
  14391. UploadProgress progress) {
  14392. return cli_->Patch(path, items, progress);
  14393. }
  14394. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14395. const UploadFormDataItems &items,
  14396. UploadProgress progress) {
  14397. return cli_->Patch(path, headers, items, progress);
  14398. }
  14399. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14400. const UploadFormDataItems &items,
  14401. const std::string &boundary,
  14402. UploadProgress progress) {
  14403. return cli_->Patch(path, headers, items, boundary, progress);
  14404. }
  14405. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14406. const UploadFormDataItems &items,
  14407. const FormDataProviderItems &provider_items,
  14408. UploadProgress progress) {
  14409. return cli_->Patch(path, headers, items, provider_items, progress);
  14410. }
  14411. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14412. const std::string &body,
  14413. const std::string &content_type,
  14414. ContentReceiver content_receiver,
  14415. DownloadProgress progress) {
  14416. return cli_->Patch(path, headers, body, content_type, content_receiver,
  14417. progress);
  14418. }
  14419. inline Result Client::Delete(const std::string &path,
  14420. DownloadProgress progress) {
  14421. return cli_->Delete(path, progress);
  14422. }
  14423. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14424. DownloadProgress progress) {
  14425. return cli_->Delete(path, headers, progress);
  14426. }
  14427. inline Result Client::Delete(const std::string &path, const char *body,
  14428. size_t content_length,
  14429. const std::string &content_type,
  14430. DownloadProgress progress) {
  14431. return cli_->Delete(path, body, content_length, content_type, progress);
  14432. }
  14433. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14434. const char *body, size_t content_length,
  14435. const std::string &content_type,
  14436. DownloadProgress progress) {
  14437. return cli_->Delete(path, headers, body, content_length, content_type,
  14438. progress);
  14439. }
  14440. inline Result Client::Delete(const std::string &path, const std::string &body,
  14441. const std::string &content_type,
  14442. DownloadProgress progress) {
  14443. return cli_->Delete(path, body, content_type, progress);
  14444. }
  14445. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14446. const std::string &body,
  14447. const std::string &content_type,
  14448. DownloadProgress progress) {
  14449. return cli_->Delete(path, headers, body, content_type, progress);
  14450. }
  14451. inline Result Client::Delete(const std::string &path, const Params &params,
  14452. DownloadProgress progress) {
  14453. return cli_->Delete(path, params, progress);
  14454. }
  14455. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14456. const Params &params, DownloadProgress progress) {
  14457. return cli_->Delete(path, headers, params, progress);
  14458. }
  14459. inline Result Client::Options(const std::string &path) {
  14460. return cli_->Options(path);
  14461. }
  14462. inline Result Client::Options(const std::string &path, const Headers &headers) {
  14463. return cli_->Options(path, headers);
  14464. }
  14465. inline ClientImpl::StreamHandle
  14466. Client::open_stream(const std::string &method, const std::string &path,
  14467. const Params &params, const Headers &headers,
  14468. const std::string &body, const std::string &content_type) {
  14469. return cli_->open_stream(method, path, params, headers, body, content_type);
  14470. }
  14471. inline bool Client::send(Request &req, Response &res, Error &error) {
  14472. return cli_->send(req, res, error);
  14473. }
  14474. inline Result Client::send(const Request &req) { return cli_->send(req); }
  14475. inline void Client::stop() { cli_->stop(); }
  14476. inline std::string Client::host() const { return cli_->host(); }
  14477. inline int Client::port() const { return cli_->port(); }
  14478. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  14479. inline socket_t Client::socket() const { return cli_->socket(); }
  14480. inline void
  14481. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  14482. cli_->set_hostname_addr_map(std::move(addr_map));
  14483. }
  14484. inline void Client::set_default_headers(Headers headers) {
  14485. cli_->set_default_headers(std::move(headers));
  14486. }
  14487. inline void Client::set_header_writer(
  14488. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  14489. cli_->set_header_writer(writer);
  14490. }
  14491. inline void Client::set_address_family(int family) {
  14492. cli_->set_address_family(family);
  14493. }
  14494. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  14495. inline void Client::set_socket_options(SocketOptions socket_options) {
  14496. cli_->set_socket_options(std::move(socket_options));
  14497. }
  14498. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  14499. cli_->set_connection_timeout(sec, usec);
  14500. }
  14501. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  14502. cli_->set_read_timeout(sec, usec);
  14503. }
  14504. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  14505. cli_->set_write_timeout(sec, usec);
  14506. }
  14507. inline void Client::set_basic_auth(const std::string &username,
  14508. const std::string &password) {
  14509. cli_->set_basic_auth(username, password);
  14510. }
  14511. inline void Client::set_bearer_token_auth(const std::string &token) {
  14512. cli_->set_bearer_token_auth(token);
  14513. }
  14514. #ifdef CPPHTTPLIB_SSL_ENABLED
  14515. inline void Client::set_digest_auth(const std::string &username,
  14516. const std::string &password) {
  14517. cli_->set_digest_auth(username, password);
  14518. }
  14519. #endif
  14520. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  14521. inline void Client::set_follow_location(bool on) {
  14522. cli_->set_follow_location(on);
  14523. }
  14524. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  14525. [[deprecated("Use set_path_encode instead")]]
  14526. inline void Client::set_url_encode(bool on) {
  14527. cli_->set_path_encode(on);
  14528. }
  14529. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  14530. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  14531. inline void Client::set_interface(const std::string &intf) {
  14532. cli_->set_interface(intf);
  14533. }
  14534. inline void Client::set_proxy(const std::string &host, int port) {
  14535. cli_->set_proxy(host, port);
  14536. }
  14537. inline void Client::set_proxy_basic_auth(const std::string &username,
  14538. const std::string &password) {
  14539. cli_->set_proxy_basic_auth(username, password);
  14540. }
  14541. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  14542. cli_->set_proxy_bearer_token_auth(token);
  14543. }
  14544. #ifdef CPPHTTPLIB_SSL_ENABLED
  14545. inline void Client::set_proxy_digest_auth(const std::string &username,
  14546. const std::string &password) {
  14547. cli_->set_proxy_digest_auth(username, password);
  14548. }
  14549. inline void Client::enable_server_certificate_verification(bool enabled) {
  14550. cli_->enable_server_certificate_verification(enabled);
  14551. }
  14552. inline void Client::enable_server_hostname_verification(bool enabled) {
  14553. cli_->enable_server_hostname_verification(enabled);
  14554. }
  14555. #endif
  14556. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14557. inline void Client::set_server_certificate_verifier(
  14558. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  14559. cli_->set_server_certificate_verifier(verifier);
  14560. }
  14561. #endif
  14562. inline void Client::set_logger(Logger logger) {
  14563. cli_->set_logger(std::move(logger));
  14564. }
  14565. inline void Client::set_error_logger(ErrorLogger error_logger) {
  14566. cli_->set_error_logger(std::move(error_logger));
  14567. }
  14568. #ifdef CPPHTTPLIB_SSL_ENABLED
  14569. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14570. const std::string &ca_cert_dir_path) {
  14571. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14572. }
  14573. #endif
  14574. #ifdef CPPHTTPLIB_SSL_ENABLED
  14575. inline void Client::set_ca_cert_store(void *ca_cert_store) {
  14576. if (is_ssl_) {
  14577. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14578. } else if (ca_cert_store) {
  14579. detail::tls::tls_free_ca_store(ca_cert_store);
  14580. }
  14581. }
  14582. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14583. set_ca_cert_store(detail::tls::tls_create_ca_store(ca_cert, size));
  14584. }
  14585. inline void
  14586. Client::set_server_certificate_verifier(TlsVerifyCallback verifier) {
  14587. if (is_ssl_) {
  14588. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14589. std::move(verifier));
  14590. }
  14591. }
  14592. inline void *Client::tls_context() const {
  14593. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14594. return nullptr;
  14595. }
  14596. #endif
  14597. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14598. inline long Client::get_openssl_verify_result() const {
  14599. if (is_ssl_) {
  14600. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  14601. }
  14602. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  14603. }
  14604. inline SSL_CTX *Client::ssl_context() const {
  14605. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  14606. return nullptr;
  14607. }
  14608. #endif
  14609. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14610. inline mbedtls_ssl_config *Client::ssl_config() const {
  14611. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_config(); }
  14612. return nullptr;
  14613. }
  14614. #endif
  14615. // ----------------------------------------------------------------------------
  14616. } // namespace httplib
  14617. #endif // CPPHTTPLIB_HTTPLIB_H