httplib.h 571 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217
  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. bool has_header(const std::string &key) const;
  661. std::string get_header_value(const std::string &key, const char *def = "",
  662. size_t id = 0) const;
  663. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  664. size_t id = 0) const;
  665. size_t get_header_value_count(const std::string &key) const;
  666. void set_header(const std::string &key, const std::string &val);
  667. bool has_trailer(const std::string &key) const;
  668. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  669. size_t get_trailer_value_count(const std::string &key) const;
  670. bool has_param(const std::string &key) const;
  671. std::string get_param_value(const std::string &key, size_t id = 0) const;
  672. size_t get_param_value_count(const std::string &key) const;
  673. bool is_multipart_form_data() const;
  674. // private members...
  675. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  676. size_t content_length_ = 0;
  677. ContentProvider content_provider_;
  678. bool is_chunked_content_provider_ = false;
  679. size_t authorization_count_ = 0;
  680. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  681. (std::chrono::steady_clock::time_point::min)();
  682. #ifdef CPPHTTPLIB_SSL_ENABLED
  683. const void *ssl = nullptr; // tls_session_t (void*) - TLS session handle
  684. #endif
  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. // Response
  1145. operator bool() const { return res_ != nullptr; }
  1146. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1147. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1148. const Response &value() const { return *res_; }
  1149. Response &value() { return *res_; }
  1150. const Response &operator*() const { return *res_; }
  1151. Response &operator*() { return *res_; }
  1152. const Response *operator->() const { return res_.get(); }
  1153. Response *operator->() { return res_.get(); }
  1154. // Error
  1155. Error error() const { return err_; }
  1156. // Request Headers
  1157. bool has_request_header(const std::string &key) const;
  1158. std::string get_request_header_value(const std::string &key,
  1159. const char *def = "",
  1160. size_t id = 0) const;
  1161. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1162. size_t id = 0) const;
  1163. size_t get_request_header_value_count(const std::string &key) const;
  1164. private:
  1165. std::unique_ptr<Response> res_;
  1166. Error err_ = Error::Unknown;
  1167. Headers request_headers_;
  1168. #ifdef CPPHTTPLIB_SSL_ENABLED
  1169. public:
  1170. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1171. int ssl_error)
  1172. : res_(std::move(res)), err_(err),
  1173. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1174. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1175. int ssl_error, unsigned long ssl_backend_error)
  1176. : res_(std::move(res)), err_(err),
  1177. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1178. ssl_backend_error_(ssl_backend_error) {}
  1179. // SSL Error (backend-specific error code from handshake)
  1180. int ssl_error() const { return ssl_error_; }
  1181. // Backend-specific error code (OpenSSL: ERR_get_error(), Mbed TLS: mbedtls
  1182. // error code)
  1183. unsigned long ssl_backend_error() const { return ssl_backend_error_; }
  1184. private:
  1185. int ssl_error_ = 0;
  1186. unsigned long ssl_backend_error_ = 0;
  1187. #endif
  1188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1189. public:
  1190. // OpenSSL Error (alias for ssl_backend_error for backward compatibility)
  1191. unsigned long ssl_openssl_error() const { return ssl_backend_error_; }
  1192. #endif
  1193. };
  1194. struct ClientConnection {
  1195. socket_t sock = INVALID_SOCKET;
  1196. bool is_open() const { return sock != INVALID_SOCKET; }
  1197. ClientConnection() = default;
  1198. ~ClientConnection();
  1199. ClientConnection(const ClientConnection &) = delete;
  1200. ClientConnection &operator=(const ClientConnection &) = delete;
  1201. #ifndef CPPHTTPLIB_SSL_ENABLED
  1202. ClientConnection(ClientConnection &&other) noexcept : sock(other.sock) {
  1203. other.sock = INVALID_SOCKET;
  1204. }
  1205. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1206. if (this != &other) {
  1207. sock = other.sock;
  1208. other.sock = INVALID_SOCKET;
  1209. }
  1210. return *this;
  1211. }
  1212. #else
  1213. ClientConnection(ClientConnection &&other) noexcept
  1214. : sock(other.sock), session(other.session) {
  1215. other.sock = INVALID_SOCKET;
  1216. other.session = nullptr;
  1217. }
  1218. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1219. if (this != &other) {
  1220. sock = other.sock;
  1221. other.sock = INVALID_SOCKET;
  1222. session = other.session;
  1223. other.session = nullptr;
  1224. }
  1225. return *this;
  1226. }
  1227. // Use void* directly since tls::tls_session_t is not yet defined here
  1228. void *session = nullptr;
  1229. #endif
  1230. };
  1231. namespace detail {
  1232. struct ChunkedDecoder;
  1233. struct BodyReader {
  1234. Stream *stream = nullptr;
  1235. size_t content_length = 0;
  1236. size_t bytes_read = 0;
  1237. bool chunked = false;
  1238. bool eof = false;
  1239. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1240. Error last_error = Error::Success;
  1241. ssize_t read(char *buf, size_t len);
  1242. bool has_error() const { return last_error != Error::Success; }
  1243. };
  1244. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1245. size_t len) {
  1246. (void)stream;
  1247. return br.read(buf, len);
  1248. }
  1249. class decompressor;
  1250. } // namespace detail
  1251. class ClientImpl {
  1252. public:
  1253. explicit ClientImpl(const std::string &host);
  1254. explicit ClientImpl(const std::string &host, int port);
  1255. explicit ClientImpl(const std::string &host, int port,
  1256. const std::string &client_cert_path,
  1257. const std::string &client_key_path);
  1258. virtual ~ClientImpl();
  1259. virtual bool is_valid() const;
  1260. struct StreamHandle {
  1261. std::unique_ptr<Response> response;
  1262. Error error = Error::Success;
  1263. StreamHandle() = default;
  1264. StreamHandle(const StreamHandle &) = delete;
  1265. StreamHandle &operator=(const StreamHandle &) = delete;
  1266. StreamHandle(StreamHandle &&) = default;
  1267. StreamHandle &operator=(StreamHandle &&) = default;
  1268. ~StreamHandle() = default;
  1269. bool is_valid() const {
  1270. return response != nullptr && error == Error::Success;
  1271. }
  1272. ssize_t read(char *buf, size_t len);
  1273. void parse_trailers_if_needed();
  1274. Error get_read_error() const { return body_reader_.last_error; }
  1275. bool has_read_error() const { return body_reader_.has_error(); }
  1276. bool trailers_parsed_ = false;
  1277. private:
  1278. friend class ClientImpl;
  1279. ssize_t read_with_decompression(char *buf, size_t len);
  1280. std::unique_ptr<ClientConnection> connection_;
  1281. std::unique_ptr<Stream> socket_stream_;
  1282. Stream *stream_ = nullptr;
  1283. detail::BodyReader body_reader_;
  1284. std::unique_ptr<detail::decompressor> decompressor_;
  1285. std::string decompress_buffer_;
  1286. size_t decompress_offset_ = 0;
  1287. };
  1288. // clang-format off
  1289. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1290. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1291. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1292. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1293. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1294. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1295. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1296. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1297. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1298. Result Head(const std::string &path);
  1299. Result Head(const std::string &path, const Headers &headers);
  1300. Result Post(const std::string &path);
  1301. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1302. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1303. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1304. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1305. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1306. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1307. Result Post(const std::string &path, const Params &params);
  1308. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1309. Result Post(const std::string &path, const Headers &headers);
  1310. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1311. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1312. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1313. 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);
  1314. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1315. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1316. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1317. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1318. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1319. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1320. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1321. Result Put(const std::string &path);
  1322. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1323. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1324. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1325. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1326. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1327. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1328. Result Put(const std::string &path, const Params &params);
  1329. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1330. Result Put(const std::string &path, const Headers &headers);
  1331. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1332. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1333. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1334. 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);
  1335. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1336. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1337. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1338. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1339. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1340. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1341. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1342. Result Patch(const std::string &path);
  1343. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1344. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1345. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1346. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1347. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1348. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1349. Result Patch(const std::string &path, const Params &params);
  1350. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1351. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1352. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1353. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1354. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1355. 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);
  1356. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1357. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1358. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1359. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1360. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1361. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1362. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1363. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1364. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1365. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1366. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1367. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1368. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1369. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1370. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1371. Result Options(const std::string &path);
  1372. Result Options(const std::string &path, const Headers &headers);
  1373. // clang-format on
  1374. // Streaming API: Open a stream for reading response body incrementally
  1375. // Socket ownership is transferred to StreamHandle for true streaming
  1376. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1377. StreamHandle open_stream(const std::string &method, const std::string &path,
  1378. const Params &params = {},
  1379. const Headers &headers = {},
  1380. const std::string &body = {},
  1381. const std::string &content_type = {});
  1382. bool send(Request &req, Response &res, Error &error);
  1383. Result send(const Request &req);
  1384. void stop();
  1385. std::string host() const;
  1386. int port() const;
  1387. size_t is_socket_open() const;
  1388. socket_t socket() const;
  1389. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1390. void set_default_headers(Headers headers);
  1391. void
  1392. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1393. void set_address_family(int family);
  1394. void set_tcp_nodelay(bool on);
  1395. void set_ipv6_v6only(bool on);
  1396. void set_socket_options(SocketOptions socket_options);
  1397. void set_connection_timeout(time_t sec, time_t usec = 0);
  1398. template <class Rep, class Period>
  1399. void
  1400. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1401. void set_read_timeout(time_t sec, time_t usec = 0);
  1402. template <class Rep, class Period>
  1403. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1404. void set_write_timeout(time_t sec, time_t usec = 0);
  1405. template <class Rep, class Period>
  1406. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1407. void set_max_timeout(time_t msec);
  1408. template <class Rep, class Period>
  1409. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1410. void set_basic_auth(const std::string &username, const std::string &password);
  1411. void set_bearer_token_auth(const std::string &token);
  1412. void set_keep_alive(bool on);
  1413. void set_follow_location(bool on);
  1414. void set_path_encode(bool on);
  1415. void set_compress(bool on);
  1416. void set_decompress(bool on);
  1417. void set_interface(const std::string &intf);
  1418. void set_proxy(const std::string &host, int port);
  1419. void set_proxy_basic_auth(const std::string &username,
  1420. const std::string &password);
  1421. void set_proxy_bearer_token_auth(const std::string &token);
  1422. void set_logger(Logger logger);
  1423. void set_error_logger(ErrorLogger error_logger);
  1424. protected:
  1425. struct Socket {
  1426. socket_t sock = INVALID_SOCKET;
  1427. // For Mbed TLS compatibility: start_time for request timeout tracking
  1428. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1429. bool is_open() const { return sock != INVALID_SOCKET; }
  1430. #ifdef CPPHTTPLIB_SSL_ENABLED
  1431. // Use void* directly since tls::tls_session_t is not yet defined here
  1432. void *ssl = nullptr;
  1433. #endif
  1434. };
  1435. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1436. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1437. // All of:
  1438. // shutdown_ssl
  1439. // shutdown_socket
  1440. // close_socket
  1441. // should ONLY be called when socket_mutex_ is locked.
  1442. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1443. // with a DIFFERENT thread sending requests using that socket.
  1444. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1445. void shutdown_socket(Socket &socket) const;
  1446. void close_socket(Socket &socket);
  1447. bool process_request(Stream &strm, Request &req, Response &res,
  1448. bool close_connection, Error &error);
  1449. bool write_content_with_provider(Stream &strm, const Request &req,
  1450. Error &error) const;
  1451. void copy_settings(const ClientImpl &rhs);
  1452. void output_log(const Request &req, const Response &res) const;
  1453. void output_error_log(const Error &err, const Request *req) const;
  1454. // Socket endpoint information
  1455. const std::string host_;
  1456. const int port_;
  1457. // Current open socket
  1458. Socket socket_;
  1459. mutable std::mutex socket_mutex_;
  1460. std::recursive_mutex request_mutex_;
  1461. // These are all protected under socket_mutex
  1462. size_t socket_requests_in_flight_ = 0;
  1463. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1464. bool socket_should_be_closed_when_request_is_done_ = false;
  1465. // Hostname-IP map
  1466. std::map<std::string, std::string> addr_map_;
  1467. // Default headers
  1468. Headers default_headers_;
  1469. // Header writer
  1470. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1471. detail::write_headers;
  1472. // Settings
  1473. std::string client_cert_path_;
  1474. std::string client_key_path_;
  1475. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1476. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1477. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1478. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1479. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1480. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1481. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1482. std::string basic_auth_username_;
  1483. std::string basic_auth_password_;
  1484. std::string bearer_token_auth_token_;
  1485. bool keep_alive_ = false;
  1486. bool follow_location_ = false;
  1487. bool path_encode_ = true;
  1488. int address_family_ = AF_UNSPEC;
  1489. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1490. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1491. SocketOptions socket_options_ = nullptr;
  1492. bool compress_ = false;
  1493. bool decompress_ = true;
  1494. std::string interface_;
  1495. std::string proxy_host_;
  1496. int proxy_port_ = -1;
  1497. std::string proxy_basic_auth_username_;
  1498. std::string proxy_basic_auth_password_;
  1499. std::string proxy_bearer_token_auth_token_;
  1500. mutable std::mutex logger_mutex_;
  1501. Logger logger_;
  1502. ErrorLogger error_logger_;
  1503. private:
  1504. bool send_(Request &req, Response &res, Error &error);
  1505. Result send_(Request &&req);
  1506. socket_t create_client_socket(Error &error) const;
  1507. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1508. bool skip_100_continue = true) const;
  1509. bool write_request(Stream &strm, Request &req, bool close_connection,
  1510. Error &error, bool skip_body = false);
  1511. bool write_request_body(Stream &strm, Request &req, Error &error);
  1512. void prepare_default_headers(Request &r, bool for_stream,
  1513. const std::string &ct);
  1514. bool redirect(Request &req, Response &res, Error &error);
  1515. bool create_redirect_client(const std::string &scheme,
  1516. const std::string &host, int port, Request &req,
  1517. Response &res, const std::string &path,
  1518. const std::string &location, Error &error);
  1519. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1520. bool handle_request(Stream &strm, Request &req, Response &res,
  1521. bool close_connection, Error &error);
  1522. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1523. Request &req, const char *body, size_t content_length,
  1524. ContentProvider content_provider,
  1525. ContentProviderWithoutLength content_provider_without_length,
  1526. const std::string &content_type, ContentReceiver content_receiver,
  1527. Error &error);
  1528. Result send_with_content_provider_and_receiver(
  1529. const std::string &method, const std::string &path,
  1530. const Headers &headers, const char *body, size_t content_length,
  1531. ContentProvider content_provider,
  1532. ContentProviderWithoutLength content_provider_without_length,
  1533. const std::string &content_type, ContentReceiver content_receiver,
  1534. UploadProgress progress);
  1535. ContentProviderWithoutLength get_multipart_content_provider(
  1536. const std::string &boundary, const UploadFormDataItems &items,
  1537. const FormDataProviderItems &provider_items) const;
  1538. virtual bool
  1539. process_socket(const Socket &socket,
  1540. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1541. std::function<bool(Stream &strm)> callback);
  1542. virtual bool is_ssl() const;
  1543. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1544. #ifdef CPPHTTPLIB_SSL_ENABLED
  1545. public:
  1546. void set_digest_auth(const std::string &username,
  1547. const std::string &password);
  1548. void set_proxy_digest_auth(const std::string &username,
  1549. const std::string &password);
  1550. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1551. const std::string &ca_cert_dir_path = std::string());
  1552. void enable_server_certificate_verification(bool enabled);
  1553. void enable_server_hostname_verification(bool enabled);
  1554. protected:
  1555. std::string digest_auth_username_;
  1556. std::string digest_auth_password_;
  1557. std::string proxy_digest_auth_username_;
  1558. std::string proxy_digest_auth_password_;
  1559. std::string ca_cert_file_path_;
  1560. std::string ca_cert_dir_path_;
  1561. bool server_certificate_verification_ = true;
  1562. bool server_hostname_verification_ = true;
  1563. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  1564. int last_ssl_error_ = 0;
  1565. unsigned long last_backend_error_ = 0;
  1566. #endif
  1567. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1568. public:
  1569. [[deprecated("Use load_ca_cert_store() instead")]]
  1570. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1571. [[deprecated("Use tls::tls_create_ca_store() instead")]]
  1572. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1573. void set_server_certificate_verifier(
  1574. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1575. protected:
  1576. X509_STORE *ca_cert_store_ = nullptr;
  1577. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1578. #endif
  1579. };
  1580. class Client {
  1581. public:
  1582. // Universal interface
  1583. explicit Client(const std::string &scheme_host_port);
  1584. explicit Client(const std::string &scheme_host_port,
  1585. const std::string &client_cert_path,
  1586. const std::string &client_key_path);
  1587. // HTTP only interface
  1588. explicit Client(const std::string &host, int port);
  1589. explicit Client(const std::string &host, int port,
  1590. const std::string &client_cert_path,
  1591. const std::string &client_key_path);
  1592. Client(Client &&) = default;
  1593. Client &operator=(Client &&) = default;
  1594. ~Client();
  1595. bool is_valid() const;
  1596. // clang-format off
  1597. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1598. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1599. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1600. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1601. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1602. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1603. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1604. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1605. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1606. Result Head(const std::string &path);
  1607. Result Head(const std::string &path, const Headers &headers);
  1608. Result Post(const std::string &path);
  1609. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1610. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1611. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1612. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1613. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1614. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1615. Result Post(const std::string &path, const Params &params);
  1616. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1617. Result Post(const std::string &path, const Headers &headers);
  1618. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1619. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1620. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1621. 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);
  1622. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1623. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1624. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1625. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1626. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1627. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1628. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1629. Result Put(const std::string &path);
  1630. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1631. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1632. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1633. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1634. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1635. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1636. Result Put(const std::string &path, const Params &params);
  1637. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1638. Result Put(const std::string &path, const Headers &headers);
  1639. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1640. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1641. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1642. 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);
  1643. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1644. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1645. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1646. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1647. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1648. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1649. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1650. Result Patch(const std::string &path);
  1651. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1652. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1653. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1654. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1655. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1656. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1657. Result Patch(const std::string &path, const Params &params);
  1658. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1659. Result Patch(const std::string &path, const Headers &headers);
  1660. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1661. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1662. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1663. 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);
  1664. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1665. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1666. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1667. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1668. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1669. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1670. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1671. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1672. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1673. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1674. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1675. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1676. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1677. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1678. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1679. Result Options(const std::string &path);
  1680. Result Options(const std::string &path, const Headers &headers);
  1681. // clang-format on
  1682. // Streaming API: Open a stream for reading response body incrementally
  1683. // Socket ownership is transferred to StreamHandle for true streaming
  1684. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1685. ClientImpl::StreamHandle open_stream(const std::string &method,
  1686. const std::string &path,
  1687. const Params &params = {},
  1688. const Headers &headers = {},
  1689. const std::string &body = {},
  1690. const std::string &content_type = {});
  1691. bool send(Request &req, Response &res, Error &error);
  1692. Result send(const Request &req);
  1693. void stop();
  1694. std::string host() const;
  1695. int port() const;
  1696. size_t is_socket_open() const;
  1697. socket_t socket() const;
  1698. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1699. void set_default_headers(Headers headers);
  1700. void
  1701. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1702. void set_address_family(int family);
  1703. void set_tcp_nodelay(bool on);
  1704. void set_socket_options(SocketOptions socket_options);
  1705. void set_connection_timeout(time_t sec, time_t usec = 0);
  1706. template <class Rep, class Period>
  1707. void
  1708. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1709. void set_read_timeout(time_t sec, time_t usec = 0);
  1710. template <class Rep, class Period>
  1711. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1712. void set_write_timeout(time_t sec, time_t usec = 0);
  1713. template <class Rep, class Period>
  1714. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1715. void set_max_timeout(time_t msec);
  1716. template <class Rep, class Period>
  1717. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1718. void set_basic_auth(const std::string &username, const std::string &password);
  1719. void set_bearer_token_auth(const std::string &token);
  1720. void set_keep_alive(bool on);
  1721. void set_follow_location(bool on);
  1722. void set_path_encode(bool on);
  1723. void set_url_encode(bool on);
  1724. void set_compress(bool on);
  1725. void set_decompress(bool on);
  1726. void set_interface(const std::string &intf);
  1727. void set_proxy(const std::string &host, int port);
  1728. void set_proxy_basic_auth(const std::string &username,
  1729. const std::string &password);
  1730. void set_proxy_bearer_token_auth(const std::string &token);
  1731. void set_logger(Logger logger);
  1732. void set_error_logger(ErrorLogger error_logger);
  1733. private:
  1734. std::unique_ptr<ClientImpl> cli_;
  1735. #ifdef CPPHTTPLIB_SSL_ENABLED
  1736. public:
  1737. void set_digest_auth(const std::string &username,
  1738. const std::string &password);
  1739. void set_proxy_digest_auth(const std::string &username,
  1740. const std::string &password);
  1741. void enable_server_certificate_verification(bool enabled);
  1742. void enable_server_hostname_verification(bool enabled);
  1743. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1744. const std::string &ca_cert_dir_path = std::string());
  1745. // Use void* directly since tls::tls_ca_store_t is not yet defined here
  1746. void set_ca_cert_store(void *ca_cert_store);
  1747. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1748. // Custom certificate verification callback (works with all TLS backends)
  1749. // Callback receives session and peer certificate, returns true to accept
  1750. using TlsVerifyCallback = std::function<bool(void *session, void *peer_cert)>;
  1751. void set_server_certificate_verifier(TlsVerifyCallback verifier);
  1752. // Backend-agnostic TLS context accessor
  1753. void *tls_context() const;
  1754. private:
  1755. bool is_ssl_ = false;
  1756. #endif
  1757. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1758. public:
  1759. [[deprecated("Use tls_context() instead")]]
  1760. SSL_CTX *ssl_context() const;
  1761. void set_server_certificate_verifier(
  1762. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1763. long get_openssl_verify_result() const;
  1764. #endif
  1765. };
  1766. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  1767. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  1768. // cert/key). This struct is exposed for use in SSL context setup callbacks.
  1769. struct MbedTlsContext {
  1770. mbedtls_ssl_config conf;
  1771. mbedtls_entropy_context entropy;
  1772. mbedtls_ctr_drbg_context ctr_drbg;
  1773. mbedtls_x509_crt ca_chain;
  1774. mbedtls_x509_crt own_cert;
  1775. mbedtls_pk_context own_key;
  1776. bool is_server = false;
  1777. bool verify_client = false;
  1778. bool has_verify_callback = false;
  1779. MbedTlsContext();
  1780. ~MbedTlsContext();
  1781. // Non-copyable
  1782. MbedTlsContext(const MbedTlsContext &) = delete;
  1783. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  1784. };
  1785. #endif
  1786. #ifdef CPPHTTPLIB_SSL_ENABLED
  1787. class SSLServer : public Server {
  1788. public:
  1789. SSLServer(const char *cert_path, const char *private_key_path,
  1790. const char *client_ca_cert_file_path = nullptr,
  1791. const char *client_ca_cert_dir_path = nullptr,
  1792. const char *private_key_password = nullptr);
  1793. // PEM memory-based constructor (works with all TLS backends)
  1794. struct PemMemory {
  1795. const char *cert_pem;
  1796. size_t cert_pem_len;
  1797. const char *key_pem;
  1798. size_t key_pem_len;
  1799. const char *client_ca_pem;
  1800. size_t client_ca_pem_len;
  1801. const char *private_key_password;
  1802. };
  1803. explicit SSLServer(const PemMemory &pem);
  1804. // Backend-agnostic callback constructor
  1805. // The callback receives the opaque tls_ctx_t handle (void*) which can be
  1806. // cast to the appropriate backend type (SSL_CTX* for OpenSSL, MbedTlsContext*
  1807. // for mbedTLS)
  1808. explicit SSLServer(const std::function<bool(void *ctx)> &setup_callback);
  1809. ~SSLServer() override;
  1810. bool is_valid() const override;
  1811. // Update certificates from PEM strings (works with all TLS backends)
  1812. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  1813. const char *password = nullptr);
  1814. bool update_client_ca_pem(const char *ca_pem);
  1815. // Backend-agnostic TLS context accessor
  1816. void *tls_context() const { return ctx_; }
  1817. int ssl_last_error() const { return last_ssl_error_; }
  1818. private:
  1819. bool process_and_close_socket(socket_t sock) override;
  1820. // Use void* for tls_ctx_t to support all backends
  1821. void *ctx_ = nullptr;
  1822. std::mutex ctx_mutex_;
  1823. int last_ssl_error_ = 0;
  1824. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1825. public:
  1826. [[deprecated("Use SSLServer(PemMemory) or "
  1827. "SSLServer(std::function<bool(void*)>) instead")]]
  1828. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1829. X509_STORE *client_ca_cert_store = nullptr);
  1830. [[deprecated("Use SSLServer(std::function<bool(void*)>) instead")]]
  1831. SSLServer(
  1832. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1833. [[deprecated("Use tls_context() instead")]]
  1834. SSL_CTX *ssl_context() const;
  1835. [[deprecated("Use update_certs_pem() instead")]]
  1836. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1837. X509_STORE *client_ca_cert_store = nullptr);
  1838. #endif
  1839. };
  1840. class SSLClient final : public ClientImpl {
  1841. public:
  1842. explicit SSLClient(const std::string &host);
  1843. explicit SSLClient(const std::string &host, int port);
  1844. explicit SSLClient(const std::string &host, int port,
  1845. const std::string &client_cert_path,
  1846. const std::string &client_key_path,
  1847. const std::string &private_key_password = std::string());
  1848. // PEM memory-based constructor (works with all TLS backends)
  1849. struct PemMemory {
  1850. const char *cert_pem;
  1851. size_t cert_pem_len;
  1852. const char *key_pem;
  1853. size_t key_pem_len;
  1854. const char *private_key_password;
  1855. };
  1856. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  1857. ~SSLClient() override;
  1858. bool is_valid() const override;
  1859. // Use void* directly since tls::tls_ca_store_t is not yet defined here
  1860. void set_ca_cert_store(void *ca_cert_store);
  1861. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1862. // Custom certificate verification callback (works with all TLS backends)
  1863. // Callback receives session and peer certificate, returns true to accept
  1864. using TlsVerifyCallback = std::function<bool(void *session, void *peer_cert)>;
  1865. void set_server_certificate_verifier(TlsVerifyCallback verifier);
  1866. // Backend-agnostic TLS context accessor
  1867. void *tls_context() const { return ctx_; }
  1868. private:
  1869. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1870. bool ensure_socket_connection(Socket &socket, Error &error) override;
  1871. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1872. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1873. bool
  1874. process_socket(const Socket &socket,
  1875. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1876. std::function<bool(Stream &strm)> callback) override;
  1877. bool is_ssl() const override;
  1878. bool connect_with_proxy(
  1879. Socket &sock,
  1880. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1881. Response &res, bool &success, Error &error);
  1882. bool initialize_ssl(Socket &socket, Error &error);
  1883. bool load_certs();
  1884. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1885. // Use void* directly since tls::tls_ctx_t is not yet defined here
  1886. void *ctx_;
  1887. std::mutex ctx_mutex_;
  1888. std::once_flag initialize_cert_;
  1889. std::vector<std::string> host_components_;
  1890. long verify_result_ = 0;
  1891. friend class ClientImpl;
  1892. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1893. public:
  1894. [[deprecated("Use SSLClient(host, port, PemMemory) instead")]]
  1895. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1896. EVP_PKEY *client_key,
  1897. const std::string &private_key_password = std::string());
  1898. long get_openssl_verify_result() const;
  1899. [[deprecated("Use tls_context() instead")]]
  1900. SSL_CTX *ssl_context() const;
  1901. private:
  1902. bool verify_host(X509 *server_cert) const;
  1903. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1904. bool verify_host_with_common_name(X509 *server_cert) const;
  1905. #endif
  1906. };
  1907. #endif // CPPHTTPLIB_SSL_ENABLED
  1908. namespace detail {
  1909. template <typename T, typename U>
  1910. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1911. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1912. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1913. duration - std::chrono::seconds(sec))
  1914. .count();
  1915. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1916. }
  1917. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1918. return N - 1;
  1919. }
  1920. inline bool is_numeric(const std::string &str) {
  1921. return !str.empty() &&
  1922. std::all_of(str.cbegin(), str.cend(),
  1923. [](unsigned char c) { return std::isdigit(c); });
  1924. }
  1925. inline size_t get_header_value_u64(const Headers &headers,
  1926. const std::string &key, size_t def,
  1927. size_t id, bool &is_invalid_value) {
  1928. is_invalid_value = false;
  1929. auto rng = headers.equal_range(key);
  1930. auto it = rng.first;
  1931. std::advance(it, static_cast<ssize_t>(id));
  1932. if (it != rng.second) {
  1933. if (is_numeric(it->second)) {
  1934. return std::strtoull(it->second.data(), nullptr, 10);
  1935. } else {
  1936. is_invalid_value = true;
  1937. }
  1938. }
  1939. return def;
  1940. }
  1941. inline size_t get_header_value_u64(const Headers &headers,
  1942. const std::string &key, size_t def,
  1943. size_t id) {
  1944. auto dummy = false;
  1945. return get_header_value_u64(headers, key, def, id, dummy);
  1946. }
  1947. } // namespace detail
  1948. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  1949. size_t id) const {
  1950. return detail::get_header_value_u64(headers, key, def, id);
  1951. }
  1952. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  1953. size_t id) const {
  1954. return detail::get_header_value_u64(headers, key, def, id);
  1955. }
  1956. namespace detail {
  1957. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1958. const void *optval, socklen_t optlen) {
  1959. return setsockopt(sock, level, optname,
  1960. #ifdef _WIN32
  1961. reinterpret_cast<const char *>(optval),
  1962. #else
  1963. optval,
  1964. #endif
  1965. optlen) == 0;
  1966. }
  1967. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1968. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1969. }
  1970. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1971. time_t sec, time_t usec) {
  1972. #ifdef _WIN32
  1973. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1974. #else
  1975. timeval timeout;
  1976. timeout.tv_sec = static_cast<long>(sec);
  1977. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1978. #endif
  1979. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  1980. }
  1981. } // namespace detail
  1982. inline void default_socket_options(socket_t sock) {
  1983. detail::set_socket_opt(sock, SOL_SOCKET,
  1984. #ifdef SO_REUSEPORT
  1985. SO_REUSEPORT,
  1986. #else
  1987. SO_REUSEADDR,
  1988. #endif
  1989. 1);
  1990. }
  1991. inline std::string get_bearer_token_auth(const Request &req) {
  1992. if (req.has_header("Authorization")) {
  1993. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  1994. return req.get_header_value("Authorization")
  1995. .substr(bearer_header_prefix_len);
  1996. }
  1997. return "";
  1998. }
  1999. template <class Rep, class Period>
  2000. inline Server &
  2001. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2002. detail::duration_to_sec_and_usec(
  2003. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2004. return *this;
  2005. }
  2006. template <class Rep, class Period>
  2007. inline Server &
  2008. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2009. detail::duration_to_sec_and_usec(
  2010. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2011. return *this;
  2012. }
  2013. template <class Rep, class Period>
  2014. inline Server &
  2015. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2016. detail::duration_to_sec_and_usec(
  2017. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2018. return *this;
  2019. }
  2020. inline size_t Result::get_request_header_value_u64(const std::string &key,
  2021. size_t def,
  2022. size_t id) const {
  2023. return detail::get_header_value_u64(request_headers_, key, def, id);
  2024. }
  2025. template <class Rep, class Period>
  2026. inline void ClientImpl::set_connection_timeout(
  2027. const std::chrono::duration<Rep, Period> &duration) {
  2028. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2029. set_connection_timeout(sec, usec);
  2030. });
  2031. }
  2032. template <class Rep, class Period>
  2033. inline void ClientImpl::set_read_timeout(
  2034. const std::chrono::duration<Rep, Period> &duration) {
  2035. detail::duration_to_sec_and_usec(
  2036. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2037. }
  2038. template <class Rep, class Period>
  2039. inline void ClientImpl::set_write_timeout(
  2040. const std::chrono::duration<Rep, Period> &duration) {
  2041. detail::duration_to_sec_and_usec(
  2042. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2043. }
  2044. template <class Rep, class Period>
  2045. inline void ClientImpl::set_max_timeout(
  2046. const std::chrono::duration<Rep, Period> &duration) {
  2047. auto msec =
  2048. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2049. set_max_timeout(msec);
  2050. }
  2051. template <class Rep, class Period>
  2052. inline void Client::set_connection_timeout(
  2053. const std::chrono::duration<Rep, Period> &duration) {
  2054. cli_->set_connection_timeout(duration);
  2055. }
  2056. template <class Rep, class Period>
  2057. inline void
  2058. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2059. cli_->set_read_timeout(duration);
  2060. }
  2061. template <class Rep, class Period>
  2062. inline void
  2063. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2064. cli_->set_write_timeout(duration);
  2065. }
  2066. inline void Client::set_max_timeout(time_t msec) {
  2067. cli_->set_max_timeout(msec);
  2068. }
  2069. template <class Rep, class Period>
  2070. inline void
  2071. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2072. cli_->set_max_timeout(duration);
  2073. }
  2074. /*
  2075. * Forward declarations and types that will be part of the .h file if split into
  2076. * .h + .cc.
  2077. */
  2078. std::string hosted_at(const std::string &hostname);
  2079. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2080. // JavaScript-style URL encoding/decoding functions
  2081. std::string encode_uri_component(const std::string &value);
  2082. std::string encode_uri(const std::string &value);
  2083. std::string decode_uri_component(const std::string &value);
  2084. std::string decode_uri(const std::string &value);
  2085. // RFC 3986 compliant URL component encoding/decoding functions
  2086. std::string encode_path_component(const std::string &component);
  2087. std::string decode_path_component(const std::string &component);
  2088. std::string encode_query_component(const std::string &component,
  2089. bool space_as_plus = true);
  2090. std::string decode_query_component(const std::string &component,
  2091. bool plus_as_space = true);
  2092. std::string append_query_params(const std::string &path, const Params &params);
  2093. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2094. std::pair<std::string, std::string>
  2095. make_basic_authentication_header(const std::string &username,
  2096. const std::string &password,
  2097. bool is_proxy = false);
  2098. namespace detail {
  2099. #if defined(_WIN32)
  2100. inline std::wstring u8string_to_wstring(const char *s) {
  2101. if (!s) { return std::wstring(); }
  2102. auto len = static_cast<int>(strlen(s));
  2103. if (!len) { return std::wstring(); }
  2104. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2105. if (!wlen) { return std::wstring(); }
  2106. std::wstring ws;
  2107. ws.resize(wlen);
  2108. wlen = ::MultiByteToWideChar(
  2109. CP_UTF8, 0, s, len,
  2110. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2111. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2112. return ws;
  2113. }
  2114. #endif
  2115. struct FileStat {
  2116. FileStat(const std::string &path);
  2117. bool is_file() const;
  2118. bool is_dir() const;
  2119. time_t mtime() const;
  2120. size_t size() const;
  2121. private:
  2122. #if defined(_WIN32)
  2123. struct _stat st_;
  2124. #else
  2125. struct stat st_;
  2126. #endif
  2127. int ret_ = -1;
  2128. };
  2129. std::string make_host_and_port_string(const std::string &host, int port,
  2130. bool is_ssl);
  2131. std::string trim_copy(const std::string &s);
  2132. void divide(
  2133. const char *data, std::size_t size, char d,
  2134. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2135. fn);
  2136. void divide(
  2137. const std::string &str, char d,
  2138. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2139. fn);
  2140. void split(const char *b, const char *e, char d,
  2141. std::function<void(const char *, const char *)> fn);
  2142. void split(const char *b, const char *e, char d, size_t m,
  2143. std::function<void(const char *, const char *)> fn);
  2144. bool process_client_socket(
  2145. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2146. time_t write_timeout_sec, time_t write_timeout_usec,
  2147. time_t max_timeout_msec,
  2148. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2149. std::function<bool(Stream &)> callback);
  2150. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2151. int port, int address_family, bool tcp_nodelay,
  2152. bool ipv6_v6only, SocketOptions socket_options,
  2153. time_t connection_timeout_sec,
  2154. time_t connection_timeout_usec,
  2155. time_t read_timeout_sec, time_t read_timeout_usec,
  2156. time_t write_timeout_sec,
  2157. time_t write_timeout_usec,
  2158. const std::string &intf, Error &error);
  2159. const char *get_header_value(const Headers &headers, const std::string &key,
  2160. const char *def, size_t id);
  2161. std::string params_to_query_str(const Params &params);
  2162. void parse_query_text(const char *data, std::size_t size, Params &params);
  2163. void parse_query_text(const std::string &s, Params &params);
  2164. bool parse_multipart_boundary(const std::string &content_type,
  2165. std::string &boundary);
  2166. bool parse_range_header(const std::string &s, Ranges &ranges);
  2167. bool parse_accept_header(const std::string &s,
  2168. std::vector<std::string> &content_types);
  2169. int close_socket(socket_t sock);
  2170. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2171. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2172. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2173. EncodingType encoding_type(const Request &req, const Response &res);
  2174. class BufferStream final : public Stream {
  2175. public:
  2176. BufferStream() = default;
  2177. ~BufferStream() override = default;
  2178. bool is_readable() const override;
  2179. bool wait_readable() const override;
  2180. bool wait_writable() const override;
  2181. ssize_t read(char *ptr, size_t size) override;
  2182. ssize_t write(const char *ptr, size_t size) override;
  2183. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2184. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2185. socket_t socket() const override;
  2186. time_t duration() const override;
  2187. const std::string &get_buffer() const;
  2188. private:
  2189. std::string buffer;
  2190. size_t position = 0;
  2191. };
  2192. class compressor {
  2193. public:
  2194. virtual ~compressor() = default;
  2195. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2196. virtual bool compress(const char *data, size_t data_length, bool last,
  2197. Callback callback) = 0;
  2198. };
  2199. class decompressor {
  2200. public:
  2201. virtual ~decompressor() = default;
  2202. virtual bool is_valid() const = 0;
  2203. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2204. virtual bool decompress(const char *data, size_t data_length,
  2205. Callback callback) = 0;
  2206. };
  2207. class nocompressor final : public compressor {
  2208. public:
  2209. ~nocompressor() override = default;
  2210. bool compress(const char *data, size_t data_length, bool /*last*/,
  2211. Callback callback) override;
  2212. };
  2213. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2214. class gzip_compressor final : public compressor {
  2215. public:
  2216. gzip_compressor();
  2217. ~gzip_compressor() override;
  2218. bool compress(const char *data, size_t data_length, bool last,
  2219. Callback callback) override;
  2220. private:
  2221. bool is_valid_ = false;
  2222. z_stream strm_;
  2223. };
  2224. class gzip_decompressor final : public decompressor {
  2225. public:
  2226. gzip_decompressor();
  2227. ~gzip_decompressor() override;
  2228. bool is_valid() const override;
  2229. bool decompress(const char *data, size_t data_length,
  2230. Callback callback) override;
  2231. private:
  2232. bool is_valid_ = false;
  2233. z_stream strm_;
  2234. };
  2235. #endif
  2236. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2237. class brotli_compressor final : public compressor {
  2238. public:
  2239. brotli_compressor();
  2240. ~brotli_compressor();
  2241. bool compress(const char *data, size_t data_length, bool last,
  2242. Callback callback) override;
  2243. private:
  2244. BrotliEncoderState *state_ = nullptr;
  2245. };
  2246. class brotli_decompressor final : public decompressor {
  2247. public:
  2248. brotli_decompressor();
  2249. ~brotli_decompressor();
  2250. bool is_valid() const override;
  2251. bool decompress(const char *data, size_t data_length,
  2252. Callback callback) override;
  2253. private:
  2254. BrotliDecoderResult decoder_r;
  2255. BrotliDecoderState *decoder_s = nullptr;
  2256. };
  2257. #endif
  2258. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2259. class zstd_compressor : public compressor {
  2260. public:
  2261. zstd_compressor();
  2262. ~zstd_compressor();
  2263. bool compress(const char *data, size_t data_length, bool last,
  2264. Callback callback) override;
  2265. private:
  2266. ZSTD_CCtx *ctx_ = nullptr;
  2267. };
  2268. class zstd_decompressor : public decompressor {
  2269. public:
  2270. zstd_decompressor();
  2271. ~zstd_decompressor();
  2272. bool is_valid() const override;
  2273. bool decompress(const char *data, size_t data_length,
  2274. Callback callback) override;
  2275. private:
  2276. ZSTD_DCtx *ctx_ = nullptr;
  2277. };
  2278. #endif
  2279. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2280. // to store data. The call can set memory on stack for performance.
  2281. class stream_line_reader {
  2282. public:
  2283. stream_line_reader(Stream &strm, char *fixed_buffer,
  2284. size_t fixed_buffer_size);
  2285. const char *ptr() const;
  2286. size_t size() const;
  2287. bool end_with_crlf() const;
  2288. bool getline();
  2289. private:
  2290. void append(char c);
  2291. Stream &strm_;
  2292. char *fixed_buffer_;
  2293. const size_t fixed_buffer_size_;
  2294. size_t fixed_buffer_used_size_ = 0;
  2295. std::string growable_buffer_;
  2296. };
  2297. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2298. const Headers &src_headers);
  2299. struct ChunkedDecoder {
  2300. Stream &strm;
  2301. size_t chunk_remaining = 0;
  2302. bool finished = false;
  2303. char line_buf[64];
  2304. size_t last_chunk_total = 0;
  2305. size_t last_chunk_offset = 0;
  2306. explicit ChunkedDecoder(Stream &s);
  2307. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2308. size_t &out_chunk_total);
  2309. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2310. };
  2311. class mmap {
  2312. public:
  2313. mmap(const char *path);
  2314. ~mmap();
  2315. bool open(const char *path);
  2316. void close();
  2317. bool is_open() const;
  2318. size_t size() const;
  2319. const char *data() const;
  2320. private:
  2321. #if defined(_WIN32)
  2322. HANDLE hFile_ = NULL;
  2323. HANDLE hMapping_ = NULL;
  2324. #else
  2325. int fd_ = -1;
  2326. #endif
  2327. size_t size_ = 0;
  2328. void *addr_ = nullptr;
  2329. bool is_open_empty_file = false;
  2330. };
  2331. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2332. namespace fields {
  2333. bool is_token_char(char c);
  2334. bool is_token(const std::string &s);
  2335. bool is_field_name(const std::string &s);
  2336. bool is_vchar(char c);
  2337. bool is_obs_text(char c);
  2338. bool is_field_vchar(char c);
  2339. bool is_field_content(const std::string &s);
  2340. bool is_field_value(const std::string &s);
  2341. } // namespace fields
  2342. } // namespace detail
  2343. /*
  2344. * TLS Abstraction Layer Declarations
  2345. */
  2346. #ifdef CPPHTTPLIB_SSL_ENABLED
  2347. // Crypto abstraction layer
  2348. namespace crypto {
  2349. // Hash algorithm enumeration
  2350. enum class HashAlgorithm { MD5, SHA1, SHA256, SHA384, SHA512 };
  2351. // Compute hash of data, returns hex-encoded string
  2352. std::string hash(HashAlgorithm algo, const void *data, size_t len);
  2353. std::string hash(HashAlgorithm algo, const std::string &data);
  2354. // Compute hash of data, returns raw bytes
  2355. bool hash_raw(HashAlgorithm algo, const void *data, size_t len,
  2356. std::vector<uint8_t> &digest);
  2357. // Get digest size in bytes for algorithm
  2358. size_t hash_size(HashAlgorithm algo);
  2359. } // namespace crypto
  2360. // TLS abstraction layer
  2361. namespace tls {
  2362. // Error codes for TLS operations (backend-independent)
  2363. enum class ErrorCode : int {
  2364. Success = 0,
  2365. WantRead, // Non-blocking: need to wait for read
  2366. WantWrite, // Non-blocking: need to wait for write
  2367. PeerClosed, // Peer closed the connection
  2368. Fatal, // Unrecoverable error
  2369. SyscallError, // System call error (check sys_errno)
  2370. CertVerifyFailed, // Certificate verification failed
  2371. HostnameMismatch, // Hostname verification failed
  2372. };
  2373. // TLS error information
  2374. struct TlsError {
  2375. ErrorCode code = ErrorCode::Fatal;
  2376. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  2377. int sys_errno = 0; // errno when SyscallError
  2378. };
  2379. // Opaque handles (defined as void* for abstraction)
  2380. using tls_ctx_t = void *;
  2381. using tls_session_t = void *;
  2382. using tls_cert_t = void *;
  2383. using tls_ca_store_t = void *;
  2384. // Global initialization
  2385. bool tls_global_init();
  2386. void tls_global_cleanup();
  2387. // Client context
  2388. tls_ctx_t tls_create_client_context();
  2389. void tls_free_context(tls_ctx_t ctx);
  2390. bool tls_set_min_version(tls_ctx_t ctx, int version);
  2391. bool tls_load_ca_pem(tls_ctx_t ctx, const char *pem, size_t len);
  2392. bool tls_load_ca_file(tls_ctx_t ctx, const char *file_path);
  2393. bool tls_load_ca_dir(tls_ctx_t ctx, const char *dir_path);
  2394. bool tls_load_system_certs(tls_ctx_t ctx);
  2395. bool tls_set_client_cert_pem(tls_ctx_t ctx, const char *cert, const char *key,
  2396. const char *password);
  2397. bool tls_set_client_cert_file(tls_ctx_t ctx, const char *cert_path,
  2398. const char *key_path, const char *password);
  2399. // Server context
  2400. tls_ctx_t tls_create_server_context();
  2401. bool tls_set_server_cert_pem(tls_ctx_t ctx, const char *cert, const char *key,
  2402. const char *password);
  2403. bool tls_set_server_cert_file(tls_ctx_t ctx, const char *cert_path,
  2404. const char *key_path, const char *password);
  2405. bool tls_set_client_ca_file(tls_ctx_t ctx, const char *ca_file,
  2406. const char *ca_dir);
  2407. void tls_set_verify_client(tls_ctx_t ctx, bool require);
  2408. // Session management
  2409. tls_session_t tls_create_session(tls_ctx_t ctx, socket_t sock);
  2410. void tls_free_session(tls_session_t session);
  2411. bool tls_set_sni(tls_session_t session, const char *hostname);
  2412. bool tls_set_hostname(tls_session_t session, const char *hostname);
  2413. // Handshake (non-blocking capable)
  2414. TlsError tls_connect(tls_session_t session);
  2415. TlsError tls_accept(tls_session_t session);
  2416. // Handshake with timeout (blocking until timeout)
  2417. bool tls_connect_nonblocking(tls_session_t session, socket_t sock,
  2418. time_t timeout_sec, time_t timeout_usec,
  2419. TlsError *err);
  2420. bool tls_accept_nonblocking(tls_session_t session, socket_t sock,
  2421. time_t timeout_sec, time_t timeout_usec,
  2422. TlsError *err);
  2423. // I/O (non-blocking capable)
  2424. ssize_t tls_read(tls_session_t session, void *buf, size_t len, TlsError &err);
  2425. ssize_t tls_write(tls_session_t session, const void *buf, size_t len,
  2426. TlsError &err);
  2427. int tls_pending(tls_session_t session);
  2428. void tls_shutdown(tls_session_t session, bool graceful);
  2429. // Connection state
  2430. bool tls_is_peer_closed(tls_session_t session, socket_t sock);
  2431. // Certificate verification
  2432. tls_cert_t tls_get_peer_cert(tls_session_t session);
  2433. void tls_free_cert(tls_cert_t cert);
  2434. bool tls_verify_hostname(tls_cert_t cert, const char *hostname);
  2435. long tls_get_verify_result(tls_session_t session);
  2436. // Certificate introspection
  2437. std::string tls_get_cert_subject_cn(tls_cert_t cert);
  2438. std::string tls_get_cert_issuer_name(tls_cert_t cert);
  2439. // Subject Alternative Names (SAN) entry types
  2440. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  2441. // SAN entry structure
  2442. struct TlsSanEntry {
  2443. SanType type;
  2444. std::string value;
  2445. };
  2446. // Get Subject Alternative Names from certificate
  2447. bool tls_get_cert_sans(tls_cert_t cert, std::vector<TlsSanEntry> &sans);
  2448. // Get certificate validity period (Unix timestamps)
  2449. bool tls_get_cert_validity(tls_cert_t cert, time_t &not_before,
  2450. time_t &not_after);
  2451. // Get certificate serial number as hex string
  2452. std::string tls_get_cert_serial(tls_cert_t cert);
  2453. // SNI (Server Name Indication)
  2454. // Returns the SNI hostname from the TLS session, or empty string if not set
  2455. const char *tls_get_sni(tls_session_t session);
  2456. // CA store management
  2457. tls_ca_store_t tls_create_ca_store(const char *pem, size_t len);
  2458. void tls_free_ca_store(tls_ca_store_t store);
  2459. bool tls_set_ca_store(tls_ctx_t ctx, tls_ca_store_t store);
  2460. // Get list of CA certificates from store (returns count, fills certs vector)
  2461. // Caller must call tls_free_cert() on each certificate when done
  2462. size_t tls_get_ca_certs(tls_ctx_t ctx, std::vector<tls_cert_t> &certs);
  2463. // Get list of CA subject names from context (for client certificate request)
  2464. // Returns vector of subject name strings
  2465. std::vector<std::string> tls_get_ca_names(tls_ctx_t ctx);
  2466. // Dynamic certificate update (for servers)
  2467. bool tls_update_server_cert(tls_ctx_t ctx, const char *cert_pem,
  2468. const char *key_pem, const char *password);
  2469. bool tls_update_server_client_ca(tls_ctx_t ctx, const char *ca_pem);
  2470. // Custom certificate verification callback
  2471. // Returns true to accept the certificate, false to reject
  2472. using TlsVerifyCallback =
  2473. std::function<bool(tls_session_t session, tls_cert_t peer_cert)>;
  2474. bool tls_set_verify_callback(tls_ctx_t ctx, TlsVerifyCallback callback);
  2475. // Extended verification context for detailed callback
  2476. struct TlsVerifyContext {
  2477. tls_session_t session; // TLS session handle
  2478. tls_cert_t cert; // Current certificate being verified
  2479. int depth; // Certificate chain depth (0 = leaf)
  2480. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  2481. long error_code; // Backend-specific error code (0 = no error)
  2482. const char *error_string; // Human-readable error description
  2483. };
  2484. // Extended verification callback with full context
  2485. using TlsVerifyCallbackEx = std::function<bool(const TlsVerifyContext &ctx)>;
  2486. bool tls_set_verify_callback_ex(tls_ctx_t ctx, TlsVerifyCallbackEx callback);
  2487. // Get verification error code from session (after handshake)
  2488. long tls_get_verify_error(tls_session_t session);
  2489. // Convert verification error code to string
  2490. std::string tls_verify_error_string(long error_code);
  2491. // Error information
  2492. uint64_t tls_peek_error();
  2493. uint64_t tls_get_error();
  2494. std::string tls_error_string(uint64_t code);
  2495. } // namespace tls
  2496. #endif // CPPHTTPLIB_SSL_ENABLED
  2497. namespace detail {
  2498. #ifdef CPPHTTPLIB_SSL_ENABLED
  2499. // Utility function for SSL implementation
  2500. bool is_ip_address(const std::string &host);
  2501. #endif // CPPHTTPLIB_SSL_ENABLED
  2502. } // namespace detail
  2503. namespace stream {
  2504. class Result {
  2505. public:
  2506. Result() : chunk_size_(8192) {}
  2507. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192)
  2508. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  2509. Result(Result &&other) noexcept
  2510. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  2511. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  2512. finished_(other.finished_) {
  2513. other.current_size_ = 0;
  2514. other.finished_ = true;
  2515. }
  2516. Result &operator=(Result &&other) noexcept {
  2517. if (this != &other) {
  2518. handle_ = std::move(other.handle_);
  2519. buffer_ = std::move(other.buffer_);
  2520. current_size_ = other.current_size_;
  2521. chunk_size_ = other.chunk_size_;
  2522. finished_ = other.finished_;
  2523. other.current_size_ = 0;
  2524. other.finished_ = true;
  2525. }
  2526. return *this;
  2527. }
  2528. Result(const Result &) = delete;
  2529. Result &operator=(const Result &) = delete;
  2530. // Check if the result is valid (connection succeeded and response received)
  2531. bool is_valid() const { return handle_.is_valid(); }
  2532. explicit operator bool() const { return is_valid(); }
  2533. // Response status code
  2534. int status() const {
  2535. return handle_.response ? handle_.response->status : -1;
  2536. }
  2537. // Response headers
  2538. const Headers &headers() const {
  2539. static const Headers empty_headers;
  2540. return handle_.response ? handle_.response->headers : empty_headers;
  2541. }
  2542. std::string get_header_value(const std::string &key,
  2543. const char *def = "") const {
  2544. return handle_.response ? handle_.response->get_header_value(key, def)
  2545. : def;
  2546. }
  2547. bool has_header(const std::string &key) const {
  2548. return handle_.response ? handle_.response->has_header(key) : false;
  2549. }
  2550. // Error information
  2551. Error error() const { return handle_.error; }
  2552. Error read_error() const { return handle_.get_read_error(); }
  2553. bool has_read_error() const { return handle_.has_read_error(); }
  2554. // Streaming iteration API
  2555. // Call next() to read the next chunk, then access data via data()/size()
  2556. // Returns true if data was read, false when stream is exhausted
  2557. bool next() {
  2558. if (!handle_.is_valid() || finished_) { return false; }
  2559. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  2560. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  2561. if (n > 0) {
  2562. current_size_ = static_cast<size_t>(n);
  2563. return true;
  2564. }
  2565. current_size_ = 0;
  2566. finished_ = true;
  2567. return false;
  2568. }
  2569. // Pointer to current chunk data (valid after next() returns true)
  2570. const char *data() const { return buffer_.data(); }
  2571. // Size of current chunk (valid after next() returns true)
  2572. size_t size() const { return current_size_; }
  2573. // Convenience method: read all remaining data into a string
  2574. std::string read_all() {
  2575. std::string result;
  2576. while (next()) {
  2577. result.append(data(), size());
  2578. }
  2579. return result;
  2580. }
  2581. private:
  2582. ClientImpl::StreamHandle handle_;
  2583. std::string buffer_;
  2584. size_t current_size_ = 0;
  2585. size_t chunk_size_;
  2586. bool finished_ = false;
  2587. };
  2588. // GET
  2589. template <typename ClientType>
  2590. inline Result Get(ClientType &cli, const std::string &path,
  2591. size_t chunk_size = 8192) {
  2592. return Result{cli.open_stream("GET", path), chunk_size};
  2593. }
  2594. template <typename ClientType>
  2595. inline Result Get(ClientType &cli, const std::string &path,
  2596. const Headers &headers, size_t chunk_size = 8192) {
  2597. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2598. }
  2599. template <typename ClientType>
  2600. inline Result Get(ClientType &cli, const std::string &path,
  2601. const Params &params, size_t chunk_size = 8192) {
  2602. return Result{cli.open_stream("GET", path, params), chunk_size};
  2603. }
  2604. template <typename ClientType>
  2605. inline Result Get(ClientType &cli, const std::string &path,
  2606. const Params &params, const Headers &headers,
  2607. size_t chunk_size = 8192) {
  2608. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2609. }
  2610. // POST
  2611. template <typename ClientType>
  2612. inline Result Post(ClientType &cli, const std::string &path,
  2613. const std::string &body, const std::string &content_type,
  2614. size_t chunk_size = 8192) {
  2615. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2616. chunk_size};
  2617. }
  2618. template <typename ClientType>
  2619. inline Result Post(ClientType &cli, const std::string &path,
  2620. const Headers &headers, const std::string &body,
  2621. const std::string &content_type, size_t chunk_size = 8192) {
  2622. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2623. chunk_size};
  2624. }
  2625. template <typename ClientType>
  2626. inline Result Post(ClientType &cli, const std::string &path,
  2627. const Params &params, const std::string &body,
  2628. const std::string &content_type, size_t chunk_size = 8192) {
  2629. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2630. chunk_size};
  2631. }
  2632. template <typename ClientType>
  2633. inline Result Post(ClientType &cli, const std::string &path,
  2634. const Params &params, const Headers &headers,
  2635. const std::string &body, const std::string &content_type,
  2636. size_t chunk_size = 8192) {
  2637. return Result{
  2638. cli.open_stream("POST", path, params, headers, body, content_type),
  2639. chunk_size};
  2640. }
  2641. // PUT
  2642. template <typename ClientType>
  2643. inline Result Put(ClientType &cli, const std::string &path,
  2644. const std::string &body, const std::string &content_type,
  2645. size_t chunk_size = 8192) {
  2646. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2647. chunk_size};
  2648. }
  2649. template <typename ClientType>
  2650. inline Result Put(ClientType &cli, const std::string &path,
  2651. const Headers &headers, const std::string &body,
  2652. const std::string &content_type, size_t chunk_size = 8192) {
  2653. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2654. chunk_size};
  2655. }
  2656. template <typename ClientType>
  2657. inline Result Put(ClientType &cli, const std::string &path,
  2658. const Params &params, const std::string &body,
  2659. const std::string &content_type, size_t chunk_size = 8192) {
  2660. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2661. chunk_size};
  2662. }
  2663. template <typename ClientType>
  2664. inline Result Put(ClientType &cli, const std::string &path,
  2665. const Params &params, const Headers &headers,
  2666. const std::string &body, const std::string &content_type,
  2667. size_t chunk_size = 8192) {
  2668. return Result{
  2669. cli.open_stream("PUT", path, params, headers, body, content_type),
  2670. chunk_size};
  2671. }
  2672. // PATCH
  2673. template <typename ClientType>
  2674. inline Result Patch(ClientType &cli, const std::string &path,
  2675. const std::string &body, const std::string &content_type,
  2676. size_t chunk_size = 8192) {
  2677. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2678. chunk_size};
  2679. }
  2680. template <typename ClientType>
  2681. inline Result Patch(ClientType &cli, const std::string &path,
  2682. const Headers &headers, const std::string &body,
  2683. const std::string &content_type, size_t chunk_size = 8192) {
  2684. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2685. chunk_size};
  2686. }
  2687. template <typename ClientType>
  2688. inline Result Patch(ClientType &cli, const std::string &path,
  2689. const Params &params, const std::string &body,
  2690. const std::string &content_type, size_t chunk_size = 8192) {
  2691. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2692. chunk_size};
  2693. }
  2694. template <typename ClientType>
  2695. inline Result Patch(ClientType &cli, const std::string &path,
  2696. const Params &params, const Headers &headers,
  2697. const std::string &body, const std::string &content_type,
  2698. size_t chunk_size = 8192) {
  2699. return Result{
  2700. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2701. chunk_size};
  2702. }
  2703. // DELETE
  2704. template <typename ClientType>
  2705. inline Result Delete(ClientType &cli, const std::string &path,
  2706. size_t chunk_size = 8192) {
  2707. return Result{cli.open_stream("DELETE", path), chunk_size};
  2708. }
  2709. template <typename ClientType>
  2710. inline Result Delete(ClientType &cli, const std::string &path,
  2711. const Headers &headers, size_t chunk_size = 8192) {
  2712. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2713. }
  2714. template <typename ClientType>
  2715. inline Result Delete(ClientType &cli, const std::string &path,
  2716. const std::string &body, const std::string &content_type,
  2717. size_t chunk_size = 8192) {
  2718. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2719. chunk_size};
  2720. }
  2721. template <typename ClientType>
  2722. inline Result Delete(ClientType &cli, const std::string &path,
  2723. const Headers &headers, const std::string &body,
  2724. const std::string &content_type,
  2725. size_t chunk_size = 8192) {
  2726. return Result{
  2727. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2728. chunk_size};
  2729. }
  2730. template <typename ClientType>
  2731. inline Result Delete(ClientType &cli, const std::string &path,
  2732. const Params &params, size_t chunk_size = 8192) {
  2733. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2734. }
  2735. template <typename ClientType>
  2736. inline Result Delete(ClientType &cli, const std::string &path,
  2737. const Params &params, const Headers &headers,
  2738. size_t chunk_size = 8192) {
  2739. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2740. }
  2741. template <typename ClientType>
  2742. inline Result Delete(ClientType &cli, const std::string &path,
  2743. const Params &params, const std::string &body,
  2744. const std::string &content_type,
  2745. size_t chunk_size = 8192) {
  2746. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2747. chunk_size};
  2748. }
  2749. template <typename ClientType>
  2750. inline Result Delete(ClientType &cli, const std::string &path,
  2751. const Params &params, const Headers &headers,
  2752. const std::string &body, const std::string &content_type,
  2753. size_t chunk_size = 8192) {
  2754. return Result{
  2755. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2756. chunk_size};
  2757. }
  2758. // HEAD
  2759. template <typename ClientType>
  2760. inline Result Head(ClientType &cli, const std::string &path,
  2761. size_t chunk_size = 8192) {
  2762. return Result{cli.open_stream("HEAD", path), chunk_size};
  2763. }
  2764. template <typename ClientType>
  2765. inline Result Head(ClientType &cli, const std::string &path,
  2766. const Headers &headers, size_t chunk_size = 8192) {
  2767. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2768. }
  2769. template <typename ClientType>
  2770. inline Result Head(ClientType &cli, const std::string &path,
  2771. const Params &params, size_t chunk_size = 8192) {
  2772. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2773. }
  2774. template <typename ClientType>
  2775. inline Result Head(ClientType &cli, const std::string &path,
  2776. const Params &params, const Headers &headers,
  2777. size_t chunk_size = 8192) {
  2778. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2779. }
  2780. // OPTIONS
  2781. template <typename ClientType>
  2782. inline Result Options(ClientType &cli, const std::string &path,
  2783. size_t chunk_size = 8192) {
  2784. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2785. }
  2786. template <typename ClientType>
  2787. inline Result Options(ClientType &cli, const std::string &path,
  2788. const Headers &headers, size_t chunk_size = 8192) {
  2789. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2790. }
  2791. template <typename ClientType>
  2792. inline Result Options(ClientType &cli, const std::string &path,
  2793. const Params &params, size_t chunk_size = 8192) {
  2794. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2795. }
  2796. template <typename ClientType>
  2797. inline Result Options(ClientType &cli, const std::string &path,
  2798. const Params &params, const Headers &headers,
  2799. size_t chunk_size = 8192) {
  2800. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2801. }
  2802. } // namespace stream
  2803. namespace sse {
  2804. struct SSEMessage {
  2805. std::string event; // Event type (default: "message")
  2806. std::string data; // Event payload
  2807. std::string id; // Event ID for Last-Event-ID header
  2808. SSEMessage() : event("message") {}
  2809. void clear() {
  2810. event = "message";
  2811. data.clear();
  2812. id.clear();
  2813. }
  2814. };
  2815. class SSEClient {
  2816. public:
  2817. using MessageHandler = std::function<void(const SSEMessage &)>;
  2818. using ErrorHandler = std::function<void(Error)>;
  2819. using OpenHandler = std::function<void()>;
  2820. SSEClient(Client &client, const std::string &path)
  2821. : client_(client), path_(path) {}
  2822. SSEClient(Client &client, const std::string &path, const Headers &headers)
  2823. : client_(client), path_(path), headers_(headers) {}
  2824. ~SSEClient() { stop(); }
  2825. SSEClient(const SSEClient &) = delete;
  2826. SSEClient &operator=(const SSEClient &) = delete;
  2827. // Event handlers
  2828. SSEClient &on_message(MessageHandler handler) {
  2829. on_message_ = std::move(handler);
  2830. return *this;
  2831. }
  2832. SSEClient &on_event(const std::string &type, MessageHandler handler) {
  2833. event_handlers_[type] = std::move(handler);
  2834. return *this;
  2835. }
  2836. SSEClient &on_open(OpenHandler handler) {
  2837. on_open_ = std::move(handler);
  2838. return *this;
  2839. }
  2840. SSEClient &on_error(ErrorHandler handler) {
  2841. on_error_ = std::move(handler);
  2842. return *this;
  2843. }
  2844. SSEClient &set_reconnect_interval(int ms) {
  2845. reconnect_interval_ms_ = ms;
  2846. return *this;
  2847. }
  2848. SSEClient &set_max_reconnect_attempts(int n) {
  2849. max_reconnect_attempts_ = n;
  2850. return *this;
  2851. }
  2852. // State accessors
  2853. bool is_connected() const { return connected_.load(); }
  2854. const std::string &last_event_id() const { return last_event_id_; }
  2855. // Blocking start - runs event loop with auto-reconnect
  2856. void start() {
  2857. running_.store(true);
  2858. run_event_loop();
  2859. }
  2860. // Non-blocking start - runs in background thread
  2861. void start_async() {
  2862. running_.store(true);
  2863. async_thread_ = std::thread([this]() { run_event_loop(); });
  2864. }
  2865. // Stop the client (thread-safe)
  2866. void stop() {
  2867. running_.store(false);
  2868. client_.stop(); // Cancel any pending operations
  2869. if (async_thread_.joinable()) { async_thread_.join(); }
  2870. }
  2871. private:
  2872. // Parse a single SSE field line
  2873. // Returns true if this line ends an event (blank line)
  2874. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms) {
  2875. // Blank line signals end of event
  2876. if (line.empty() || line == "\r") { return true; }
  2877. // Lines starting with ':' are comments (ignored)
  2878. if (!line.empty() && line[0] == ':') { return false; }
  2879. // Find the colon separator
  2880. auto colon_pos = line.find(':');
  2881. if (colon_pos == std::string::npos) {
  2882. // Line with no colon is treated as field name with empty value
  2883. return false;
  2884. }
  2885. auto field = line.substr(0, colon_pos);
  2886. std::string value;
  2887. // Value starts after colon, skip optional single space
  2888. if (colon_pos + 1 < line.size()) {
  2889. auto value_start = colon_pos + 1;
  2890. if (line[value_start] == ' ') { value_start++; }
  2891. value = line.substr(value_start);
  2892. // Remove trailing \r if present
  2893. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  2894. }
  2895. // Handle known fields
  2896. if (field == "event") {
  2897. msg.event = value;
  2898. } else if (field == "data") {
  2899. // Multiple data lines are concatenated with newlines
  2900. if (!msg.data.empty()) { msg.data += "\n"; }
  2901. msg.data += value;
  2902. } else if (field == "id") {
  2903. // Empty id is valid (clears the last event ID)
  2904. msg.id = value;
  2905. } else if (field == "retry") {
  2906. // Parse retry interval in milliseconds
  2907. try {
  2908. retry_ms = std::stoi(value);
  2909. } catch (...) {
  2910. // Invalid retry value, ignore
  2911. }
  2912. }
  2913. // Unknown fields are ignored per SSE spec
  2914. return false;
  2915. }
  2916. // Main event loop with auto-reconnect
  2917. void run_event_loop() {
  2918. auto reconnect_count = 0;
  2919. while (running_.load()) {
  2920. // Build headers, including Last-Event-ID if we have one
  2921. auto request_headers = headers_;
  2922. if (!last_event_id_.empty()) {
  2923. request_headers.emplace("Last-Event-ID", last_event_id_);
  2924. }
  2925. // Open streaming connection
  2926. auto result = stream::Get(client_, path_, request_headers);
  2927. // Connection error handling
  2928. if (!result) {
  2929. connected_.store(false);
  2930. if (on_error_) { on_error_(result.error()); }
  2931. if (!should_reconnect(reconnect_count)) { break; }
  2932. wait_for_reconnect();
  2933. reconnect_count++;
  2934. continue;
  2935. }
  2936. if (result.status() != 200) {
  2937. connected_.store(false);
  2938. // For certain errors, don't reconnect
  2939. if (result.status() == 204 || // No Content - server wants us to stop
  2940. result.status() == 404 || // Not Found
  2941. result.status() == 401 || // Unauthorized
  2942. result.status() == 403) { // Forbidden
  2943. if (on_error_) { on_error_(Error::Connection); }
  2944. break;
  2945. }
  2946. if (on_error_) { on_error_(Error::Connection); }
  2947. if (!should_reconnect(reconnect_count)) { break; }
  2948. wait_for_reconnect();
  2949. reconnect_count++;
  2950. continue;
  2951. }
  2952. // Connection successful
  2953. connected_.store(true);
  2954. reconnect_count = 0;
  2955. if (on_open_) { on_open_(); }
  2956. // Event receiving loop
  2957. std::string buffer;
  2958. SSEMessage current_msg;
  2959. while (running_.load() && result.next()) {
  2960. buffer.append(result.data(), result.size());
  2961. // Process complete lines in the buffer
  2962. size_t line_start = 0;
  2963. size_t newline_pos;
  2964. while ((newline_pos = buffer.find('\n', line_start)) !=
  2965. std::string::npos) {
  2966. auto line = buffer.substr(line_start, newline_pos - line_start);
  2967. line_start = newline_pos + 1;
  2968. // Parse the line and check if event is complete
  2969. auto event_complete =
  2970. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  2971. if (event_complete && !current_msg.data.empty()) {
  2972. // Update last_event_id for reconnection
  2973. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  2974. // Dispatch event to appropriate handler
  2975. dispatch_event(current_msg);
  2976. current_msg.clear();
  2977. }
  2978. }
  2979. // Keep unprocessed data in buffer
  2980. buffer.erase(0, line_start);
  2981. }
  2982. // Connection ended
  2983. connected_.store(false);
  2984. if (!running_.load()) { break; }
  2985. // Check for read errors
  2986. if (result.has_read_error()) {
  2987. if (on_error_) { on_error_(result.read_error()); }
  2988. }
  2989. if (!should_reconnect(reconnect_count)) { break; }
  2990. wait_for_reconnect();
  2991. reconnect_count++;
  2992. }
  2993. connected_.store(false);
  2994. }
  2995. // Dispatch event to appropriate handler
  2996. void dispatch_event(const SSEMessage &msg) {
  2997. // Check for specific event type handler first
  2998. auto it = event_handlers_.find(msg.event);
  2999. if (it != event_handlers_.end()) {
  3000. it->second(msg);
  3001. return;
  3002. }
  3003. // Fall back to generic message handler
  3004. if (on_message_) { on_message_(msg); }
  3005. }
  3006. // Check if we should attempt to reconnect
  3007. bool should_reconnect(int count) const {
  3008. if (!running_.load()) { return false; }
  3009. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3010. return count < max_reconnect_attempts_;
  3011. }
  3012. // Wait for reconnect interval
  3013. void wait_for_reconnect() {
  3014. // Use small increments to check running_ flag frequently
  3015. auto waited = 0;
  3016. while (running_.load() && waited < reconnect_interval_ms_) {
  3017. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3018. waited += 100;
  3019. }
  3020. }
  3021. // Client and path
  3022. Client &client_;
  3023. std::string path_;
  3024. Headers headers_;
  3025. // Callbacks
  3026. MessageHandler on_message_;
  3027. std::map<std::string, MessageHandler> event_handlers_;
  3028. OpenHandler on_open_;
  3029. ErrorHandler on_error_;
  3030. // Configuration
  3031. int reconnect_interval_ms_ = 3000;
  3032. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3033. // State
  3034. std::atomic<bool> running_{false};
  3035. std::atomic<bool> connected_{false};
  3036. std::string last_event_id_;
  3037. // Async support
  3038. std::thread async_thread_;
  3039. };
  3040. } // namespace sse
  3041. // ----------------------------------------------------------------------------
  3042. /*
  3043. * Implementation that will be part of the .cc file if split into .h + .cc.
  3044. */
  3045. namespace detail {
  3046. inline bool is_hex(char c, int &v) {
  3047. if (isdigit(c)) {
  3048. v = c - '0';
  3049. return true;
  3050. } else if ('A' <= c && c <= 'F') {
  3051. v = c - 'A' + 10;
  3052. return true;
  3053. } else if ('a' <= c && c <= 'f') {
  3054. v = c - 'a' + 10;
  3055. return true;
  3056. }
  3057. return false;
  3058. }
  3059. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3060. int &val) {
  3061. if (i >= s.size()) { return false; }
  3062. val = 0;
  3063. for (; cnt; i++, cnt--) {
  3064. if (!s[i]) { return false; }
  3065. auto v = 0;
  3066. if (is_hex(s[i], v)) {
  3067. val = val * 16 + v;
  3068. } else {
  3069. return false;
  3070. }
  3071. }
  3072. return true;
  3073. }
  3074. inline std::string from_i_to_hex(size_t n) {
  3075. static const auto charset = "0123456789abcdef";
  3076. std::string ret;
  3077. do {
  3078. ret = charset[n & 15] + ret;
  3079. n >>= 4;
  3080. } while (n > 0);
  3081. return ret;
  3082. }
  3083. inline std::string compute_etag(const FileStat &fs) {
  3084. if (!fs.is_file()) { return std::string(); }
  3085. // If mtime cannot be determined (negative value indicates an error
  3086. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3087. // value like 0 could collide with a real file that legitimately has
  3088. // mtime == 0 (epoch) and lead to misleading validators.
  3089. auto mtime_raw = fs.mtime();
  3090. if (mtime_raw < 0) { return std::string(); }
  3091. auto mtime = static_cast<size_t>(mtime_raw);
  3092. auto size = fs.size();
  3093. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3094. from_i_to_hex(size) + "\"";
  3095. }
  3096. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3097. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3098. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3099. inline std::string file_mtime_to_http_date(time_t mtime) {
  3100. if (mtime < 0) { return std::string(); }
  3101. struct tm tm_buf;
  3102. #ifdef _WIN32
  3103. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3104. #else
  3105. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3106. #endif
  3107. char buf[64];
  3108. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3109. return std::string();
  3110. }
  3111. return std::string(buf);
  3112. }
  3113. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3114. inline time_t parse_http_date(const std::string &date_str) {
  3115. struct tm tm_buf;
  3116. // Create a classic locale object once for all parsing attempts
  3117. const std::locale classic_locale = std::locale::classic();
  3118. // Try to parse using std::get_time (C++11, cross-platform)
  3119. auto try_parse = [&](const char *fmt) -> bool {
  3120. std::istringstream ss(date_str);
  3121. ss.imbue(classic_locale);
  3122. memset(&tm_buf, 0, sizeof(tm_buf));
  3123. ss >> std::get_time(&tm_buf, fmt);
  3124. return !ss.fail();
  3125. };
  3126. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3127. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3128. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3129. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3130. // asctime format: "Sun Nov 6 08:49:37 1994"
  3131. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3132. return static_cast<time_t>(-1);
  3133. }
  3134. }
  3135. }
  3136. #ifdef _WIN32
  3137. return _mkgmtime(&tm_buf);
  3138. #else
  3139. return timegm(&tm_buf);
  3140. #endif
  3141. }
  3142. inline bool is_weak_etag(const std::string &s) {
  3143. // Check if the string is a weak ETag (starts with 'W/"')
  3144. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3145. }
  3146. inline bool is_strong_etag(const std::string &s) {
  3147. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3148. // chars)
  3149. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3150. }
  3151. inline size_t to_utf8(int code, char *buff) {
  3152. if (code < 0x0080) {
  3153. buff[0] = static_cast<char>(code & 0x7F);
  3154. return 1;
  3155. } else if (code < 0x0800) {
  3156. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3157. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3158. return 2;
  3159. } else if (code < 0xD800) {
  3160. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3161. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3162. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3163. return 3;
  3164. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3165. return 0;
  3166. } else if (code < 0x10000) {
  3167. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3168. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3169. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3170. return 3;
  3171. } else if (code < 0x110000) {
  3172. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3173. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3174. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3175. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3176. return 4;
  3177. }
  3178. // NOTREACHED
  3179. return 0;
  3180. }
  3181. // NOTE: This code came up with the following stackoverflow post:
  3182. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3183. inline std::string base64_encode(const std::string &in) {
  3184. static const auto lookup =
  3185. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3186. std::string out;
  3187. out.reserve(in.size());
  3188. auto val = 0;
  3189. auto valb = -6;
  3190. for (auto c : in) {
  3191. val = (val << 8) + static_cast<uint8_t>(c);
  3192. valb += 8;
  3193. while (valb >= 0) {
  3194. out.push_back(lookup[(val >> valb) & 0x3F]);
  3195. valb -= 6;
  3196. }
  3197. }
  3198. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3199. while (out.size() % 4) {
  3200. out.push_back('=');
  3201. }
  3202. return out;
  3203. }
  3204. inline bool is_valid_path(const std::string &path) {
  3205. size_t level = 0;
  3206. size_t i = 0;
  3207. // Skip slash
  3208. while (i < path.size() && path[i] == '/') {
  3209. i++;
  3210. }
  3211. while (i < path.size()) {
  3212. // Read component
  3213. auto beg = i;
  3214. while (i < path.size() && path[i] != '/') {
  3215. if (path[i] == '\0') {
  3216. return false;
  3217. } else if (path[i] == '\\') {
  3218. return false;
  3219. }
  3220. i++;
  3221. }
  3222. auto len = i - beg;
  3223. assert(len > 0);
  3224. if (!path.compare(beg, len, ".")) {
  3225. ;
  3226. } else if (!path.compare(beg, len, "..")) {
  3227. if (level == 0) { return false; }
  3228. level--;
  3229. } else {
  3230. level++;
  3231. }
  3232. // Skip slash
  3233. while (i < path.size() && path[i] == '/') {
  3234. i++;
  3235. }
  3236. }
  3237. return true;
  3238. }
  3239. inline FileStat::FileStat(const std::string &path) {
  3240. #if defined(_WIN32)
  3241. auto wpath = u8string_to_wstring(path.c_str());
  3242. ret_ = _wstat(wpath.c_str(), &st_);
  3243. #else
  3244. ret_ = stat(path.c_str(), &st_);
  3245. #endif
  3246. }
  3247. inline bool FileStat::is_file() const {
  3248. return ret_ >= 0 && S_ISREG(st_.st_mode);
  3249. }
  3250. inline bool FileStat::is_dir() const {
  3251. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  3252. }
  3253. inline time_t FileStat::mtime() const {
  3254. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  3255. : static_cast<time_t>(-1);
  3256. }
  3257. inline size_t FileStat::size() const {
  3258. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  3259. }
  3260. inline std::string encode_path(const std::string &s) {
  3261. std::string result;
  3262. result.reserve(s.size());
  3263. for (size_t i = 0; s[i]; i++) {
  3264. switch (s[i]) {
  3265. case ' ': result += "%20"; break;
  3266. case '+': result += "%2B"; break;
  3267. case '\r': result += "%0D"; break;
  3268. case '\n': result += "%0A"; break;
  3269. case '\'': result += "%27"; break;
  3270. case ',': result += "%2C"; break;
  3271. // case ':': result += "%3A"; break; // ok? probably...
  3272. case ';': result += "%3B"; break;
  3273. default:
  3274. auto c = static_cast<uint8_t>(s[i]);
  3275. if (c >= 0x80) {
  3276. result += '%';
  3277. char hex[4];
  3278. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  3279. assert(len == 2);
  3280. result.append(hex, static_cast<size_t>(len));
  3281. } else {
  3282. result += s[i];
  3283. }
  3284. break;
  3285. }
  3286. }
  3287. return result;
  3288. }
  3289. inline std::string file_extension(const std::string &path) {
  3290. std::smatch m;
  3291. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  3292. if (std::regex_search(path, m, re)) { return m[1].str(); }
  3293. return std::string();
  3294. }
  3295. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  3296. template <typename T>
  3297. inline bool parse_header(const char *beg, const char *end, T fn);
  3298. template <typename T>
  3299. inline bool parse_header(const char *beg, const char *end, T fn) {
  3300. // Skip trailing spaces and tabs.
  3301. while (beg < end && is_space_or_tab(end[-1])) {
  3302. end--;
  3303. }
  3304. auto p = beg;
  3305. while (p < end && *p != ':') {
  3306. p++;
  3307. }
  3308. auto name = std::string(beg, p);
  3309. if (!detail::fields::is_field_name(name)) { return false; }
  3310. if (p == end) { return false; }
  3311. auto key_end = p;
  3312. if (*p++ != ':') { return false; }
  3313. while (p < end && is_space_or_tab(*p)) {
  3314. p++;
  3315. }
  3316. if (p <= end) {
  3317. auto key_len = key_end - beg;
  3318. if (!key_len) { return false; }
  3319. auto key = std::string(beg, key_end);
  3320. auto val = std::string(p, end);
  3321. if (!detail::fields::is_field_value(val)) { return false; }
  3322. if (case_ignore::equal(key, "Location") ||
  3323. case_ignore::equal(key, "Referer")) {
  3324. fn(key, val);
  3325. } else {
  3326. fn(key, decode_path_component(val));
  3327. }
  3328. return true;
  3329. }
  3330. return false;
  3331. }
  3332. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3333. const Headers &src_headers) {
  3334. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3335. // transfer coding is complete when a chunk with a chunk-size of zero is
  3336. // received, possibly followed by a trailer section, and finally terminated by
  3337. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3338. //
  3339. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3340. // doesn't care for the existence of the final CRLF. In other words, it seems
  3341. // to be ok whether the final CRLF exists or not in the chunked data.
  3342. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3343. //
  3344. // According to the reference code in RFC 9112, cpp-httplib now allows
  3345. // chunked transfer coding data without the final CRLF.
  3346. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3347. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3348. "transfer-encoding",
  3349. "content-length",
  3350. "host",
  3351. "authorization",
  3352. "www-authenticate",
  3353. "proxy-authenticate",
  3354. "proxy-authorization",
  3355. "cookie",
  3356. "set-cookie",
  3357. "cache-control",
  3358. "expect",
  3359. "max-forwards",
  3360. "pragma",
  3361. "range",
  3362. "te",
  3363. "age",
  3364. "expires",
  3365. "date",
  3366. "location",
  3367. "retry-after",
  3368. "vary",
  3369. "warning",
  3370. "content-encoding",
  3371. "content-type",
  3372. "content-range",
  3373. "trailer"};
  3374. case_ignore::unordered_set<std::string> declared_trailers;
  3375. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  3376. if (trailer_header && std::strlen(trailer_header)) {
  3377. auto len = std::strlen(trailer_header);
  3378. split(trailer_header, trailer_header + len, ',',
  3379. [&](const char *b, const char *e) {
  3380. const char *kbeg = b;
  3381. const char *kend = e;
  3382. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  3383. ++kbeg;
  3384. }
  3385. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  3386. --kend;
  3387. }
  3388. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  3389. if (!key.empty() &&
  3390. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  3391. declared_trailers.insert(key);
  3392. }
  3393. });
  3394. }
  3395. size_t trailer_header_count = 0;
  3396. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3397. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3398. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3399. constexpr auto line_terminator_len = 2;
  3400. auto line_beg = line_reader.ptr();
  3401. auto line_end =
  3402. line_reader.ptr() + line_reader.size() - line_terminator_len;
  3403. if (!parse_header(line_beg, line_end,
  3404. [&](const std::string &key, const std::string &val) {
  3405. if (declared_trailers.find(key) !=
  3406. declared_trailers.end()) {
  3407. dest.emplace(key, val);
  3408. trailer_header_count++;
  3409. }
  3410. })) {
  3411. return false;
  3412. }
  3413. if (!line_reader.getline()) { return false; }
  3414. }
  3415. return true;
  3416. }
  3417. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  3418. size_t right) {
  3419. while (b + left < e && is_space_or_tab(b[left])) {
  3420. left++;
  3421. }
  3422. while (right > 0 && is_space_or_tab(b[right - 1])) {
  3423. right--;
  3424. }
  3425. return std::make_pair(left, right);
  3426. }
  3427. inline std::string trim_copy(const std::string &s) {
  3428. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  3429. return s.substr(r.first, r.second - r.first);
  3430. }
  3431. inline std::string trim_double_quotes_copy(const std::string &s) {
  3432. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  3433. return s.substr(1, s.size() - 2);
  3434. }
  3435. return s;
  3436. }
  3437. inline void
  3438. divide(const char *data, std::size_t size, char d,
  3439. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3440. fn) {
  3441. const auto it = std::find(data, data + size, d);
  3442. const auto found = static_cast<std::size_t>(it != data + size);
  3443. const auto lhs_data = data;
  3444. const auto lhs_size = static_cast<std::size_t>(it - data);
  3445. const auto rhs_data = it + found;
  3446. const auto rhs_size = size - lhs_size - found;
  3447. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  3448. }
  3449. inline void
  3450. divide(const std::string &str, char d,
  3451. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3452. fn) {
  3453. divide(str.data(), str.size(), d, std::move(fn));
  3454. }
  3455. inline void split(const char *b, const char *e, char d,
  3456. std::function<void(const char *, const char *)> fn) {
  3457. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  3458. }
  3459. inline void split(const char *b, const char *e, char d, size_t m,
  3460. std::function<void(const char *, const char *)> fn) {
  3461. size_t i = 0;
  3462. size_t beg = 0;
  3463. size_t count = 1;
  3464. while (e ? (b + i < e) : (b[i] != '\0')) {
  3465. if (b[i] == d && count < m) {
  3466. auto r = trim(b, e, beg, i);
  3467. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3468. beg = i + 1;
  3469. count++;
  3470. }
  3471. i++;
  3472. }
  3473. if (i) {
  3474. auto r = trim(b, e, beg, i);
  3475. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3476. }
  3477. }
  3478. inline bool split_find(const char *b, const char *e, char d, size_t m,
  3479. std::function<bool(const char *, const char *)> fn) {
  3480. size_t i = 0;
  3481. size_t beg = 0;
  3482. size_t count = 1;
  3483. while (e ? (b + i < e) : (b[i] != '\0')) {
  3484. if (b[i] == d && count < m) {
  3485. auto r = trim(b, e, beg, i);
  3486. if (r.first < r.second) {
  3487. auto found = fn(&b[r.first], &b[r.second]);
  3488. if (found) { return true; }
  3489. }
  3490. beg = i + 1;
  3491. count++;
  3492. }
  3493. i++;
  3494. }
  3495. if (i) {
  3496. auto r = trim(b, e, beg, i);
  3497. if (r.first < r.second) {
  3498. auto found = fn(&b[r.first], &b[r.second]);
  3499. if (found) { return true; }
  3500. }
  3501. }
  3502. return false;
  3503. }
  3504. inline bool split_find(const char *b, const char *e, char d,
  3505. std::function<bool(const char *, const char *)> fn) {
  3506. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  3507. std::move(fn));
  3508. }
  3509. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  3510. size_t fixed_buffer_size)
  3511. : strm_(strm), fixed_buffer_(fixed_buffer),
  3512. fixed_buffer_size_(fixed_buffer_size) {}
  3513. inline const char *stream_line_reader::ptr() const {
  3514. if (growable_buffer_.empty()) {
  3515. return fixed_buffer_;
  3516. } else {
  3517. return growable_buffer_.data();
  3518. }
  3519. }
  3520. inline size_t stream_line_reader::size() const {
  3521. if (growable_buffer_.empty()) {
  3522. return fixed_buffer_used_size_;
  3523. } else {
  3524. return growable_buffer_.size();
  3525. }
  3526. }
  3527. inline bool stream_line_reader::end_with_crlf() const {
  3528. auto end = ptr() + size();
  3529. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  3530. }
  3531. inline bool stream_line_reader::getline() {
  3532. fixed_buffer_used_size_ = 0;
  3533. growable_buffer_.clear();
  3534. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3535. char prev_byte = 0;
  3536. #endif
  3537. for (size_t i = 0;; i++) {
  3538. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  3539. // Treat exceptionally long lines as an error to
  3540. // prevent infinite loops/memory exhaustion
  3541. return false;
  3542. }
  3543. char byte;
  3544. auto n = strm_.read(&byte, 1);
  3545. if (n < 0) {
  3546. return false;
  3547. } else if (n == 0) {
  3548. if (i == 0) {
  3549. return false;
  3550. } else {
  3551. break;
  3552. }
  3553. }
  3554. append(byte);
  3555. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3556. if (byte == '\n') { break; }
  3557. #else
  3558. if (prev_byte == '\r' && byte == '\n') { break; }
  3559. prev_byte = byte;
  3560. #endif
  3561. }
  3562. return true;
  3563. }
  3564. inline void stream_line_reader::append(char c) {
  3565. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  3566. fixed_buffer_[fixed_buffer_used_size_++] = c;
  3567. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  3568. } else {
  3569. if (growable_buffer_.empty()) {
  3570. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  3571. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  3572. }
  3573. growable_buffer_ += c;
  3574. }
  3575. }
  3576. inline mmap::mmap(const char *path) { open(path); }
  3577. inline mmap::~mmap() { close(); }
  3578. inline bool mmap::open(const char *path) {
  3579. close();
  3580. #if defined(_WIN32)
  3581. auto wpath = u8string_to_wstring(path);
  3582. if (wpath.empty()) { return false; }
  3583. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  3584. OPEN_EXISTING, NULL);
  3585. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  3586. LARGE_INTEGER size{};
  3587. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  3588. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  3589. // See:
  3590. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  3591. if (static_cast<ULONGLONG>(size.QuadPart) >
  3592. (std::numeric_limits<decltype(size_)>::max)()) {
  3593. // `size_t` might be 32-bits, on 32-bits Windows.
  3594. return false;
  3595. }
  3596. size_ = static_cast<size_t>(size.QuadPart);
  3597. hMapping_ =
  3598. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  3599. // Special treatment for an empty file...
  3600. if (hMapping_ == NULL && size_ == 0) {
  3601. close();
  3602. is_open_empty_file = true;
  3603. return true;
  3604. }
  3605. if (hMapping_ == NULL) {
  3606. close();
  3607. return false;
  3608. }
  3609. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  3610. if (addr_ == nullptr) {
  3611. close();
  3612. return false;
  3613. }
  3614. #else
  3615. fd_ = ::open(path, O_RDONLY);
  3616. if (fd_ == -1) { return false; }
  3617. struct stat sb;
  3618. if (fstat(fd_, &sb) == -1) {
  3619. close();
  3620. return false;
  3621. }
  3622. size_ = static_cast<size_t>(sb.st_size);
  3623. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  3624. // Special treatment for an empty file...
  3625. if (addr_ == MAP_FAILED && size_ == 0) {
  3626. close();
  3627. is_open_empty_file = true;
  3628. return false;
  3629. }
  3630. #endif
  3631. return true;
  3632. }
  3633. inline bool mmap::is_open() const {
  3634. return is_open_empty_file ? true : addr_ != nullptr;
  3635. }
  3636. inline size_t mmap::size() const { return size_; }
  3637. inline const char *mmap::data() const {
  3638. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  3639. }
  3640. inline void mmap::close() {
  3641. #if defined(_WIN32)
  3642. if (addr_) {
  3643. ::UnmapViewOfFile(addr_);
  3644. addr_ = nullptr;
  3645. }
  3646. if (hMapping_) {
  3647. ::CloseHandle(hMapping_);
  3648. hMapping_ = NULL;
  3649. }
  3650. if (hFile_ != INVALID_HANDLE_VALUE) {
  3651. ::CloseHandle(hFile_);
  3652. hFile_ = INVALID_HANDLE_VALUE;
  3653. }
  3654. is_open_empty_file = false;
  3655. #else
  3656. if (addr_ != nullptr) {
  3657. munmap(addr_, size_);
  3658. addr_ = nullptr;
  3659. }
  3660. if (fd_ != -1) {
  3661. ::close(fd_);
  3662. fd_ = -1;
  3663. }
  3664. #endif
  3665. size_ = 0;
  3666. }
  3667. inline int close_socket(socket_t sock) {
  3668. #ifdef _WIN32
  3669. return closesocket(sock);
  3670. #else
  3671. return close(sock);
  3672. #endif
  3673. }
  3674. template <typename T> inline ssize_t handle_EINTR(T fn) {
  3675. ssize_t res = 0;
  3676. while (true) {
  3677. res = fn();
  3678. if (res < 0 && errno == EINTR) {
  3679. std::this_thread::sleep_for(std::chrono::microseconds{1});
  3680. continue;
  3681. }
  3682. break;
  3683. }
  3684. return res;
  3685. }
  3686. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  3687. return handle_EINTR([&]() {
  3688. return recv(sock,
  3689. #ifdef _WIN32
  3690. static_cast<char *>(ptr), static_cast<int>(size),
  3691. #else
  3692. ptr, size,
  3693. #endif
  3694. flags);
  3695. });
  3696. }
  3697. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  3698. int flags) {
  3699. return handle_EINTR([&]() {
  3700. return send(sock,
  3701. #ifdef _WIN32
  3702. static_cast<const char *>(ptr), static_cast<int>(size),
  3703. #else
  3704. ptr, size,
  3705. #endif
  3706. flags);
  3707. });
  3708. }
  3709. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  3710. #ifdef _WIN32
  3711. return ::WSAPoll(fds, nfds, timeout);
  3712. #else
  3713. return ::poll(fds, nfds, timeout);
  3714. #endif
  3715. }
  3716. template <bool Read>
  3717. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  3718. #ifdef __APPLE__
  3719. if (sock >= FD_SETSIZE) { return -1; }
  3720. fd_set fds, *rfds, *wfds;
  3721. FD_ZERO(&fds);
  3722. FD_SET(sock, &fds);
  3723. rfds = (Read ? &fds : nullptr);
  3724. wfds = (Read ? nullptr : &fds);
  3725. timeval tv;
  3726. tv.tv_sec = static_cast<long>(sec);
  3727. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3728. return handle_EINTR([&]() {
  3729. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  3730. });
  3731. #else
  3732. struct pollfd pfd;
  3733. pfd.fd = sock;
  3734. pfd.events = (Read ? POLLIN : POLLOUT);
  3735. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3736. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  3737. #endif
  3738. }
  3739. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  3740. return select_impl<true>(sock, sec, usec);
  3741. }
  3742. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  3743. return select_impl<false>(sock, sec, usec);
  3744. }
  3745. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  3746. time_t usec) {
  3747. #ifdef __APPLE__
  3748. if (sock >= FD_SETSIZE) { return Error::Connection; }
  3749. fd_set fdsr, fdsw;
  3750. FD_ZERO(&fdsr);
  3751. FD_ZERO(&fdsw);
  3752. FD_SET(sock, &fdsr);
  3753. FD_SET(sock, &fdsw);
  3754. timeval tv;
  3755. tv.tv_sec = static_cast<long>(sec);
  3756. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3757. auto ret = handle_EINTR([&]() {
  3758. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  3759. });
  3760. if (ret == 0) { return Error::ConnectionTimeout; }
  3761. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  3762. auto error = 0;
  3763. socklen_t len = sizeof(error);
  3764. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3765. reinterpret_cast<char *>(&error), &len);
  3766. auto successful = res >= 0 && !error;
  3767. return successful ? Error::Success : Error::Connection;
  3768. }
  3769. return Error::Connection;
  3770. #else
  3771. struct pollfd pfd_read;
  3772. pfd_read.fd = sock;
  3773. pfd_read.events = POLLIN | POLLOUT;
  3774. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3775. auto poll_res =
  3776. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  3777. if (poll_res == 0) { return Error::ConnectionTimeout; }
  3778. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  3779. auto error = 0;
  3780. socklen_t len = sizeof(error);
  3781. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3782. reinterpret_cast<char *>(&error), &len);
  3783. auto successful = res >= 0 && !error;
  3784. return successful ? Error::Success : Error::Connection;
  3785. }
  3786. return Error::Connection;
  3787. #endif
  3788. }
  3789. inline bool is_socket_alive(socket_t sock) {
  3790. const auto val = detail::select_read(sock, 0, 0);
  3791. if (val == 0) {
  3792. return true;
  3793. } else if (val < 0 && errno == EBADF) {
  3794. return false;
  3795. }
  3796. char buf[1];
  3797. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  3798. }
  3799. class SocketStream final : public Stream {
  3800. public:
  3801. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3802. time_t write_timeout_sec, time_t write_timeout_usec,
  3803. time_t max_timeout_msec = 0,
  3804. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3805. (std::chrono::steady_clock::time_point::min)());
  3806. ~SocketStream() override;
  3807. bool is_readable() const override;
  3808. bool wait_readable() const override;
  3809. bool wait_writable() const override;
  3810. ssize_t read(char *ptr, size_t size) override;
  3811. ssize_t write(const char *ptr, size_t size) override;
  3812. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3813. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3814. socket_t socket() const override;
  3815. time_t duration() const override;
  3816. private:
  3817. socket_t sock_;
  3818. time_t read_timeout_sec_;
  3819. time_t read_timeout_usec_;
  3820. time_t write_timeout_sec_;
  3821. time_t write_timeout_usec_;
  3822. time_t max_timeout_msec_;
  3823. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3824. std::vector<char> read_buff_;
  3825. size_t read_buff_off_ = 0;
  3826. size_t read_buff_content_size_ = 0;
  3827. static const size_t read_buff_size_ = 1024l * 4;
  3828. };
  3829. #ifdef CPPHTTPLIB_SSL_ENABLED
  3830. class SSLSocketStream final : public Stream {
  3831. public:
  3832. SSLSocketStream(
  3833. socket_t sock, tls::tls_session_t session, time_t read_timeout_sec,
  3834. time_t read_timeout_usec, time_t write_timeout_sec,
  3835. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  3836. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3837. (std::chrono::steady_clock::time_point::min)());
  3838. ~SSLSocketStream() override;
  3839. bool is_readable() const override;
  3840. bool wait_readable() const override;
  3841. bool wait_writable() const override;
  3842. ssize_t read(char *ptr, size_t size) override;
  3843. ssize_t write(const char *ptr, size_t size) override;
  3844. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3845. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3846. socket_t socket() const override;
  3847. time_t duration() const override;
  3848. private:
  3849. socket_t sock_;
  3850. tls::tls_session_t session_;
  3851. time_t read_timeout_sec_;
  3852. time_t read_timeout_usec_;
  3853. time_t write_timeout_sec_;
  3854. time_t write_timeout_usec_;
  3855. time_t max_timeout_msec_;
  3856. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3857. };
  3858. #endif
  3859. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3860. time_t keep_alive_timeout_sec) {
  3861. using namespace std::chrono;
  3862. const auto interval_usec =
  3863. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  3864. // Avoid expensive `steady_clock::now()` call for the first time
  3865. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  3866. const auto start = steady_clock::now() - microseconds{interval_usec};
  3867. const auto timeout = seconds{keep_alive_timeout_sec};
  3868. while (true) {
  3869. if (svr_sock == INVALID_SOCKET) {
  3870. break; // Server socket is closed
  3871. }
  3872. auto val = select_read(sock, 0, interval_usec);
  3873. if (val < 0) {
  3874. break; // Ssocket error
  3875. } else if (val == 0) {
  3876. if (steady_clock::now() - start > timeout) {
  3877. break; // Timeout
  3878. }
  3879. } else {
  3880. return true; // Ready for read
  3881. }
  3882. }
  3883. return false;
  3884. }
  3885. template <typename T>
  3886. inline bool
  3887. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3888. size_t keep_alive_max_count,
  3889. time_t keep_alive_timeout_sec, T callback) {
  3890. assert(keep_alive_max_count > 0);
  3891. auto ret = false;
  3892. auto count = keep_alive_max_count;
  3893. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  3894. auto close_connection = count == 1;
  3895. auto connection_closed = false;
  3896. ret = callback(close_connection, connection_closed);
  3897. if (!ret || connection_closed) { break; }
  3898. count--;
  3899. }
  3900. return ret;
  3901. }
  3902. template <typename T>
  3903. inline bool
  3904. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3905. size_t keep_alive_max_count,
  3906. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  3907. time_t read_timeout_usec, time_t write_timeout_sec,
  3908. time_t write_timeout_usec, T callback) {
  3909. return process_server_socket_core(
  3910. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  3911. [&](bool close_connection, bool &connection_closed) {
  3912. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3913. write_timeout_sec, write_timeout_usec);
  3914. return callback(strm, close_connection, connection_closed);
  3915. });
  3916. }
  3917. inline bool process_client_socket(
  3918. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3919. time_t write_timeout_sec, time_t write_timeout_usec,
  3920. time_t max_timeout_msec,
  3921. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3922. std::function<bool(Stream &)> callback) {
  3923. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3924. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  3925. start_time);
  3926. return callback(strm);
  3927. }
  3928. inline int shutdown_socket(socket_t sock) {
  3929. #ifdef _WIN32
  3930. return shutdown(sock, SD_BOTH);
  3931. #else
  3932. return shutdown(sock, SHUT_RDWR);
  3933. #endif
  3934. }
  3935. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  3936. if (s.size() > 1 && s[0] == '\0') {
  3937. auto ret = s;
  3938. ret[0] = '@';
  3939. return ret;
  3940. }
  3941. return s;
  3942. }
  3943. inline std::string
  3944. unescape_abstract_namespace_unix_domain(const std::string &s) {
  3945. if (s.size() > 1 && s[0] == '@') {
  3946. auto ret = s;
  3947. ret[0] = '\0';
  3948. return ret;
  3949. }
  3950. return s;
  3951. }
  3952. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  3953. const struct addrinfo *hints,
  3954. struct addrinfo **res, time_t timeout_sec) {
  3955. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  3956. if (timeout_sec <= 0) {
  3957. // No timeout specified, use standard getaddrinfo
  3958. return getaddrinfo(node, service, hints, res);
  3959. }
  3960. #ifdef _WIN32
  3961. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  3962. OVERLAPPED overlapped = {0};
  3963. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  3964. if (!event) { return EAI_FAIL; }
  3965. overlapped.hEvent = event;
  3966. PADDRINFOEXW result_addrinfo = nullptr;
  3967. HANDLE cancel_handle = nullptr;
  3968. ADDRINFOEXW hints_ex = {0};
  3969. if (hints) {
  3970. hints_ex.ai_flags = hints->ai_flags;
  3971. hints_ex.ai_family = hints->ai_family;
  3972. hints_ex.ai_socktype = hints->ai_socktype;
  3973. hints_ex.ai_protocol = hints->ai_protocol;
  3974. }
  3975. auto wnode = u8string_to_wstring(node);
  3976. auto wservice = u8string_to_wstring(service);
  3977. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  3978. hints ? &hints_ex : nullptr, &result_addrinfo,
  3979. nullptr, &overlapped, nullptr, &cancel_handle);
  3980. if (ret == WSA_IO_PENDING) {
  3981. auto wait_result =
  3982. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  3983. if (wait_result == WAIT_TIMEOUT) {
  3984. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  3985. ::CloseHandle(event);
  3986. return EAI_AGAIN;
  3987. }
  3988. DWORD bytes_returned;
  3989. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  3990. &bytes_returned, FALSE)) {
  3991. ::CloseHandle(event);
  3992. return ::WSAGetLastError();
  3993. }
  3994. }
  3995. ::CloseHandle(event);
  3996. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  3997. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  3998. return 0;
  3999. }
  4000. return ret;
  4001. #elif TARGET_OS_MAC
  4002. if (!node) { return EAI_NONAME; }
  4003. // macOS implementation using CFHost API for asynchronous DNS resolution
  4004. CFStringRef hostname_ref = CFStringCreateWithCString(
  4005. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4006. if (!hostname_ref) { return EAI_MEMORY; }
  4007. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4008. CFRelease(hostname_ref);
  4009. if (!host_ref) { return EAI_MEMORY; }
  4010. // Set up context for callback
  4011. struct CFHostContext {
  4012. bool completed = false;
  4013. bool success = false;
  4014. CFArrayRef addresses = nullptr;
  4015. std::mutex mutex;
  4016. std::condition_variable cv;
  4017. } context;
  4018. CFHostClientContext client_context;
  4019. memset(&client_context, 0, sizeof(client_context));
  4020. client_context.info = &context;
  4021. // Set callback
  4022. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4023. const CFStreamError *error, void *info) {
  4024. auto ctx = static_cast<CFHostContext *>(info);
  4025. std::lock_guard<std::mutex> lock(ctx->mutex);
  4026. if (error && error->error != 0) {
  4027. ctx->success = false;
  4028. } else {
  4029. Boolean hasBeenResolved;
  4030. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4031. if (ctx->addresses && hasBeenResolved) {
  4032. CFRetain(ctx->addresses);
  4033. ctx->success = true;
  4034. } else {
  4035. ctx->success = false;
  4036. }
  4037. }
  4038. ctx->completed = true;
  4039. ctx->cv.notify_one();
  4040. };
  4041. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4042. CFRelease(host_ref);
  4043. return EAI_SYSTEM;
  4044. }
  4045. // Schedule on run loop
  4046. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4047. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4048. // Start resolution
  4049. CFStreamError stream_error;
  4050. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4051. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4052. CFRelease(host_ref);
  4053. return EAI_FAIL;
  4054. }
  4055. // Wait for completion with timeout
  4056. auto timeout_time =
  4057. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4058. bool timed_out = false;
  4059. {
  4060. std::unique_lock<std::mutex> lock(context.mutex);
  4061. while (!context.completed) {
  4062. auto now = std::chrono::steady_clock::now();
  4063. if (now >= timeout_time) {
  4064. timed_out = true;
  4065. break;
  4066. }
  4067. // Run the runloop for a short time
  4068. lock.unlock();
  4069. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4070. lock.lock();
  4071. }
  4072. }
  4073. // Clean up
  4074. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4075. CFHostSetClient(host_ref, nullptr, nullptr);
  4076. if (timed_out || !context.completed) {
  4077. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4078. CFRelease(host_ref);
  4079. return EAI_AGAIN;
  4080. }
  4081. if (!context.success || !context.addresses) {
  4082. CFRelease(host_ref);
  4083. return EAI_NODATA;
  4084. }
  4085. // Convert CFArray to addrinfo
  4086. CFIndex count = CFArrayGetCount(context.addresses);
  4087. if (count == 0) {
  4088. CFRelease(context.addresses);
  4089. CFRelease(host_ref);
  4090. return EAI_NODATA;
  4091. }
  4092. struct addrinfo *result_addrinfo = nullptr;
  4093. struct addrinfo **current = &result_addrinfo;
  4094. for (CFIndex i = 0; i < count; i++) {
  4095. CFDataRef addr_data =
  4096. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4097. if (!addr_data) continue;
  4098. const struct sockaddr *sockaddr_ptr =
  4099. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4100. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4101. // Allocate addrinfo structure
  4102. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4103. if (!*current) {
  4104. freeaddrinfo(result_addrinfo);
  4105. CFRelease(context.addresses);
  4106. CFRelease(host_ref);
  4107. return EAI_MEMORY;
  4108. }
  4109. memset(*current, 0, sizeof(struct addrinfo));
  4110. // Set up addrinfo fields
  4111. (*current)->ai_family = sockaddr_ptr->sa_family;
  4112. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4113. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4114. (*current)->ai_addrlen = sockaddr_len;
  4115. // Copy sockaddr
  4116. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4117. if (!(*current)->ai_addr) {
  4118. freeaddrinfo(result_addrinfo);
  4119. CFRelease(context.addresses);
  4120. CFRelease(host_ref);
  4121. return EAI_MEMORY;
  4122. }
  4123. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4124. // Set port if service is specified
  4125. if (service && strlen(service) > 0) {
  4126. int port = atoi(service);
  4127. if (port > 0) {
  4128. if (sockaddr_ptr->sa_family == AF_INET) {
  4129. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4130. ->sin_port = htons(static_cast<uint16_t>(port));
  4131. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4132. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4133. ->sin6_port = htons(static_cast<uint16_t>(port));
  4134. }
  4135. }
  4136. }
  4137. current = &((*current)->ai_next);
  4138. }
  4139. CFRelease(context.addresses);
  4140. CFRelease(host_ref);
  4141. *res = result_addrinfo;
  4142. return 0;
  4143. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  4144. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  4145. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  4146. struct gaicb request;
  4147. struct gaicb *requests[1] = {&request};
  4148. struct sigevent sevp;
  4149. struct timespec timeout;
  4150. // Initialize the request structure
  4151. memset(&request, 0, sizeof(request));
  4152. request.ar_name = node;
  4153. request.ar_service = service;
  4154. request.ar_request = hints;
  4155. // Set up timeout
  4156. timeout.tv_sec = timeout_sec;
  4157. timeout.tv_nsec = 0;
  4158. // Initialize sigevent structure (not used, but required)
  4159. memset(&sevp, 0, sizeof(sevp));
  4160. sevp.sigev_notify = SIGEV_NONE;
  4161. // Start asynchronous resolution
  4162. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  4163. if (start_result != 0) { return start_result; }
  4164. // Wait for completion with timeout
  4165. int wait_result =
  4166. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  4167. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  4168. // Completed successfully, get the result
  4169. int gai_result = gai_error(&request);
  4170. if (gai_result == 0) {
  4171. *res = request.ar_result;
  4172. return 0;
  4173. } else {
  4174. // Clean up on error
  4175. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  4176. return gai_result;
  4177. }
  4178. } else if (wait_result == EAI_AGAIN) {
  4179. // Timeout occurred, cancel the request
  4180. gai_cancel(&request);
  4181. return EAI_AGAIN;
  4182. } else {
  4183. // Other error occurred
  4184. gai_cancel(&request);
  4185. return wait_result;
  4186. }
  4187. #else
  4188. // Fallback implementation using thread-based timeout for other Unix systems
  4189. struct GetAddrInfoState {
  4190. ~GetAddrInfoState() {
  4191. if (info) { freeaddrinfo(info); }
  4192. }
  4193. std::mutex mutex;
  4194. std::condition_variable result_cv;
  4195. bool completed = false;
  4196. int result = EAI_SYSTEM;
  4197. std::string node;
  4198. std::string service;
  4199. struct addrinfo hints;
  4200. struct addrinfo *info = nullptr;
  4201. };
  4202. // Allocate on the heap, so the resolver thread can keep using the data.
  4203. auto state = std::make_shared<GetAddrInfoState>();
  4204. if (node) { state->node = node; }
  4205. state->service = service;
  4206. state->hints = *hints;
  4207. std::thread resolve_thread([state]() {
  4208. auto thread_result =
  4209. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4210. &state->info);
  4211. std::lock_guard<std::mutex> lock(state->mutex);
  4212. state->result = thread_result;
  4213. state->completed = true;
  4214. state->result_cv.notify_one();
  4215. });
  4216. // Wait for completion or timeout
  4217. std::unique_lock<std::mutex> lock(state->mutex);
  4218. auto finished =
  4219. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4220. [&] { return state->completed; });
  4221. if (finished) {
  4222. // Operation completed within timeout
  4223. resolve_thread.join();
  4224. *res = state->info;
  4225. state->info = nullptr; // Pass ownership to caller
  4226. return state->result;
  4227. } else {
  4228. // Timeout occurred
  4229. resolve_thread.detach(); // Let the thread finish in background
  4230. return EAI_AGAIN; // Return timeout error
  4231. }
  4232. #endif
  4233. #else
  4234. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4235. return getaddrinfo(node, service, hints, res);
  4236. #endif
  4237. }
  4238. template <typename BindOrConnect>
  4239. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4240. int address_family, int socket_flags, bool tcp_nodelay,
  4241. bool ipv6_v6only, SocketOptions socket_options,
  4242. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4243. // Get address info
  4244. const char *node = nullptr;
  4245. struct addrinfo hints;
  4246. struct addrinfo *result;
  4247. memset(&hints, 0, sizeof(struct addrinfo));
  4248. hints.ai_socktype = SOCK_STREAM;
  4249. hints.ai_protocol = IPPROTO_IP;
  4250. if (!ip.empty()) {
  4251. node = ip.c_str();
  4252. // Ask getaddrinfo to convert IP in c-string to address
  4253. hints.ai_family = AF_UNSPEC;
  4254. hints.ai_flags = AI_NUMERICHOST;
  4255. } else {
  4256. if (!host.empty()) { node = host.c_str(); }
  4257. hints.ai_family = address_family;
  4258. hints.ai_flags = socket_flags;
  4259. }
  4260. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  4261. if (hints.ai_family == AF_UNIX) {
  4262. const auto addrlen = host.length();
  4263. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  4264. #ifdef SOCK_CLOEXEC
  4265. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  4266. hints.ai_protocol);
  4267. #else
  4268. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4269. #endif
  4270. if (sock != INVALID_SOCKET) {
  4271. sockaddr_un addr{};
  4272. addr.sun_family = AF_UNIX;
  4273. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  4274. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  4275. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  4276. hints.ai_addrlen = static_cast<socklen_t>(
  4277. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  4278. #ifndef SOCK_CLOEXEC
  4279. #ifndef _WIN32
  4280. fcntl(sock, F_SETFD, FD_CLOEXEC);
  4281. #endif
  4282. #endif
  4283. if (socket_options) { socket_options(sock); }
  4284. #ifdef _WIN32
  4285. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  4286. // remove the option.
  4287. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  4288. #endif
  4289. bool dummy;
  4290. if (!bind_or_connect(sock, hints, dummy)) {
  4291. close_socket(sock);
  4292. sock = INVALID_SOCKET;
  4293. }
  4294. }
  4295. return sock;
  4296. }
  4297. #endif
  4298. auto service = std::to_string(port);
  4299. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  4300. timeout_sec)) {
  4301. #if defined __linux__ && !defined __ANDROID__
  4302. res_init();
  4303. #endif
  4304. return INVALID_SOCKET;
  4305. }
  4306. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4307. for (auto rp = result; rp; rp = rp->ai_next) {
  4308. // Create a socket
  4309. #ifdef _WIN32
  4310. auto sock =
  4311. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  4312. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  4313. /**
  4314. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  4315. * and above the socket creation fails on older Windows Systems.
  4316. *
  4317. * Let's try to create a socket the old way in this case.
  4318. *
  4319. * Reference:
  4320. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  4321. *
  4322. * WSA_FLAG_NO_HANDLE_INHERIT:
  4323. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  4324. * SP1, and later
  4325. *
  4326. */
  4327. if (sock == INVALID_SOCKET) {
  4328. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4329. }
  4330. #else
  4331. #ifdef SOCK_CLOEXEC
  4332. auto sock =
  4333. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  4334. #else
  4335. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4336. #endif
  4337. #endif
  4338. if (sock == INVALID_SOCKET) { continue; }
  4339. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  4340. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  4341. close_socket(sock);
  4342. continue;
  4343. }
  4344. #endif
  4345. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  4346. if (rp->ai_family == AF_INET6) {
  4347. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  4348. }
  4349. if (socket_options) { socket_options(sock); }
  4350. // bind or connect
  4351. auto quit = false;
  4352. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  4353. close_socket(sock);
  4354. if (quit) { break; }
  4355. }
  4356. return INVALID_SOCKET;
  4357. }
  4358. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  4359. #ifdef _WIN32
  4360. auto flags = nonblocking ? 1UL : 0UL;
  4361. ioctlsocket(sock, FIONBIO, &flags);
  4362. #else
  4363. auto flags = fcntl(sock, F_GETFL, 0);
  4364. fcntl(sock, F_SETFL,
  4365. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  4366. #endif
  4367. }
  4368. inline bool is_connection_error() {
  4369. #ifdef _WIN32
  4370. return WSAGetLastError() != WSAEWOULDBLOCK;
  4371. #else
  4372. return errno != EINPROGRESS;
  4373. #endif
  4374. }
  4375. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  4376. struct addrinfo hints;
  4377. struct addrinfo *result;
  4378. memset(&hints, 0, sizeof(struct addrinfo));
  4379. hints.ai_family = AF_UNSPEC;
  4380. hints.ai_socktype = SOCK_STREAM;
  4381. hints.ai_protocol = 0;
  4382. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  4383. return false;
  4384. }
  4385. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4386. auto ret = false;
  4387. for (auto rp = result; rp; rp = rp->ai_next) {
  4388. const auto &ai = *rp;
  4389. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4390. ret = true;
  4391. break;
  4392. }
  4393. }
  4394. return ret;
  4395. }
  4396. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  4397. #define USE_IF2IP
  4398. #endif
  4399. #ifdef USE_IF2IP
  4400. inline std::string if2ip(int address_family, const std::string &ifn) {
  4401. struct ifaddrs *ifap;
  4402. getifaddrs(&ifap);
  4403. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  4404. std::string addr_candidate;
  4405. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  4406. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  4407. (AF_UNSPEC == address_family ||
  4408. ifa->ifa_addr->sa_family == address_family)) {
  4409. if (ifa->ifa_addr->sa_family == AF_INET) {
  4410. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  4411. char buf[INET_ADDRSTRLEN];
  4412. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  4413. return std::string(buf, INET_ADDRSTRLEN);
  4414. }
  4415. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  4416. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  4417. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  4418. char buf[INET6_ADDRSTRLEN] = {};
  4419. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  4420. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  4421. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  4422. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  4423. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  4424. } else {
  4425. return std::string(buf, INET6_ADDRSTRLEN);
  4426. }
  4427. }
  4428. }
  4429. }
  4430. }
  4431. }
  4432. return addr_candidate;
  4433. }
  4434. #endif
  4435. inline socket_t create_client_socket(
  4436. const std::string &host, const std::string &ip, int port,
  4437. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  4438. SocketOptions socket_options, time_t connection_timeout_sec,
  4439. time_t connection_timeout_usec, time_t read_timeout_sec,
  4440. time_t read_timeout_usec, time_t write_timeout_sec,
  4441. time_t write_timeout_usec, const std::string &intf, Error &error) {
  4442. auto sock = create_socket(
  4443. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  4444. std::move(socket_options),
  4445. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  4446. if (!intf.empty()) {
  4447. #ifdef USE_IF2IP
  4448. auto ip_from_if = if2ip(address_family, intf);
  4449. if (ip_from_if.empty()) { ip_from_if = intf; }
  4450. if (!bind_ip_address(sock2, ip_from_if)) {
  4451. error = Error::BindIPAddress;
  4452. return false;
  4453. }
  4454. #endif
  4455. }
  4456. set_nonblocking(sock2, true);
  4457. auto ret =
  4458. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  4459. if (ret < 0) {
  4460. if (is_connection_error()) {
  4461. error = Error::Connection;
  4462. return false;
  4463. }
  4464. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  4465. connection_timeout_usec);
  4466. if (error != Error::Success) {
  4467. if (error == Error::ConnectionTimeout) { quit = true; }
  4468. return false;
  4469. }
  4470. }
  4471. set_nonblocking(sock2, false);
  4472. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  4473. read_timeout_usec);
  4474. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  4475. write_timeout_usec);
  4476. error = Error::Success;
  4477. return true;
  4478. },
  4479. connection_timeout_sec); // Pass DNS timeout
  4480. if (sock != INVALID_SOCKET) {
  4481. error = Error::Success;
  4482. } else {
  4483. if (error == Error::Success) { error = Error::Connection; }
  4484. }
  4485. return sock;
  4486. }
  4487. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  4488. socklen_t addr_len, std::string &ip, int &port) {
  4489. if (addr.ss_family == AF_INET) {
  4490. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  4491. } else if (addr.ss_family == AF_INET6) {
  4492. port =
  4493. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  4494. } else {
  4495. return false;
  4496. }
  4497. std::array<char, NI_MAXHOST> ipstr{};
  4498. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  4499. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  4500. 0, NI_NUMERICHOST)) {
  4501. return false;
  4502. }
  4503. ip = ipstr.data();
  4504. return true;
  4505. }
  4506. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4507. struct sockaddr_storage addr;
  4508. socklen_t addr_len = sizeof(addr);
  4509. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4510. &addr_len)) {
  4511. get_ip_and_port(addr, addr_len, ip, port);
  4512. }
  4513. }
  4514. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4515. struct sockaddr_storage addr;
  4516. socklen_t addr_len = sizeof(addr);
  4517. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4518. &addr_len)) {
  4519. #ifndef _WIN32
  4520. if (addr.ss_family == AF_UNIX) {
  4521. #if defined(__linux__)
  4522. struct ucred ucred;
  4523. socklen_t len = sizeof(ucred);
  4524. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  4525. port = ucred.pid;
  4526. }
  4527. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  4528. pid_t pid;
  4529. socklen_t len = sizeof(pid);
  4530. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  4531. port = pid;
  4532. }
  4533. #endif
  4534. return;
  4535. }
  4536. #endif
  4537. get_ip_and_port(addr, addr_len, ip, port);
  4538. }
  4539. }
  4540. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  4541. unsigned int h) {
  4542. return (l == 0)
  4543. ? h
  4544. : str2tag_core(
  4545. s + 1, l - 1,
  4546. // Unsets the 6 high bits of h, therefore no overflow happens
  4547. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  4548. h * 33) ^
  4549. static_cast<unsigned char>(*s));
  4550. }
  4551. inline unsigned int str2tag(const std::string &s) {
  4552. return str2tag_core(s.data(), s.size(), 0);
  4553. }
  4554. namespace udl {
  4555. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  4556. return str2tag_core(s, l, 0);
  4557. }
  4558. } // namespace udl
  4559. inline std::string
  4560. find_content_type(const std::string &path,
  4561. const std::map<std::string, std::string> &user_data,
  4562. const std::string &default_content_type) {
  4563. auto ext = file_extension(path);
  4564. auto it = user_data.find(ext);
  4565. if (it != user_data.end()) { return it->second; }
  4566. using udl::operator""_t;
  4567. switch (str2tag(ext)) {
  4568. default: return default_content_type;
  4569. case "css"_t: return "text/css";
  4570. case "csv"_t: return "text/csv";
  4571. case "htm"_t:
  4572. case "html"_t: return "text/html";
  4573. case "js"_t:
  4574. case "mjs"_t: return "text/javascript";
  4575. case "txt"_t: return "text/plain";
  4576. case "vtt"_t: return "text/vtt";
  4577. case "apng"_t: return "image/apng";
  4578. case "avif"_t: return "image/avif";
  4579. case "bmp"_t: return "image/bmp";
  4580. case "gif"_t: return "image/gif";
  4581. case "png"_t: return "image/png";
  4582. case "svg"_t: return "image/svg+xml";
  4583. case "webp"_t: return "image/webp";
  4584. case "ico"_t: return "image/x-icon";
  4585. case "tif"_t: return "image/tiff";
  4586. case "tiff"_t: return "image/tiff";
  4587. case "jpg"_t:
  4588. case "jpeg"_t: return "image/jpeg";
  4589. case "mp4"_t: return "video/mp4";
  4590. case "mpeg"_t: return "video/mpeg";
  4591. case "webm"_t: return "video/webm";
  4592. case "mp3"_t: return "audio/mp3";
  4593. case "mpga"_t: return "audio/mpeg";
  4594. case "weba"_t: return "audio/webm";
  4595. case "wav"_t: return "audio/wave";
  4596. case "otf"_t: return "font/otf";
  4597. case "ttf"_t: return "font/ttf";
  4598. case "woff"_t: return "font/woff";
  4599. case "woff2"_t: return "font/woff2";
  4600. case "7z"_t: return "application/x-7z-compressed";
  4601. case "atom"_t: return "application/atom+xml";
  4602. case "pdf"_t: return "application/pdf";
  4603. case "json"_t: return "application/json";
  4604. case "rss"_t: return "application/rss+xml";
  4605. case "tar"_t: return "application/x-tar";
  4606. case "xht"_t:
  4607. case "xhtml"_t: return "application/xhtml+xml";
  4608. case "xslt"_t: return "application/xslt+xml";
  4609. case "xml"_t: return "application/xml";
  4610. case "gz"_t: return "application/gzip";
  4611. case "zip"_t: return "application/zip";
  4612. case "wasm"_t: return "application/wasm";
  4613. }
  4614. }
  4615. inline bool can_compress_content_type(const std::string &content_type) {
  4616. using udl::operator""_t;
  4617. auto tag = str2tag(content_type);
  4618. switch (tag) {
  4619. case "image/svg+xml"_t:
  4620. case "application/javascript"_t:
  4621. case "application/json"_t:
  4622. case "application/xml"_t:
  4623. case "application/protobuf"_t:
  4624. case "application/xhtml+xml"_t: return true;
  4625. case "text/event-stream"_t: return false;
  4626. default: return !content_type.rfind("text/", 0);
  4627. }
  4628. }
  4629. inline EncodingType encoding_type(const Request &req, const Response &res) {
  4630. auto ret =
  4631. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  4632. if (!ret) { return EncodingType::None; }
  4633. const auto &s = req.get_header_value("Accept-Encoding");
  4634. (void)(s);
  4635. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4636. // TODO: 'Accept-Encoding' has br, not br;q=0
  4637. ret = s.find("br") != std::string::npos;
  4638. if (ret) { return EncodingType::Brotli; }
  4639. #endif
  4640. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4641. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  4642. ret = s.find("gzip") != std::string::npos;
  4643. if (ret) { return EncodingType::Gzip; }
  4644. #endif
  4645. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4646. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  4647. ret = s.find("zstd") != std::string::npos;
  4648. if (ret) { return EncodingType::Zstd; }
  4649. #endif
  4650. return EncodingType::None;
  4651. }
  4652. inline bool nocompressor::compress(const char *data, size_t data_length,
  4653. bool /*last*/, Callback callback) {
  4654. if (!data_length) { return true; }
  4655. return callback(data, data_length);
  4656. }
  4657. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4658. inline gzip_compressor::gzip_compressor() {
  4659. std::memset(&strm_, 0, sizeof(strm_));
  4660. strm_.zalloc = Z_NULL;
  4661. strm_.zfree = Z_NULL;
  4662. strm_.opaque = Z_NULL;
  4663. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  4664. Z_DEFAULT_STRATEGY) == Z_OK;
  4665. }
  4666. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  4667. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  4668. bool last, Callback callback) {
  4669. assert(is_valid_);
  4670. do {
  4671. constexpr size_t max_avail_in =
  4672. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4673. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4674. (std::min)(data_length, max_avail_in));
  4675. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4676. data_length -= strm_.avail_in;
  4677. data += strm_.avail_in;
  4678. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  4679. auto ret = Z_OK;
  4680. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4681. do {
  4682. strm_.avail_out = static_cast<uInt>(buff.size());
  4683. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4684. ret = deflate(&strm_, flush);
  4685. if (ret == Z_STREAM_ERROR) { return false; }
  4686. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4687. return false;
  4688. }
  4689. } while (strm_.avail_out == 0);
  4690. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  4691. (flush == Z_NO_FLUSH && ret == Z_OK));
  4692. assert(strm_.avail_in == 0);
  4693. } while (data_length > 0);
  4694. return true;
  4695. }
  4696. inline gzip_decompressor::gzip_decompressor() {
  4697. std::memset(&strm_, 0, sizeof(strm_));
  4698. strm_.zalloc = Z_NULL;
  4699. strm_.zfree = Z_NULL;
  4700. strm_.opaque = Z_NULL;
  4701. // 15 is the value of wbits, which should be at the maximum possible value
  4702. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  4703. // that the stream type should be automatically detected either gzip or
  4704. // deflate.
  4705. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  4706. }
  4707. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  4708. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  4709. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  4710. Callback callback) {
  4711. assert(is_valid_);
  4712. auto ret = Z_OK;
  4713. do {
  4714. constexpr size_t max_avail_in =
  4715. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4716. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4717. (std::min)(data_length, max_avail_in));
  4718. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4719. data_length -= strm_.avail_in;
  4720. data += strm_.avail_in;
  4721. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4722. while (strm_.avail_in > 0 && ret == Z_OK) {
  4723. strm_.avail_out = static_cast<uInt>(buff.size());
  4724. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4725. ret = inflate(&strm_, Z_NO_FLUSH);
  4726. assert(ret != Z_STREAM_ERROR);
  4727. switch (ret) {
  4728. case Z_NEED_DICT:
  4729. case Z_DATA_ERROR:
  4730. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  4731. }
  4732. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4733. return false;
  4734. }
  4735. }
  4736. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  4737. } while (data_length > 0);
  4738. return true;
  4739. }
  4740. #endif
  4741. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4742. inline brotli_compressor::brotli_compressor() {
  4743. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  4744. }
  4745. inline brotli_compressor::~brotli_compressor() {
  4746. BrotliEncoderDestroyInstance(state_);
  4747. }
  4748. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  4749. bool last, Callback callback) {
  4750. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4751. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  4752. auto available_in = data_length;
  4753. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4754. for (;;) {
  4755. if (last) {
  4756. if (BrotliEncoderIsFinished(state_)) { break; }
  4757. } else {
  4758. if (!available_in) { break; }
  4759. }
  4760. auto available_out = buff.size();
  4761. auto next_out = buff.data();
  4762. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  4763. &available_out, &next_out, nullptr)) {
  4764. return false;
  4765. }
  4766. auto output_bytes = buff.size() - available_out;
  4767. if (output_bytes) {
  4768. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  4769. }
  4770. }
  4771. return true;
  4772. }
  4773. inline brotli_decompressor::brotli_decompressor() {
  4774. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  4775. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  4776. : BROTLI_DECODER_RESULT_ERROR;
  4777. }
  4778. inline brotli_decompressor::~brotli_decompressor() {
  4779. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  4780. }
  4781. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  4782. inline bool brotli_decompressor::decompress(const char *data,
  4783. size_t data_length,
  4784. Callback callback) {
  4785. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4786. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  4787. return 0;
  4788. }
  4789. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4790. size_t avail_in = data_length;
  4791. size_t total_out;
  4792. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  4793. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4794. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  4795. char *next_out = buff.data();
  4796. size_t avail_out = buff.size();
  4797. decoder_r = BrotliDecoderDecompressStream(
  4798. decoder_s, &avail_in, &next_in, &avail_out,
  4799. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  4800. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  4801. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  4802. }
  4803. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4804. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  4805. }
  4806. #endif
  4807. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4808. inline zstd_compressor::zstd_compressor() {
  4809. ctx_ = ZSTD_createCCtx();
  4810. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  4811. }
  4812. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  4813. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  4814. bool last, Callback callback) {
  4815. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4816. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  4817. ZSTD_inBuffer input = {data, data_length, 0};
  4818. bool finished;
  4819. do {
  4820. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4821. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  4822. if (ZSTD_isError(remaining)) { return false; }
  4823. if (!callback(buff.data(), output.pos)) { return false; }
  4824. finished = last ? (remaining == 0) : (input.pos == input.size);
  4825. } while (!finished);
  4826. return true;
  4827. }
  4828. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  4829. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  4830. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  4831. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  4832. Callback callback) {
  4833. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4834. ZSTD_inBuffer input = {data, data_length, 0};
  4835. while (input.pos < input.size) {
  4836. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4837. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  4838. if (ZSTD_isError(remaining)) { return false; }
  4839. if (!callback(buff.data(), output.pos)) { return false; }
  4840. }
  4841. return true;
  4842. }
  4843. #endif
  4844. inline std::unique_ptr<decompressor>
  4845. create_decompressor(const std::string &encoding) {
  4846. std::unique_ptr<decompressor> decompressor;
  4847. if (encoding == "gzip" || encoding == "deflate") {
  4848. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4849. decompressor = detail::make_unique<gzip_decompressor>();
  4850. #endif
  4851. } else if (encoding.find("br") != std::string::npos) {
  4852. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4853. decompressor = detail::make_unique<brotli_decompressor>();
  4854. #endif
  4855. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  4856. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4857. decompressor = detail::make_unique<zstd_decompressor>();
  4858. #endif
  4859. }
  4860. return decompressor;
  4861. }
  4862. inline bool is_prohibited_header_name(const std::string &name) {
  4863. using udl::operator""_t;
  4864. switch (str2tag(name)) {
  4865. case "REMOTE_ADDR"_t:
  4866. case "REMOTE_PORT"_t:
  4867. case "LOCAL_ADDR"_t:
  4868. case "LOCAL_PORT"_t: return true;
  4869. default: return false;
  4870. }
  4871. }
  4872. inline bool has_header(const Headers &headers, const std::string &key) {
  4873. if (is_prohibited_header_name(key)) { return false; }
  4874. return headers.find(key) != headers.end();
  4875. }
  4876. inline const char *get_header_value(const Headers &headers,
  4877. const std::string &key, const char *def,
  4878. size_t id) {
  4879. if (is_prohibited_header_name(key)) {
  4880. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4881. std::string msg = "Prohibited header name '" + key + "' is specified.";
  4882. throw std::invalid_argument(msg);
  4883. #else
  4884. return "";
  4885. #endif
  4886. }
  4887. auto rng = headers.equal_range(key);
  4888. auto it = rng.first;
  4889. std::advance(it, static_cast<ssize_t>(id));
  4890. if (it != rng.second) { return it->second.c_str(); }
  4891. return def;
  4892. }
  4893. inline bool read_headers(Stream &strm, Headers &headers) {
  4894. const auto bufsiz = 2048;
  4895. char buf[bufsiz];
  4896. stream_line_reader line_reader(strm, buf, bufsiz);
  4897. size_t header_count = 0;
  4898. for (;;) {
  4899. if (!line_reader.getline()) { return false; }
  4900. // Check if the line ends with CRLF.
  4901. auto line_terminator_len = 2;
  4902. if (line_reader.end_with_crlf()) {
  4903. // Blank line indicates end of headers.
  4904. if (line_reader.size() == 2) { break; }
  4905. } else {
  4906. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4907. // Blank line indicates end of headers.
  4908. if (line_reader.size() == 1) { break; }
  4909. line_terminator_len = 1;
  4910. #else
  4911. continue; // Skip invalid line.
  4912. #endif
  4913. }
  4914. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4915. // Check header count limit
  4916. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4917. // Exclude line terminator
  4918. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  4919. if (!parse_header(line_reader.ptr(), end,
  4920. [&](const std::string &key, const std::string &val) {
  4921. headers.emplace(key, val);
  4922. })) {
  4923. return false;
  4924. }
  4925. header_count++;
  4926. }
  4927. return true;
  4928. }
  4929. inline bool read_content_with_length(Stream &strm, size_t len,
  4930. DownloadProgress progress,
  4931. ContentReceiverWithProgress out) {
  4932. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4933. detail::BodyReader br;
  4934. br.stream = &strm;
  4935. br.content_length = len;
  4936. br.chunked = false;
  4937. br.bytes_read = 0;
  4938. br.last_error = Error::Success;
  4939. size_t r = 0;
  4940. while (r < len) {
  4941. auto read_len = static_cast<size_t>(len - r);
  4942. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  4943. auto n = detail::read_body_content(&strm, br, buf, to_read);
  4944. if (n <= 0) { return false; }
  4945. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  4946. r += static_cast<size_t>(n);
  4947. if (progress) {
  4948. if (!progress(r, len)) { return false; }
  4949. }
  4950. }
  4951. return true;
  4952. }
  4953. inline void skip_content_with_length(Stream &strm, size_t len) {
  4954. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4955. size_t r = 0;
  4956. while (r < len) {
  4957. auto read_len = static_cast<size_t>(len - r);
  4958. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  4959. if (n <= 0) { return; }
  4960. r += static_cast<size_t>(n);
  4961. }
  4962. }
  4963. enum class ReadContentResult {
  4964. Success, // Successfully read the content
  4965. PayloadTooLarge, // The content exceeds the specified payload limit
  4966. Error // An error occurred while reading the content
  4967. };
  4968. inline ReadContentResult
  4969. read_content_without_length(Stream &strm, size_t payload_max_length,
  4970. ContentReceiverWithProgress out) {
  4971. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4972. size_t r = 0;
  4973. for (;;) {
  4974. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  4975. if (n == 0) { return ReadContentResult::Success; }
  4976. if (n < 0) { return ReadContentResult::Error; }
  4977. // Check if adding this data would exceed the payload limit
  4978. if (r > payload_max_length ||
  4979. payload_max_length - r < static_cast<size_t>(n)) {
  4980. return ReadContentResult::PayloadTooLarge;
  4981. }
  4982. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  4983. return ReadContentResult::Error;
  4984. }
  4985. r += static_cast<size_t>(n);
  4986. }
  4987. return ReadContentResult::Success;
  4988. }
  4989. template <typename T>
  4990. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  4991. size_t payload_max_length,
  4992. ContentReceiverWithProgress out) {
  4993. detail::ChunkedDecoder dec(strm);
  4994. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4995. size_t total_len = 0;
  4996. for (;;) {
  4997. size_t chunk_offset = 0;
  4998. size_t chunk_total = 0;
  4999. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  5000. if (n < 0) { return ReadContentResult::Error; }
  5001. if (n == 0) {
  5002. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  5003. return ReadContentResult::Error;
  5004. }
  5005. return ReadContentResult::Success;
  5006. }
  5007. if (total_len > payload_max_length ||
  5008. payload_max_length - total_len < static_cast<size_t>(n)) {
  5009. return ReadContentResult::PayloadTooLarge;
  5010. }
  5011. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  5012. return ReadContentResult::Error;
  5013. }
  5014. total_len += static_cast<size_t>(n);
  5015. }
  5016. }
  5017. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  5018. return case_ignore::equal(
  5019. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  5020. }
  5021. template <typename T, typename U>
  5022. bool prepare_content_receiver(T &x, int &status,
  5023. ContentReceiverWithProgress receiver,
  5024. bool decompress, U callback) {
  5025. if (decompress) {
  5026. std::string encoding = x.get_header_value("Content-Encoding");
  5027. std::unique_ptr<decompressor> decompressor;
  5028. if (!encoding.empty()) {
  5029. decompressor = detail::create_decompressor(encoding);
  5030. if (!decompressor) {
  5031. // Unsupported encoding or no support compiled in
  5032. status = StatusCode::UnsupportedMediaType_415;
  5033. return false;
  5034. }
  5035. }
  5036. if (decompressor) {
  5037. if (decompressor->is_valid()) {
  5038. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  5039. size_t off, size_t len) {
  5040. return decompressor->decompress(buf, n,
  5041. [&](const char *buf2, size_t n2) {
  5042. return receiver(buf2, n2, off, len);
  5043. });
  5044. };
  5045. return callback(std::move(out));
  5046. } else {
  5047. status = StatusCode::InternalServerError_500;
  5048. return false;
  5049. }
  5050. }
  5051. }
  5052. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  5053. size_t len) {
  5054. return receiver(buf, n, off, len);
  5055. };
  5056. return callback(std::move(out));
  5057. }
  5058. template <typename T>
  5059. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  5060. DownloadProgress progress,
  5061. ContentReceiverWithProgress receiver, bool decompress) {
  5062. return prepare_content_receiver(
  5063. x, status, std::move(receiver), decompress,
  5064. [&](const ContentReceiverWithProgress &out) {
  5065. auto ret = true;
  5066. auto exceed_payload_max_length = false;
  5067. if (is_chunked_transfer_encoding(x.headers)) {
  5068. auto result = read_content_chunked(strm, x, payload_max_length, out);
  5069. if (result == ReadContentResult::Success) {
  5070. ret = true;
  5071. } else if (result == ReadContentResult::PayloadTooLarge) {
  5072. exceed_payload_max_length = true;
  5073. ret = false;
  5074. } else {
  5075. ret = false;
  5076. }
  5077. } else if (!has_header(x.headers, "Content-Length")) {
  5078. auto result =
  5079. read_content_without_length(strm, payload_max_length, out);
  5080. if (result == ReadContentResult::Success) {
  5081. ret = true;
  5082. } else if (result == ReadContentResult::PayloadTooLarge) {
  5083. exceed_payload_max_length = true;
  5084. ret = false;
  5085. } else {
  5086. ret = false;
  5087. }
  5088. } else {
  5089. auto is_invalid_value = false;
  5090. auto len = get_header_value_u64(x.headers, "Content-Length",
  5091. (std::numeric_limits<size_t>::max)(),
  5092. 0, is_invalid_value);
  5093. if (is_invalid_value) {
  5094. ret = false;
  5095. } else if (len > payload_max_length) {
  5096. exceed_payload_max_length = true;
  5097. skip_content_with_length(strm, len);
  5098. ret = false;
  5099. } else if (len > 0) {
  5100. ret = read_content_with_length(strm, len, std::move(progress), out);
  5101. }
  5102. }
  5103. if (!ret) {
  5104. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  5105. : StatusCode::BadRequest_400;
  5106. }
  5107. return ret;
  5108. });
  5109. }
  5110. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  5111. const std::string &path) {
  5112. std::string s = method;
  5113. s += ' ';
  5114. s += path;
  5115. s += " HTTP/1.1\r\n";
  5116. return strm.write(s.data(), s.size());
  5117. }
  5118. inline ssize_t write_response_line(Stream &strm, int status) {
  5119. std::string s = "HTTP/1.1 ";
  5120. s += std::to_string(status);
  5121. s += ' ';
  5122. s += httplib::status_message(status);
  5123. s += "\r\n";
  5124. return strm.write(s.data(), s.size());
  5125. }
  5126. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  5127. ssize_t write_len = 0;
  5128. for (const auto &x : headers) {
  5129. std::string s;
  5130. s = x.first;
  5131. s += ": ";
  5132. s += x.second;
  5133. s += "\r\n";
  5134. auto len = strm.write(s.data(), s.size());
  5135. if (len < 0) { return len; }
  5136. write_len += len;
  5137. }
  5138. auto len = strm.write("\r\n");
  5139. if (len < 0) { return len; }
  5140. write_len += len;
  5141. return write_len;
  5142. }
  5143. inline bool write_data(Stream &strm, const char *d, size_t l) {
  5144. size_t offset = 0;
  5145. while (offset < l) {
  5146. auto length = strm.write(d + offset, l - offset);
  5147. if (length < 0) { return false; }
  5148. offset += static_cast<size_t>(length);
  5149. }
  5150. return true;
  5151. }
  5152. template <typename T>
  5153. inline bool write_content_with_progress(Stream &strm,
  5154. const ContentProvider &content_provider,
  5155. size_t offset, size_t length,
  5156. T is_shutting_down,
  5157. const UploadProgress &upload_progress,
  5158. Error &error) {
  5159. size_t end_offset = offset + length;
  5160. size_t start_offset = offset;
  5161. auto ok = true;
  5162. DataSink data_sink;
  5163. data_sink.write = [&](const char *d, size_t l) -> bool {
  5164. if (ok) {
  5165. if (write_data(strm, d, l)) {
  5166. offset += l;
  5167. if (upload_progress && length > 0) {
  5168. size_t current_written = offset - start_offset;
  5169. if (!upload_progress(current_written, length)) {
  5170. ok = false;
  5171. return false;
  5172. }
  5173. }
  5174. } else {
  5175. ok = false;
  5176. }
  5177. }
  5178. return ok;
  5179. };
  5180. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5181. while (offset < end_offset && !is_shutting_down()) {
  5182. if (!strm.wait_writable()) {
  5183. error = Error::Write;
  5184. return false;
  5185. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  5186. error = Error::Canceled;
  5187. return false;
  5188. } else if (!ok) {
  5189. error = Error::Write;
  5190. return false;
  5191. }
  5192. }
  5193. error = Error::Success;
  5194. return true;
  5195. }
  5196. template <typename T>
  5197. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5198. size_t offset, size_t length, T is_shutting_down,
  5199. Error &error) {
  5200. return write_content_with_progress<T>(strm, content_provider, offset, length,
  5201. is_shutting_down, nullptr, error);
  5202. }
  5203. template <typename T>
  5204. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5205. size_t offset, size_t length,
  5206. const T &is_shutting_down) {
  5207. auto error = Error::Success;
  5208. return write_content(strm, content_provider, offset, length, is_shutting_down,
  5209. error);
  5210. }
  5211. template <typename T>
  5212. inline bool
  5213. write_content_without_length(Stream &strm,
  5214. const ContentProvider &content_provider,
  5215. const T &is_shutting_down) {
  5216. size_t offset = 0;
  5217. auto data_available = true;
  5218. auto ok = true;
  5219. DataSink data_sink;
  5220. data_sink.write = [&](const char *d, size_t l) -> bool {
  5221. if (ok) {
  5222. offset += l;
  5223. if (!write_data(strm, d, l)) { ok = false; }
  5224. }
  5225. return ok;
  5226. };
  5227. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5228. data_sink.done = [&](void) { data_available = false; };
  5229. while (data_available && !is_shutting_down()) {
  5230. if (!strm.wait_writable()) {
  5231. return false;
  5232. } else if (!content_provider(offset, 0, data_sink)) {
  5233. return false;
  5234. } else if (!ok) {
  5235. return false;
  5236. }
  5237. }
  5238. return true;
  5239. }
  5240. template <typename T, typename U>
  5241. inline bool
  5242. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  5243. const T &is_shutting_down, U &compressor, Error &error) {
  5244. size_t offset = 0;
  5245. auto data_available = true;
  5246. auto ok = true;
  5247. DataSink data_sink;
  5248. data_sink.write = [&](const char *d, size_t l) -> bool {
  5249. if (ok) {
  5250. data_available = l > 0;
  5251. offset += l;
  5252. std::string payload;
  5253. if (compressor.compress(d, l, false,
  5254. [&](const char *data, size_t data_len) {
  5255. payload.append(data, data_len);
  5256. return true;
  5257. })) {
  5258. if (!payload.empty()) {
  5259. // Emit chunked response header and footer for each chunk
  5260. auto chunk =
  5261. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5262. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  5263. }
  5264. } else {
  5265. ok = false;
  5266. }
  5267. }
  5268. return ok;
  5269. };
  5270. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5271. auto done_with_trailer = [&](const Headers *trailer) {
  5272. if (!ok) { return; }
  5273. data_available = false;
  5274. std::string payload;
  5275. if (!compressor.compress(nullptr, 0, true,
  5276. [&](const char *data, size_t data_len) {
  5277. payload.append(data, data_len);
  5278. return true;
  5279. })) {
  5280. ok = false;
  5281. return;
  5282. }
  5283. if (!payload.empty()) {
  5284. // Emit chunked response header and footer for each chunk
  5285. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5286. if (!write_data(strm, chunk.data(), chunk.size())) {
  5287. ok = false;
  5288. return;
  5289. }
  5290. }
  5291. constexpr const char done_marker[] = "0\r\n";
  5292. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  5293. // Trailer
  5294. if (trailer) {
  5295. for (const auto &kv : *trailer) {
  5296. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  5297. if (!write_data(strm, field_line.data(), field_line.size())) {
  5298. ok = false;
  5299. }
  5300. }
  5301. }
  5302. constexpr const char crlf[] = "\r\n";
  5303. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  5304. };
  5305. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  5306. data_sink.done_with_trailer = [&](const Headers &trailer) {
  5307. done_with_trailer(&trailer);
  5308. };
  5309. while (data_available && !is_shutting_down()) {
  5310. if (!strm.wait_writable()) {
  5311. error = Error::Write;
  5312. return false;
  5313. } else if (!content_provider(offset, 0, data_sink)) {
  5314. error = Error::Canceled;
  5315. return false;
  5316. } else if (!ok) {
  5317. error = Error::Write;
  5318. return false;
  5319. }
  5320. }
  5321. error = Error::Success;
  5322. return true;
  5323. }
  5324. template <typename T, typename U>
  5325. inline bool write_content_chunked(Stream &strm,
  5326. const ContentProvider &content_provider,
  5327. const T &is_shutting_down, U &compressor) {
  5328. auto error = Error::Success;
  5329. return write_content_chunked(strm, content_provider, is_shutting_down,
  5330. compressor, error);
  5331. }
  5332. template <typename T>
  5333. inline bool redirect(T &cli, Request &req, Response &res,
  5334. const std::string &path, const std::string &location,
  5335. Error &error) {
  5336. Request new_req = req;
  5337. new_req.path = path;
  5338. new_req.redirect_count_ -= 1;
  5339. if (res.status == StatusCode::SeeOther_303 &&
  5340. (req.method != "GET" && req.method != "HEAD")) {
  5341. new_req.method = "GET";
  5342. new_req.body.clear();
  5343. new_req.headers.clear();
  5344. }
  5345. Response new_res;
  5346. auto ret = cli.send(new_req, new_res, error);
  5347. if (ret) {
  5348. req = std::move(new_req);
  5349. res = std::move(new_res);
  5350. if (res.location.empty()) { res.location = location; }
  5351. }
  5352. return ret;
  5353. }
  5354. inline std::string params_to_query_str(const Params &params) {
  5355. std::string query;
  5356. for (auto it = params.begin(); it != params.end(); ++it) {
  5357. if (it != params.begin()) { query += '&'; }
  5358. query += encode_query_component(it->first);
  5359. query += '=';
  5360. query += encode_query_component(it->second);
  5361. }
  5362. return query;
  5363. }
  5364. inline void parse_query_text(const char *data, std::size_t size,
  5365. Params &params) {
  5366. std::set<std::string> cache;
  5367. split(data, data + size, '&', [&](const char *b, const char *e) {
  5368. std::string kv(b, e);
  5369. if (cache.find(kv) != cache.end()) { return; }
  5370. cache.insert(std::move(kv));
  5371. std::string key;
  5372. std::string val;
  5373. divide(b, static_cast<std::size_t>(e - b), '=',
  5374. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  5375. std::size_t rhs_size) {
  5376. key.assign(lhs_data, lhs_size);
  5377. val.assign(rhs_data, rhs_size);
  5378. });
  5379. if (!key.empty()) {
  5380. params.emplace(decode_query_component(key), decode_query_component(val));
  5381. }
  5382. });
  5383. }
  5384. inline void parse_query_text(const std::string &s, Params &params) {
  5385. parse_query_text(s.data(), s.size(), params);
  5386. }
  5387. // Normalize a query string by decoding and re-encoding each key/value pair
  5388. // while preserving the original parameter order. This avoids double-encoding
  5389. // and ensures consistent encoding without reordering (unlike Params which
  5390. // uses std::multimap and sorts keys).
  5391. inline std::string normalize_query_string(const std::string &query) {
  5392. std::string result;
  5393. split(query.data(), query.data() + query.size(), '&',
  5394. [&](const char *b, const char *e) {
  5395. std::string key;
  5396. std::string val;
  5397. divide(b, static_cast<std::size_t>(e - b), '=',
  5398. [&](const char *lhs_data, std::size_t lhs_size,
  5399. const char *rhs_data, std::size_t rhs_size) {
  5400. key.assign(lhs_data, lhs_size);
  5401. val.assign(rhs_data, rhs_size);
  5402. });
  5403. if (!key.empty()) {
  5404. auto dec_key = decode_query_component(key);
  5405. auto dec_val = decode_query_component(val);
  5406. if (!result.empty()) { result += '&'; }
  5407. result += encode_query_component(dec_key);
  5408. if (!val.empty() || std::find(b, e, '=') != e) {
  5409. result += '=';
  5410. result += encode_query_component(dec_val);
  5411. }
  5412. }
  5413. });
  5414. return result;
  5415. }
  5416. inline bool parse_multipart_boundary(const std::string &content_type,
  5417. std::string &boundary) {
  5418. auto boundary_keyword = "boundary=";
  5419. auto pos = content_type.find(boundary_keyword);
  5420. if (pos == std::string::npos) { return false; }
  5421. auto end = content_type.find(';', pos);
  5422. auto beg = pos + strlen(boundary_keyword);
  5423. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  5424. return !boundary.empty();
  5425. }
  5426. inline void parse_disposition_params(const std::string &s, Params &params) {
  5427. std::set<std::string> cache;
  5428. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  5429. std::string kv(b, e);
  5430. if (cache.find(kv) != cache.end()) { return; }
  5431. cache.insert(kv);
  5432. std::string key;
  5433. std::string val;
  5434. split(b, e, '=', [&](const char *b2, const char *e2) {
  5435. if (key.empty()) {
  5436. key.assign(b2, e2);
  5437. } else {
  5438. val.assign(b2, e2);
  5439. }
  5440. });
  5441. if (!key.empty()) {
  5442. params.emplace(trim_double_quotes_copy((key)),
  5443. trim_double_quotes_copy((val)));
  5444. }
  5445. });
  5446. }
  5447. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5448. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  5449. #else
  5450. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  5451. #endif
  5452. auto is_valid = [](const std::string &str) {
  5453. return std::all_of(str.cbegin(), str.cend(),
  5454. [](unsigned char c) { return std::isdigit(c); });
  5455. };
  5456. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  5457. const auto pos = static_cast<size_t>(6);
  5458. const auto len = static_cast<size_t>(s.size() - 6);
  5459. auto all_valid_ranges = true;
  5460. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  5461. if (!all_valid_ranges) { return; }
  5462. const auto it = std::find(b, e, '-');
  5463. if (it == e) {
  5464. all_valid_ranges = false;
  5465. return;
  5466. }
  5467. const auto lhs = std::string(b, it);
  5468. const auto rhs = std::string(it + 1, e);
  5469. if (!is_valid(lhs) || !is_valid(rhs)) {
  5470. all_valid_ranges = false;
  5471. return;
  5472. }
  5473. const auto first =
  5474. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  5475. const auto last =
  5476. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  5477. if ((first == -1 && last == -1) ||
  5478. (first != -1 && last != -1 && first > last)) {
  5479. all_valid_ranges = false;
  5480. return;
  5481. }
  5482. ranges.emplace_back(first, last);
  5483. });
  5484. return all_valid_ranges && !ranges.empty();
  5485. }
  5486. return false;
  5487. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5488. }
  5489. #else
  5490. } catch (...) { return false; }
  5491. #endif
  5492. inline bool parse_accept_header(const std::string &s,
  5493. std::vector<std::string> &content_types) {
  5494. content_types.clear();
  5495. // Empty string is considered valid (no preference)
  5496. if (s.empty()) { return true; }
  5497. // Check for invalid patterns: leading/trailing commas or consecutive commas
  5498. if (s.front() == ',' || s.back() == ',' ||
  5499. s.find(",,") != std::string::npos) {
  5500. return false;
  5501. }
  5502. struct AcceptEntry {
  5503. std::string media_type;
  5504. double quality;
  5505. int order; // Original order in header
  5506. };
  5507. std::vector<AcceptEntry> entries;
  5508. int order = 0;
  5509. bool has_invalid_entry = false;
  5510. // Split by comma and parse each entry
  5511. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5512. std::string entry(b, e);
  5513. entry = trim_copy(entry);
  5514. if (entry.empty()) {
  5515. has_invalid_entry = true;
  5516. return;
  5517. }
  5518. AcceptEntry accept_entry;
  5519. accept_entry.quality = 1.0; // Default quality
  5520. accept_entry.order = order++;
  5521. // Find q= parameter
  5522. auto q_pos = entry.find(";q=");
  5523. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  5524. if (q_pos != std::string::npos) {
  5525. // Extract media type (before q parameter)
  5526. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  5527. // Extract quality value
  5528. auto q_start = entry.find('=', q_pos) + 1;
  5529. auto q_end = entry.find(';', q_start);
  5530. if (q_end == std::string::npos) { q_end = entry.length(); }
  5531. std::string quality_str =
  5532. trim_copy(entry.substr(q_start, q_end - q_start));
  5533. if (quality_str.empty()) {
  5534. has_invalid_entry = true;
  5535. return;
  5536. }
  5537. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5538. {
  5539. std::istringstream iss(quality_str);
  5540. iss >> accept_entry.quality;
  5541. // Check if conversion was successful and entire string was consumed
  5542. if (iss.fail() || !iss.eof()) {
  5543. has_invalid_entry = true;
  5544. return;
  5545. }
  5546. }
  5547. #else
  5548. try {
  5549. accept_entry.quality = std::stod(quality_str);
  5550. } catch (...) {
  5551. has_invalid_entry = true;
  5552. return;
  5553. }
  5554. #endif
  5555. // Check if quality is in valid range [0.0, 1.0]
  5556. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  5557. has_invalid_entry = true;
  5558. return;
  5559. }
  5560. } else {
  5561. // No quality parameter, use entire entry as media type
  5562. accept_entry.media_type = entry;
  5563. }
  5564. // Remove additional parameters from media type
  5565. auto param_pos = accept_entry.media_type.find(';');
  5566. if (param_pos != std::string::npos) {
  5567. accept_entry.media_type =
  5568. trim_copy(accept_entry.media_type.substr(0, param_pos));
  5569. }
  5570. // Basic validation of media type format
  5571. if (accept_entry.media_type.empty()) {
  5572. has_invalid_entry = true;
  5573. return;
  5574. }
  5575. // Check for basic media type format (should contain '/' or be '*')
  5576. if (accept_entry.media_type != "*" &&
  5577. accept_entry.media_type.find('/') == std::string::npos) {
  5578. has_invalid_entry = true;
  5579. return;
  5580. }
  5581. entries.push_back(std::move(accept_entry));
  5582. });
  5583. // Return false if any invalid entry was found
  5584. if (has_invalid_entry) { return false; }
  5585. // Sort by quality (descending), then by original order (ascending)
  5586. std::sort(entries.begin(), entries.end(),
  5587. [](const AcceptEntry &a, const AcceptEntry &b) {
  5588. if (a.quality != b.quality) {
  5589. return a.quality > b.quality; // Higher quality first
  5590. }
  5591. return a.order < b.order; // Earlier order first for same quality
  5592. });
  5593. // Extract sorted media types
  5594. content_types.reserve(entries.size());
  5595. for (auto &entry : entries) {
  5596. content_types.push_back(std::move(entry.media_type));
  5597. }
  5598. return true;
  5599. }
  5600. class FormDataParser {
  5601. public:
  5602. FormDataParser() = default;
  5603. void set_boundary(std::string &&boundary) {
  5604. boundary_ = std::move(boundary);
  5605. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  5606. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  5607. }
  5608. bool is_valid() const { return is_valid_; }
  5609. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  5610. const ContentReceiver &content_callback) {
  5611. buf_append(buf, n);
  5612. while (buf_size() > 0) {
  5613. switch (state_) {
  5614. case 0: { // Initial boundary
  5615. auto pos = buf_find(dash_boundary_crlf_);
  5616. if (pos == buf_size()) { return true; }
  5617. buf_erase(pos + dash_boundary_crlf_.size());
  5618. state_ = 1;
  5619. break;
  5620. }
  5621. case 1: { // New entry
  5622. clear_file_info();
  5623. state_ = 2;
  5624. break;
  5625. }
  5626. case 2: { // Headers
  5627. auto pos = buf_find(crlf_);
  5628. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5629. while (pos < buf_size()) {
  5630. // Empty line
  5631. if (pos == 0) {
  5632. if (!header_callback(file_)) {
  5633. is_valid_ = false;
  5634. return false;
  5635. }
  5636. buf_erase(crlf_.size());
  5637. state_ = 3;
  5638. break;
  5639. }
  5640. const auto header = buf_head(pos);
  5641. if (!parse_header(header.data(), header.data() + header.size(),
  5642. [&](const std::string &, const std::string &) {})) {
  5643. is_valid_ = false;
  5644. return false;
  5645. }
  5646. // Parse and emplace space trimmed headers into a map
  5647. if (!parse_header(
  5648. header.data(), header.data() + header.size(),
  5649. [&](const std::string &key, const std::string &val) {
  5650. file_.headers.emplace(key, val);
  5651. })) {
  5652. is_valid_ = false;
  5653. return false;
  5654. }
  5655. constexpr const char header_content_type[] = "Content-Type:";
  5656. if (start_with_case_ignore(header, header_content_type)) {
  5657. file_.content_type =
  5658. trim_copy(header.substr(str_len(header_content_type)));
  5659. } else {
  5660. thread_local const std::regex re_content_disposition(
  5661. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  5662. std::regex_constants::icase);
  5663. std::smatch m;
  5664. if (std::regex_match(header, m, re_content_disposition)) {
  5665. Params params;
  5666. parse_disposition_params(m[1], params);
  5667. auto it = params.find("name");
  5668. if (it != params.end()) {
  5669. file_.name = it->second;
  5670. } else {
  5671. is_valid_ = false;
  5672. return false;
  5673. }
  5674. it = params.find("filename");
  5675. if (it != params.end()) { file_.filename = it->second; }
  5676. it = params.find("filename*");
  5677. if (it != params.end()) {
  5678. // Only allow UTF-8 encoding...
  5679. thread_local const std::regex re_rfc5987_encoding(
  5680. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  5681. std::smatch m2;
  5682. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  5683. file_.filename = decode_path_component(m2[1]); // override...
  5684. } else {
  5685. is_valid_ = false;
  5686. return false;
  5687. }
  5688. }
  5689. }
  5690. }
  5691. buf_erase(pos + crlf_.size());
  5692. pos = buf_find(crlf_);
  5693. }
  5694. if (state_ != 3) { return true; }
  5695. break;
  5696. }
  5697. case 3: { // Body
  5698. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  5699. auto pos = buf_find(crlf_dash_boundary_);
  5700. if (pos < buf_size()) {
  5701. if (!content_callback(buf_data(), pos)) {
  5702. is_valid_ = false;
  5703. return false;
  5704. }
  5705. buf_erase(pos + crlf_dash_boundary_.size());
  5706. state_ = 4;
  5707. } else {
  5708. auto len = buf_size() - crlf_dash_boundary_.size();
  5709. if (len > 0) {
  5710. if (!content_callback(buf_data(), len)) {
  5711. is_valid_ = false;
  5712. return false;
  5713. }
  5714. buf_erase(len);
  5715. }
  5716. return true;
  5717. }
  5718. break;
  5719. }
  5720. case 4: { // Boundary
  5721. if (crlf_.size() > buf_size()) { return true; }
  5722. if (buf_start_with(crlf_)) {
  5723. buf_erase(crlf_.size());
  5724. state_ = 1;
  5725. } else {
  5726. if (dash_.size() > buf_size()) { return true; }
  5727. if (buf_start_with(dash_)) {
  5728. buf_erase(dash_.size());
  5729. is_valid_ = true;
  5730. buf_erase(buf_size()); // Remove epilogue
  5731. } else {
  5732. return true;
  5733. }
  5734. }
  5735. break;
  5736. }
  5737. }
  5738. }
  5739. return true;
  5740. }
  5741. private:
  5742. void clear_file_info() {
  5743. file_.name.clear();
  5744. file_.filename.clear();
  5745. file_.content_type.clear();
  5746. file_.headers.clear();
  5747. }
  5748. bool start_with_case_ignore(const std::string &a, const char *b) const {
  5749. const auto b_len = strlen(b);
  5750. if (a.size() < b_len) { return false; }
  5751. for (size_t i = 0; i < b_len; i++) {
  5752. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  5753. return false;
  5754. }
  5755. }
  5756. return true;
  5757. }
  5758. const std::string dash_ = "--";
  5759. const std::string crlf_ = "\r\n";
  5760. std::string boundary_;
  5761. std::string dash_boundary_crlf_;
  5762. std::string crlf_dash_boundary_;
  5763. size_t state_ = 0;
  5764. bool is_valid_ = false;
  5765. FormData file_;
  5766. // Buffer
  5767. bool start_with(const std::string &a, size_t spos, size_t epos,
  5768. const std::string &b) const {
  5769. if (epos - spos < b.size()) { return false; }
  5770. for (size_t i = 0; i < b.size(); i++) {
  5771. if (a[i + spos] != b[i]) { return false; }
  5772. }
  5773. return true;
  5774. }
  5775. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  5776. const char *buf_data() const { return &buf_[buf_spos_]; }
  5777. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  5778. bool buf_start_with(const std::string &s) const {
  5779. return start_with(buf_, buf_spos_, buf_epos_, s);
  5780. }
  5781. size_t buf_find(const std::string &s) const {
  5782. auto c = s.front();
  5783. size_t off = buf_spos_;
  5784. while (off < buf_epos_) {
  5785. auto pos = off;
  5786. while (true) {
  5787. if (pos == buf_epos_) { return buf_size(); }
  5788. if (buf_[pos] == c) { break; }
  5789. pos++;
  5790. }
  5791. auto remaining_size = buf_epos_ - pos;
  5792. if (s.size() > remaining_size) { return buf_size(); }
  5793. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  5794. off = pos + 1;
  5795. }
  5796. return buf_size();
  5797. }
  5798. void buf_append(const char *data, size_t n) {
  5799. auto remaining_size = buf_size();
  5800. if (remaining_size > 0 && buf_spos_ > 0) {
  5801. for (size_t i = 0; i < remaining_size; i++) {
  5802. buf_[i] = buf_[buf_spos_ + i];
  5803. }
  5804. }
  5805. buf_spos_ = 0;
  5806. buf_epos_ = remaining_size;
  5807. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  5808. for (size_t i = 0; i < n; i++) {
  5809. buf_[buf_epos_ + i] = data[i];
  5810. }
  5811. buf_epos_ += n;
  5812. }
  5813. void buf_erase(size_t size) { buf_spos_ += size; }
  5814. std::string buf_;
  5815. size_t buf_spos_ = 0;
  5816. size_t buf_epos_ = 0;
  5817. };
  5818. inline std::string random_string(size_t length) {
  5819. constexpr const char data[] =
  5820. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  5821. thread_local auto engine([]() {
  5822. // std::random_device might actually be deterministic on some
  5823. // platforms, but due to lack of support in the c++ standard library,
  5824. // doing better requires either some ugly hacks or breaking portability.
  5825. std::random_device seed_gen;
  5826. // Request 128 bits of entropy for initialization
  5827. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  5828. return std::mt19937(seed_sequence);
  5829. }());
  5830. std::string result;
  5831. for (size_t i = 0; i < length; i++) {
  5832. result += data[engine() % (sizeof(data) - 1)];
  5833. }
  5834. return result;
  5835. }
  5836. inline std::string make_multipart_data_boundary() {
  5837. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  5838. }
  5839. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  5840. auto valid = true;
  5841. for (size_t i = 0; i < boundary.size(); i++) {
  5842. auto c = boundary[i];
  5843. if (!std::isalnum(c) && c != '-' && c != '_') {
  5844. valid = false;
  5845. break;
  5846. }
  5847. }
  5848. return valid;
  5849. }
  5850. template <typename T>
  5851. inline std::string
  5852. serialize_multipart_formdata_item_begin(const T &item,
  5853. const std::string &boundary) {
  5854. std::string body = "--" + boundary + "\r\n";
  5855. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5856. if (!item.filename.empty()) {
  5857. body += "; filename=\"" + item.filename + "\"";
  5858. }
  5859. body += "\r\n";
  5860. if (!item.content_type.empty()) {
  5861. body += "Content-Type: " + item.content_type + "\r\n";
  5862. }
  5863. body += "\r\n";
  5864. return body;
  5865. }
  5866. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  5867. inline std::string
  5868. serialize_multipart_formdata_finish(const std::string &boundary) {
  5869. return "--" + boundary + "--\r\n";
  5870. }
  5871. inline std::string
  5872. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  5873. return "multipart/form-data; boundary=" + boundary;
  5874. }
  5875. inline std::string
  5876. serialize_multipart_formdata(const UploadFormDataItems &items,
  5877. const std::string &boundary, bool finish = true) {
  5878. std::string body;
  5879. for (const auto &item : items) {
  5880. body += serialize_multipart_formdata_item_begin(item, boundary);
  5881. body += item.content + serialize_multipart_formdata_item_end();
  5882. }
  5883. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  5884. return body;
  5885. }
  5886. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  5887. if (ranges.size() <= 1) return;
  5888. // Sort ranges by start position
  5889. std::sort(ranges.begin(), ranges.end(),
  5890. [](const Range &a, const Range &b) { return a.first < b.first; });
  5891. Ranges coalesced;
  5892. coalesced.reserve(ranges.size());
  5893. for (auto &r : ranges) {
  5894. auto first_pos = r.first;
  5895. auto last_pos = r.second;
  5896. // Handle special cases like in range_error
  5897. if (first_pos == -1 && last_pos == -1) {
  5898. first_pos = 0;
  5899. last_pos = static_cast<ssize_t>(content_length);
  5900. }
  5901. if (first_pos == -1) {
  5902. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  5903. last_pos = static_cast<ssize_t>(content_length) - 1;
  5904. }
  5905. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  5906. last_pos = static_cast<ssize_t>(content_length) - 1;
  5907. }
  5908. // Skip invalid ranges
  5909. if (!(0 <= first_pos && first_pos <= last_pos &&
  5910. last_pos < static_cast<ssize_t>(content_length))) {
  5911. continue;
  5912. }
  5913. // Coalesce with previous range if overlapping or adjacent (but not
  5914. // identical)
  5915. if (!coalesced.empty()) {
  5916. auto &prev = coalesced.back();
  5917. // Check if current range overlaps or is adjacent to previous range
  5918. // but don't coalesce identical ranges (allow duplicates)
  5919. if (first_pos <= prev.second + 1 &&
  5920. !(first_pos == prev.first && last_pos == prev.second)) {
  5921. // Extend the previous range
  5922. prev.second = (std::max)(prev.second, last_pos);
  5923. continue;
  5924. }
  5925. }
  5926. // Add new range
  5927. coalesced.emplace_back(first_pos, last_pos);
  5928. }
  5929. ranges = std::move(coalesced);
  5930. }
  5931. inline bool range_error(Request &req, Response &res) {
  5932. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  5933. ssize_t content_len = static_cast<ssize_t>(
  5934. res.content_length_ ? res.content_length_ : res.body.size());
  5935. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  5936. size_t overwrapping_count = 0;
  5937. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  5938. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  5939. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  5940. // Too many ranges
  5941. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  5942. for (auto &r : req.ranges) {
  5943. auto &first_pos = r.first;
  5944. auto &last_pos = r.second;
  5945. if (first_pos == -1 && last_pos == -1) {
  5946. first_pos = 0;
  5947. last_pos = content_len;
  5948. }
  5949. if (first_pos == -1) {
  5950. first_pos = content_len - last_pos;
  5951. last_pos = content_len - 1;
  5952. }
  5953. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  5954. // A client can limit the number of bytes requested without knowing the
  5955. // size of the selected representation. If the last-pos value is absent,
  5956. // or if the value is greater than or equal to the current length of the
  5957. // representation data, the byte range is interpreted as the remainder of
  5958. // the representation (i.e., the server replaces the value of last-pos
  5959. // with a value that is one less than the current length of the selected
  5960. // representation).
  5961. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  5962. if (last_pos == -1 || last_pos >= content_len) {
  5963. last_pos = content_len - 1;
  5964. }
  5965. // Range must be within content length
  5966. if (!(0 <= first_pos && first_pos <= last_pos &&
  5967. last_pos <= content_len - 1)) {
  5968. return true;
  5969. }
  5970. // Request must not have more than two overlapping ranges
  5971. for (const auto &processed_range : processed_ranges) {
  5972. if (!(last_pos < processed_range.first ||
  5973. first_pos > processed_range.second)) {
  5974. overwrapping_count++;
  5975. if (overwrapping_count > 2) { return true; }
  5976. break; // Only count once per range
  5977. }
  5978. }
  5979. processed_ranges.emplace_back(first_pos, last_pos);
  5980. }
  5981. // After validation, coalesce overlapping ranges as per RFC 9110
  5982. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  5983. }
  5984. return false;
  5985. }
  5986. inline std::pair<size_t, size_t>
  5987. get_range_offset_and_length(Range r, size_t content_length) {
  5988. assert(r.first != -1 && r.second != -1);
  5989. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  5990. assert(r.first <= r.second &&
  5991. r.second < static_cast<ssize_t>(content_length));
  5992. (void)(content_length);
  5993. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  5994. }
  5995. inline std::string make_content_range_header_field(
  5996. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  5997. auto st = offset_and_length.first;
  5998. auto ed = st + offset_and_length.second - 1;
  5999. std::string field = "bytes ";
  6000. field += std::to_string(st);
  6001. field += '-';
  6002. field += std::to_string(ed);
  6003. field += '/';
  6004. field += std::to_string(content_length);
  6005. return field;
  6006. }
  6007. template <typename SToken, typename CToken, typename Content>
  6008. bool process_multipart_ranges_data(const Request &req,
  6009. const std::string &boundary,
  6010. const std::string &content_type,
  6011. size_t content_length, SToken stoken,
  6012. CToken ctoken, Content content) {
  6013. for (size_t i = 0; i < req.ranges.size(); i++) {
  6014. ctoken("--");
  6015. stoken(boundary);
  6016. ctoken("\r\n");
  6017. if (!content_type.empty()) {
  6018. ctoken("Content-Type: ");
  6019. stoken(content_type);
  6020. ctoken("\r\n");
  6021. }
  6022. auto offset_and_length =
  6023. get_range_offset_and_length(req.ranges[i], content_length);
  6024. ctoken("Content-Range: ");
  6025. stoken(make_content_range_header_field(offset_and_length, content_length));
  6026. ctoken("\r\n");
  6027. ctoken("\r\n");
  6028. if (!content(offset_and_length.first, offset_and_length.second)) {
  6029. return false;
  6030. }
  6031. ctoken("\r\n");
  6032. }
  6033. ctoken("--");
  6034. stoken(boundary);
  6035. ctoken("--");
  6036. return true;
  6037. }
  6038. inline void make_multipart_ranges_data(const Request &req, Response &res,
  6039. const std::string &boundary,
  6040. const std::string &content_type,
  6041. size_t content_length,
  6042. std::string &data) {
  6043. process_multipart_ranges_data(
  6044. req, boundary, content_type, content_length,
  6045. [&](const std::string &token) { data += token; },
  6046. [&](const std::string &token) { data += token; },
  6047. [&](size_t offset, size_t length) {
  6048. assert(offset + length <= content_length);
  6049. data += res.body.substr(offset, length);
  6050. return true;
  6051. });
  6052. }
  6053. inline size_t get_multipart_ranges_data_length(const Request &req,
  6054. const std::string &boundary,
  6055. const std::string &content_type,
  6056. size_t content_length) {
  6057. size_t data_length = 0;
  6058. process_multipart_ranges_data(
  6059. req, boundary, content_type, content_length,
  6060. [&](const std::string &token) { data_length += token.size(); },
  6061. [&](const std::string &token) { data_length += token.size(); },
  6062. [&](size_t /*offset*/, size_t length) {
  6063. data_length += length;
  6064. return true;
  6065. });
  6066. return data_length;
  6067. }
  6068. template <typename T>
  6069. inline bool
  6070. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  6071. const std::string &boundary,
  6072. const std::string &content_type,
  6073. size_t content_length, const T &is_shutting_down) {
  6074. return process_multipart_ranges_data(
  6075. req, boundary, content_type, content_length,
  6076. [&](const std::string &token) { strm.write(token); },
  6077. [&](const std::string &token) { strm.write(token); },
  6078. [&](size_t offset, size_t length) {
  6079. return write_content(strm, res.content_provider_, offset, length,
  6080. is_shutting_down);
  6081. });
  6082. }
  6083. inline bool expect_content(const Request &req) {
  6084. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  6085. req.method == "DELETE") {
  6086. return true;
  6087. }
  6088. if (req.has_header("Content-Length") &&
  6089. req.get_header_value_u64("Content-Length") > 0) {
  6090. return true;
  6091. }
  6092. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  6093. return false;
  6094. }
  6095. inline bool has_crlf(const std::string &s) {
  6096. auto p = s.c_str();
  6097. while (*p) {
  6098. if (*p == '\r' || *p == '\n') { return true; }
  6099. p++;
  6100. }
  6101. return false;
  6102. }
  6103. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6104. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  6105. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  6106. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  6107. unsigned int hash_length = 0;
  6108. unsigned char hash[EVP_MAX_MD_SIZE];
  6109. EVP_DigestInit_ex(context.get(), algo, nullptr);
  6110. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  6111. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  6112. std::stringstream ss;
  6113. for (auto i = 0u; i < hash_length; ++i) {
  6114. ss << std::hex << std::setw(2) << std::setfill('0')
  6115. << static_cast<unsigned int>(hash[i]);
  6116. }
  6117. return ss.str();
  6118. }
  6119. inline std::string MD5(const std::string &s) {
  6120. return message_digest(s, EVP_md5());
  6121. }
  6122. inline std::string SHA_256(const std::string &s) {
  6123. return message_digest(s, EVP_sha256());
  6124. }
  6125. inline std::string SHA_512(const std::string &s) {
  6126. return message_digest(s, EVP_sha512());
  6127. }
  6128. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  6129. inline std::string MD5(const std::string &s) {
  6130. unsigned char hash[16];
  6131. #if MBEDTLS_VERSION_MAJOR >= 3
  6132. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6133. hash);
  6134. #else
  6135. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6136. hash);
  6137. #endif
  6138. std::stringstream ss;
  6139. for (auto i = 0u; i < 16; ++i) {
  6140. ss << std::hex << std::setw(2) << std::setfill('0')
  6141. << static_cast<unsigned int>(hash[i]);
  6142. }
  6143. return ss.str();
  6144. }
  6145. inline std::string SHA_256(const std::string &s) {
  6146. unsigned char hash[32];
  6147. #if MBEDTLS_VERSION_MAJOR >= 3
  6148. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6149. hash, 0);
  6150. #else
  6151. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6152. s.size(), hash, 0);
  6153. #endif
  6154. std::stringstream ss;
  6155. for (auto i = 0u; i < 32; ++i) {
  6156. ss << std::hex << std::setw(2) << std::setfill('0')
  6157. << static_cast<unsigned int>(hash[i]);
  6158. }
  6159. return ss.str();
  6160. }
  6161. inline std::string SHA_512(const std::string &s) {
  6162. unsigned char hash[64];
  6163. #if MBEDTLS_VERSION_MAJOR >= 3
  6164. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6165. hash, 0);
  6166. #else
  6167. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6168. s.size(), hash, 0);
  6169. #endif
  6170. std::stringstream ss;
  6171. for (auto i = 0u; i < 64; ++i) {
  6172. ss << std::hex << std::setw(2) << std::setfill('0')
  6173. << static_cast<unsigned int>(hash[i]);
  6174. }
  6175. return ss.str();
  6176. }
  6177. #endif
  6178. #ifdef CPPHTTPLIB_SSL_ENABLED
  6179. inline std::pair<std::string, std::string> make_digest_authentication_header(
  6180. const Request &req, const std::map<std::string, std::string> &auth,
  6181. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  6182. const std::string &password, bool is_proxy = false) {
  6183. std::string nc;
  6184. {
  6185. std::stringstream ss;
  6186. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  6187. nc = ss.str();
  6188. }
  6189. std::string qop;
  6190. if (auth.find("qop") != auth.end()) {
  6191. qop = auth.at("qop");
  6192. if (qop.find("auth-int") != std::string::npos) {
  6193. qop = "auth-int";
  6194. } else if (qop.find("auth") != std::string::npos) {
  6195. qop = "auth";
  6196. } else {
  6197. qop.clear();
  6198. }
  6199. }
  6200. std::string algo = "MD5";
  6201. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  6202. std::string response;
  6203. {
  6204. auto H = algo == "SHA-256" ? detail::SHA_256
  6205. : algo == "SHA-512" ? detail::SHA_512
  6206. : detail::MD5;
  6207. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  6208. auto A2 = req.method + ":" + req.path;
  6209. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  6210. if (qop.empty()) {
  6211. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  6212. } else {
  6213. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  6214. ":" + qop + ":" + H(A2));
  6215. }
  6216. }
  6217. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  6218. auto field = "Digest username=\"" + username + "\", realm=\"" +
  6219. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  6220. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  6221. (qop.empty() ? ", response=\""
  6222. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  6223. cnonce + "\", response=\"") +
  6224. response + "\"" +
  6225. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  6226. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6227. return std::make_pair(key, field);
  6228. }
  6229. #endif // CPPHTTPLIB_SSL_ENABLED
  6230. #ifdef _WIN32
  6231. class WSInit {
  6232. public:
  6233. WSInit() {
  6234. WSADATA wsaData;
  6235. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  6236. }
  6237. ~WSInit() {
  6238. if (is_valid_) WSACleanup();
  6239. }
  6240. bool is_valid_ = false;
  6241. };
  6242. static WSInit wsinit_;
  6243. #endif
  6244. inline bool parse_www_authenticate(const Response &res,
  6245. std::map<std::string, std::string> &auth,
  6246. bool is_proxy) {
  6247. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  6248. if (res.has_header(auth_key)) {
  6249. thread_local auto re =
  6250. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  6251. auto s = res.get_header_value(auth_key);
  6252. auto pos = s.find(' ');
  6253. if (pos != std::string::npos) {
  6254. auto type = s.substr(0, pos);
  6255. if (type == "Basic") {
  6256. return false;
  6257. } else if (type == "Digest") {
  6258. s = s.substr(pos + 1);
  6259. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  6260. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  6261. const auto &m = *i;
  6262. auto key = s.substr(static_cast<size_t>(m.position(1)),
  6263. static_cast<size_t>(m.length(1)));
  6264. auto val = m.length(2) > 0
  6265. ? s.substr(static_cast<size_t>(m.position(2)),
  6266. static_cast<size_t>(m.length(2)))
  6267. : s.substr(static_cast<size_t>(m.position(3)),
  6268. static_cast<size_t>(m.length(3)));
  6269. auth[std::move(key)] = std::move(val);
  6270. }
  6271. return true;
  6272. }
  6273. }
  6274. }
  6275. return false;
  6276. }
  6277. class ContentProviderAdapter {
  6278. public:
  6279. explicit ContentProviderAdapter(
  6280. ContentProviderWithoutLength &&content_provider)
  6281. : content_provider_(std::move(content_provider)) {}
  6282. bool operator()(size_t offset, size_t, DataSink &sink) {
  6283. return content_provider_(offset, sink);
  6284. }
  6285. private:
  6286. ContentProviderWithoutLength content_provider_;
  6287. };
  6288. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  6289. namespace fields {
  6290. inline bool is_token_char(char c) {
  6291. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  6292. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  6293. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  6294. }
  6295. inline bool is_token(const std::string &s) {
  6296. if (s.empty()) { return false; }
  6297. for (auto c : s) {
  6298. if (!is_token_char(c)) { return false; }
  6299. }
  6300. return true;
  6301. }
  6302. inline bool is_field_name(const std::string &s) { return is_token(s); }
  6303. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  6304. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  6305. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  6306. inline bool is_field_content(const std::string &s) {
  6307. if (s.empty()) { return true; }
  6308. if (s.size() == 1) {
  6309. return is_field_vchar(s[0]);
  6310. } else if (s.size() == 2) {
  6311. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  6312. } else {
  6313. size_t i = 0;
  6314. if (!is_field_vchar(s[i])) { return false; }
  6315. i++;
  6316. while (i < s.size() - 1) {
  6317. auto c = s[i++];
  6318. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  6319. } else {
  6320. return false;
  6321. }
  6322. }
  6323. return is_field_vchar(s[i]);
  6324. }
  6325. }
  6326. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  6327. } // namespace fields
  6328. } // namespace detail
  6329. inline const char *status_message(int status) {
  6330. switch (status) {
  6331. case StatusCode::Continue_100: return "Continue";
  6332. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  6333. case StatusCode::Processing_102: return "Processing";
  6334. case StatusCode::EarlyHints_103: return "Early Hints";
  6335. case StatusCode::OK_200: return "OK";
  6336. case StatusCode::Created_201: return "Created";
  6337. case StatusCode::Accepted_202: return "Accepted";
  6338. case StatusCode::NonAuthoritativeInformation_203:
  6339. return "Non-Authoritative Information";
  6340. case StatusCode::NoContent_204: return "No Content";
  6341. case StatusCode::ResetContent_205: return "Reset Content";
  6342. case StatusCode::PartialContent_206: return "Partial Content";
  6343. case StatusCode::MultiStatus_207: return "Multi-Status";
  6344. case StatusCode::AlreadyReported_208: return "Already Reported";
  6345. case StatusCode::IMUsed_226: return "IM Used";
  6346. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  6347. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  6348. case StatusCode::Found_302: return "Found";
  6349. case StatusCode::SeeOther_303: return "See Other";
  6350. case StatusCode::NotModified_304: return "Not Modified";
  6351. case StatusCode::UseProxy_305: return "Use Proxy";
  6352. case StatusCode::unused_306: return "unused";
  6353. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  6354. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  6355. case StatusCode::BadRequest_400: return "Bad Request";
  6356. case StatusCode::Unauthorized_401: return "Unauthorized";
  6357. case StatusCode::PaymentRequired_402: return "Payment Required";
  6358. case StatusCode::Forbidden_403: return "Forbidden";
  6359. case StatusCode::NotFound_404: return "Not Found";
  6360. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  6361. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  6362. case StatusCode::ProxyAuthenticationRequired_407:
  6363. return "Proxy Authentication Required";
  6364. case StatusCode::RequestTimeout_408: return "Request Timeout";
  6365. case StatusCode::Conflict_409: return "Conflict";
  6366. case StatusCode::Gone_410: return "Gone";
  6367. case StatusCode::LengthRequired_411: return "Length Required";
  6368. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  6369. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  6370. case StatusCode::UriTooLong_414: return "URI Too Long";
  6371. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  6372. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  6373. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  6374. case StatusCode::ImATeapot_418: return "I'm a teapot";
  6375. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  6376. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  6377. case StatusCode::Locked_423: return "Locked";
  6378. case StatusCode::FailedDependency_424: return "Failed Dependency";
  6379. case StatusCode::TooEarly_425: return "Too Early";
  6380. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  6381. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  6382. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  6383. case StatusCode::RequestHeaderFieldsTooLarge_431:
  6384. return "Request Header Fields Too Large";
  6385. case StatusCode::UnavailableForLegalReasons_451:
  6386. return "Unavailable For Legal Reasons";
  6387. case StatusCode::NotImplemented_501: return "Not Implemented";
  6388. case StatusCode::BadGateway_502: return "Bad Gateway";
  6389. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  6390. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  6391. case StatusCode::HttpVersionNotSupported_505:
  6392. return "HTTP Version Not Supported";
  6393. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  6394. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  6395. case StatusCode::LoopDetected_508: return "Loop Detected";
  6396. case StatusCode::NotExtended_510: return "Not Extended";
  6397. case StatusCode::NetworkAuthenticationRequired_511:
  6398. return "Network Authentication Required";
  6399. default:
  6400. case StatusCode::InternalServerError_500: return "Internal Server Error";
  6401. }
  6402. }
  6403. inline std::string to_string(const Error error) {
  6404. switch (error) {
  6405. case Error::Success: return "Success (no error)";
  6406. case Error::Unknown: return "Unknown";
  6407. case Error::Connection: return "Could not establish connection";
  6408. case Error::BindIPAddress: return "Failed to bind IP address";
  6409. case Error::Read: return "Failed to read connection";
  6410. case Error::Write: return "Failed to write connection";
  6411. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  6412. case Error::Canceled: return "Connection handling canceled";
  6413. case Error::SSLConnection: return "SSL connection failed";
  6414. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  6415. case Error::SSLServerVerification: return "SSL server verification failed";
  6416. case Error::SSLServerHostnameVerification:
  6417. return "SSL server hostname verification failed";
  6418. case Error::UnsupportedMultipartBoundaryChars:
  6419. return "Unsupported HTTP multipart boundary characters";
  6420. case Error::Compression: return "Compression failed";
  6421. case Error::ConnectionTimeout: return "Connection timed out";
  6422. case Error::ProxyConnection: return "Proxy connection failed";
  6423. case Error::ConnectionClosed: return "Connection closed by server";
  6424. case Error::Timeout: return "Read timeout";
  6425. case Error::ResourceExhaustion: return "Resource exhaustion";
  6426. case Error::TooManyFormDataFiles: return "Too many form data files";
  6427. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  6428. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  6429. case Error::ExceedMaxSocketDescriptorCount:
  6430. return "Exceeded maximum socket descriptor count";
  6431. case Error::InvalidRequestLine: return "Invalid request line";
  6432. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  6433. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  6434. case Error::InvalidHeaders: return "Invalid headers";
  6435. case Error::MultipartParsing: return "Multipart parsing failed";
  6436. case Error::OpenFile: return "Failed to open file";
  6437. case Error::Listen: return "Failed to listen on socket";
  6438. case Error::GetSockName: return "Failed to get socket name";
  6439. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  6440. case Error::HTTPParsing: return "HTTP parsing failed";
  6441. case Error::InvalidRangeHeader: return "Invalid Range header";
  6442. default: break;
  6443. }
  6444. return "Invalid";
  6445. }
  6446. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  6447. os << to_string(obj);
  6448. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  6449. return os;
  6450. }
  6451. inline std::string hosted_at(const std::string &hostname) {
  6452. std::vector<std::string> addrs;
  6453. hosted_at(hostname, addrs);
  6454. if (addrs.empty()) { return std::string(); }
  6455. return addrs[0];
  6456. }
  6457. inline void hosted_at(const std::string &hostname,
  6458. std::vector<std::string> &addrs) {
  6459. struct addrinfo hints;
  6460. struct addrinfo *result;
  6461. memset(&hints, 0, sizeof(struct addrinfo));
  6462. hints.ai_family = AF_UNSPEC;
  6463. hints.ai_socktype = SOCK_STREAM;
  6464. hints.ai_protocol = 0;
  6465. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  6466. &result, 0)) {
  6467. #if defined __linux__ && !defined __ANDROID__
  6468. res_init();
  6469. #endif
  6470. return;
  6471. }
  6472. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6473. for (auto rp = result; rp; rp = rp->ai_next) {
  6474. const auto &addr =
  6475. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  6476. std::string ip;
  6477. auto dummy = -1;
  6478. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  6479. dummy)) {
  6480. addrs.emplace_back(std::move(ip));
  6481. }
  6482. }
  6483. }
  6484. inline std::string encode_uri_component(const std::string &value) {
  6485. std::ostringstream escaped;
  6486. escaped.fill('0');
  6487. escaped << std::hex;
  6488. for (auto c : value) {
  6489. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6490. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6491. c == ')') {
  6492. escaped << c;
  6493. } else {
  6494. escaped << std::uppercase;
  6495. escaped << '%' << std::setw(2)
  6496. << static_cast<int>(static_cast<unsigned char>(c));
  6497. escaped << std::nouppercase;
  6498. }
  6499. }
  6500. return escaped.str();
  6501. }
  6502. inline std::string encode_uri(const std::string &value) {
  6503. std::ostringstream escaped;
  6504. escaped.fill('0');
  6505. escaped << std::hex;
  6506. for (auto c : value) {
  6507. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6508. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6509. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  6510. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  6511. escaped << c;
  6512. } else {
  6513. escaped << std::uppercase;
  6514. escaped << '%' << std::setw(2)
  6515. << static_cast<int>(static_cast<unsigned char>(c));
  6516. escaped << std::nouppercase;
  6517. }
  6518. }
  6519. return escaped.str();
  6520. }
  6521. inline std::string decode_uri_component(const std::string &value) {
  6522. std::string result;
  6523. for (size_t i = 0; i < value.size(); i++) {
  6524. if (value[i] == '%' && i + 2 < value.size()) {
  6525. auto val = 0;
  6526. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6527. result += static_cast<char>(val);
  6528. i += 2;
  6529. } else {
  6530. result += value[i];
  6531. }
  6532. } else {
  6533. result += value[i];
  6534. }
  6535. }
  6536. return result;
  6537. }
  6538. inline std::string decode_uri(const std::string &value) {
  6539. std::string result;
  6540. for (size_t i = 0; i < value.size(); i++) {
  6541. if (value[i] == '%' && i + 2 < value.size()) {
  6542. auto val = 0;
  6543. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6544. result += static_cast<char>(val);
  6545. i += 2;
  6546. } else {
  6547. result += value[i];
  6548. }
  6549. } else {
  6550. result += value[i];
  6551. }
  6552. }
  6553. return result;
  6554. }
  6555. inline std::string encode_path_component(const std::string &component) {
  6556. std::string result;
  6557. result.reserve(component.size() * 3);
  6558. for (size_t i = 0; i < component.size(); i++) {
  6559. auto c = static_cast<unsigned char>(component[i]);
  6560. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  6561. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6562. result += static_cast<char>(c);
  6563. }
  6564. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  6565. // "," / ";" / "="
  6566. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  6567. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  6568. c == '=') {
  6569. result += static_cast<char>(c);
  6570. }
  6571. // Colon is allowed in path segments except first segment
  6572. else if (c == ':') {
  6573. result += static_cast<char>(c);
  6574. }
  6575. // @ is allowed in path
  6576. else if (c == '@') {
  6577. result += static_cast<char>(c);
  6578. } else {
  6579. result += '%';
  6580. char hex[3];
  6581. snprintf(hex, sizeof(hex), "%02X", c);
  6582. result.append(hex, 2);
  6583. }
  6584. }
  6585. return result;
  6586. }
  6587. inline std::string decode_path_component(const std::string &component) {
  6588. std::string result;
  6589. result.reserve(component.size());
  6590. for (size_t i = 0; i < component.size(); i++) {
  6591. if (component[i] == '%' && i + 1 < component.size()) {
  6592. if (component[i + 1] == 'u') {
  6593. // Unicode %uXXXX encoding
  6594. auto val = 0;
  6595. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  6596. // 4 digits Unicode codes
  6597. char buff[4];
  6598. size_t len = detail::to_utf8(val, buff);
  6599. if (len > 0) { result.append(buff, len); }
  6600. i += 5; // 'u0000'
  6601. } else {
  6602. result += component[i];
  6603. }
  6604. } else {
  6605. // Standard %XX encoding
  6606. auto val = 0;
  6607. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  6608. // 2 digits hex codes
  6609. result += static_cast<char>(val);
  6610. i += 2; // 'XX'
  6611. } else {
  6612. result += component[i];
  6613. }
  6614. }
  6615. } else {
  6616. result += component[i];
  6617. }
  6618. }
  6619. return result;
  6620. }
  6621. inline std::string encode_query_component(const std::string &component,
  6622. bool space_as_plus) {
  6623. std::string result;
  6624. result.reserve(component.size() * 3);
  6625. for (size_t i = 0; i < component.size(); i++) {
  6626. auto c = static_cast<unsigned char>(component[i]);
  6627. // Unreserved characters per RFC 3986
  6628. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6629. result += static_cast<char>(c);
  6630. }
  6631. // Space handling
  6632. else if (c == ' ') {
  6633. if (space_as_plus) {
  6634. result += '+';
  6635. } else {
  6636. result += "%20";
  6637. }
  6638. }
  6639. // Plus sign handling
  6640. else if (c == '+') {
  6641. if (space_as_plus) {
  6642. result += "%2B";
  6643. } else {
  6644. result += static_cast<char>(c);
  6645. }
  6646. }
  6647. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  6648. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  6649. c == '*' || c == ',' || c == ';') {
  6650. result += static_cast<char>(c);
  6651. }
  6652. // Colon and @ are allowed in query
  6653. else if (c == ':' || c == '@') {
  6654. result += static_cast<char>(c);
  6655. }
  6656. // Forward slash is allowed in query values
  6657. else if (c == '/') {
  6658. result += static_cast<char>(c);
  6659. }
  6660. // Question mark is allowed in query values (after first ?)
  6661. else if (c == '?') {
  6662. result += static_cast<char>(c);
  6663. } else {
  6664. result += '%';
  6665. char hex[3];
  6666. snprintf(hex, sizeof(hex), "%02X", c);
  6667. result.append(hex, 2);
  6668. }
  6669. }
  6670. return result;
  6671. }
  6672. inline std::string decode_query_component(const std::string &component,
  6673. bool plus_as_space) {
  6674. std::string result;
  6675. result.reserve(component.size());
  6676. for (size_t i = 0; i < component.size(); i++) {
  6677. if (component[i] == '%' && i + 2 < component.size()) {
  6678. std::string hex = component.substr(i + 1, 2);
  6679. char *end;
  6680. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  6681. if (end == hex.c_str() + 2) {
  6682. result += static_cast<char>(value);
  6683. i += 2;
  6684. } else {
  6685. result += component[i];
  6686. }
  6687. } else if (component[i] == '+' && plus_as_space) {
  6688. result += ' '; // + becomes space in form-urlencoded
  6689. } else {
  6690. result += component[i];
  6691. }
  6692. }
  6693. return result;
  6694. }
  6695. inline std::string append_query_params(const std::string &path,
  6696. const Params &params) {
  6697. std::string path_with_query = path;
  6698. thread_local const std::regex re("[^?]+\\?.*");
  6699. auto delm = std::regex_match(path, re) ? '&' : '?';
  6700. path_with_query += delm + detail::params_to_query_str(params);
  6701. return path_with_query;
  6702. }
  6703. // Header utilities
  6704. inline std::pair<std::string, std::string>
  6705. make_range_header(const Ranges &ranges) {
  6706. std::string field = "bytes=";
  6707. auto i = 0;
  6708. for (const auto &r : ranges) {
  6709. if (i != 0) { field += ", "; }
  6710. if (r.first != -1) { field += std::to_string(r.first); }
  6711. field += '-';
  6712. if (r.second != -1) { field += std::to_string(r.second); }
  6713. i++;
  6714. }
  6715. return std::make_pair("Range", std::move(field));
  6716. }
  6717. inline std::pair<std::string, std::string>
  6718. make_basic_authentication_header(const std::string &username,
  6719. const std::string &password, bool is_proxy) {
  6720. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  6721. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6722. return std::make_pair(key, std::move(field));
  6723. }
  6724. inline std::pair<std::string, std::string>
  6725. make_bearer_token_authentication_header(const std::string &token,
  6726. bool is_proxy = false) {
  6727. auto field = "Bearer " + token;
  6728. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6729. return std::make_pair(key, std::move(field));
  6730. }
  6731. // Request implementation
  6732. inline bool Request::has_header(const std::string &key) const {
  6733. return detail::has_header(headers, key);
  6734. }
  6735. inline std::string Request::get_header_value(const std::string &key,
  6736. const char *def, size_t id) const {
  6737. return detail::get_header_value(headers, key, def, id);
  6738. }
  6739. inline size_t Request::get_header_value_count(const std::string &key) const {
  6740. auto r = headers.equal_range(key);
  6741. return static_cast<size_t>(std::distance(r.first, r.second));
  6742. }
  6743. inline void Request::set_header(const std::string &key,
  6744. const std::string &val) {
  6745. if (detail::fields::is_field_name(key) &&
  6746. detail::fields::is_field_value(val)) {
  6747. headers.emplace(key, val);
  6748. }
  6749. }
  6750. inline bool Request::has_trailer(const std::string &key) const {
  6751. return trailers.find(key) != trailers.end();
  6752. }
  6753. inline std::string Request::get_trailer_value(const std::string &key,
  6754. size_t id) const {
  6755. auto rng = trailers.equal_range(key);
  6756. auto it = rng.first;
  6757. std::advance(it, static_cast<ssize_t>(id));
  6758. if (it != rng.second) { return it->second; }
  6759. return std::string();
  6760. }
  6761. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  6762. auto r = trailers.equal_range(key);
  6763. return static_cast<size_t>(std::distance(r.first, r.second));
  6764. }
  6765. inline bool Request::has_param(const std::string &key) const {
  6766. return params.find(key) != params.end();
  6767. }
  6768. inline std::string Request::get_param_value(const std::string &key,
  6769. size_t id) const {
  6770. auto rng = params.equal_range(key);
  6771. auto it = rng.first;
  6772. std::advance(it, static_cast<ssize_t>(id));
  6773. if (it != rng.second) { return it->second; }
  6774. return std::string();
  6775. }
  6776. inline size_t Request::get_param_value_count(const std::string &key) const {
  6777. auto r = params.equal_range(key);
  6778. return static_cast<size_t>(std::distance(r.first, r.second));
  6779. }
  6780. inline bool Request::is_multipart_form_data() const {
  6781. const auto &content_type = get_header_value("Content-Type");
  6782. return !content_type.rfind("multipart/form-data", 0);
  6783. }
  6784. // Multipart FormData implementation
  6785. inline std::string MultipartFormData::get_field(const std::string &key,
  6786. size_t id) const {
  6787. auto rng = fields.equal_range(key);
  6788. auto it = rng.first;
  6789. std::advance(it, static_cast<ssize_t>(id));
  6790. if (it != rng.second) { return it->second.content; }
  6791. return std::string();
  6792. }
  6793. inline std::vector<std::string>
  6794. MultipartFormData::get_fields(const std::string &key) const {
  6795. std::vector<std::string> values;
  6796. auto rng = fields.equal_range(key);
  6797. for (auto it = rng.first; it != rng.second; it++) {
  6798. values.push_back(it->second.content);
  6799. }
  6800. return values;
  6801. }
  6802. inline bool MultipartFormData::has_field(const std::string &key) const {
  6803. return fields.find(key) != fields.end();
  6804. }
  6805. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  6806. auto r = fields.equal_range(key);
  6807. return static_cast<size_t>(std::distance(r.first, r.second));
  6808. }
  6809. inline FormData MultipartFormData::get_file(const std::string &key,
  6810. size_t id) const {
  6811. auto rng = files.equal_range(key);
  6812. auto it = rng.first;
  6813. std::advance(it, static_cast<ssize_t>(id));
  6814. if (it != rng.second) { return it->second; }
  6815. return FormData();
  6816. }
  6817. inline std::vector<FormData>
  6818. MultipartFormData::get_files(const std::string &key) const {
  6819. std::vector<FormData> values;
  6820. auto rng = files.equal_range(key);
  6821. for (auto it = rng.first; it != rng.second; it++) {
  6822. values.push_back(it->second);
  6823. }
  6824. return values;
  6825. }
  6826. inline bool MultipartFormData::has_file(const std::string &key) const {
  6827. return files.find(key) != files.end();
  6828. }
  6829. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  6830. auto r = files.equal_range(key);
  6831. return static_cast<size_t>(std::distance(r.first, r.second));
  6832. }
  6833. // Response implementation
  6834. inline bool Response::has_header(const std::string &key) const {
  6835. return headers.find(key) != headers.end();
  6836. }
  6837. inline std::string Response::get_header_value(const std::string &key,
  6838. const char *def,
  6839. size_t id) const {
  6840. return detail::get_header_value(headers, key, def, id);
  6841. }
  6842. inline size_t Response::get_header_value_count(const std::string &key) const {
  6843. auto r = headers.equal_range(key);
  6844. return static_cast<size_t>(std::distance(r.first, r.second));
  6845. }
  6846. inline void Response::set_header(const std::string &key,
  6847. const std::string &val) {
  6848. if (detail::fields::is_field_name(key) &&
  6849. detail::fields::is_field_value(val)) {
  6850. headers.emplace(key, val);
  6851. }
  6852. }
  6853. inline bool Response::has_trailer(const std::string &key) const {
  6854. return trailers.find(key) != trailers.end();
  6855. }
  6856. inline std::string Response::get_trailer_value(const std::string &key,
  6857. size_t id) const {
  6858. auto rng = trailers.equal_range(key);
  6859. auto it = rng.first;
  6860. std::advance(it, static_cast<ssize_t>(id));
  6861. if (it != rng.second) { return it->second; }
  6862. return std::string();
  6863. }
  6864. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  6865. auto r = trailers.equal_range(key);
  6866. return static_cast<size_t>(std::distance(r.first, r.second));
  6867. }
  6868. inline void Response::set_redirect(const std::string &url, int stat) {
  6869. if (detail::fields::is_field_value(url)) {
  6870. set_header("Location", url);
  6871. if (300 <= stat && stat < 400) {
  6872. this->status = stat;
  6873. } else {
  6874. this->status = StatusCode::Found_302;
  6875. }
  6876. }
  6877. }
  6878. inline void Response::set_content(const char *s, size_t n,
  6879. const std::string &content_type) {
  6880. body.assign(s, n);
  6881. auto rng = headers.equal_range("Content-Type");
  6882. headers.erase(rng.first, rng.second);
  6883. set_header("Content-Type", content_type);
  6884. }
  6885. inline void Response::set_content(const std::string &s,
  6886. const std::string &content_type) {
  6887. set_content(s.data(), s.size(), content_type);
  6888. }
  6889. inline void Response::set_content(std::string &&s,
  6890. const std::string &content_type) {
  6891. body = std::move(s);
  6892. auto rng = headers.equal_range("Content-Type");
  6893. headers.erase(rng.first, rng.second);
  6894. set_header("Content-Type", content_type);
  6895. }
  6896. inline void Response::set_content_provider(
  6897. size_t in_length, const std::string &content_type, ContentProvider provider,
  6898. ContentProviderResourceReleaser resource_releaser) {
  6899. set_header("Content-Type", content_type);
  6900. content_length_ = in_length;
  6901. if (in_length > 0) { content_provider_ = std::move(provider); }
  6902. content_provider_resource_releaser_ = std::move(resource_releaser);
  6903. is_chunked_content_provider_ = false;
  6904. }
  6905. inline void Response::set_content_provider(
  6906. const std::string &content_type, ContentProviderWithoutLength provider,
  6907. ContentProviderResourceReleaser resource_releaser) {
  6908. set_header("Content-Type", content_type);
  6909. content_length_ = 0;
  6910. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6911. content_provider_resource_releaser_ = std::move(resource_releaser);
  6912. is_chunked_content_provider_ = false;
  6913. }
  6914. inline void Response::set_chunked_content_provider(
  6915. const std::string &content_type, ContentProviderWithoutLength provider,
  6916. ContentProviderResourceReleaser resource_releaser) {
  6917. set_header("Content-Type", content_type);
  6918. content_length_ = 0;
  6919. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6920. content_provider_resource_releaser_ = std::move(resource_releaser);
  6921. is_chunked_content_provider_ = true;
  6922. }
  6923. inline void Response::set_file_content(const std::string &path,
  6924. const std::string &content_type) {
  6925. file_content_path_ = path;
  6926. file_content_content_type_ = content_type;
  6927. }
  6928. inline void Response::set_file_content(const std::string &path) {
  6929. file_content_path_ = path;
  6930. }
  6931. // Result implementation
  6932. inline bool Result::has_request_header(const std::string &key) const {
  6933. return request_headers_.find(key) != request_headers_.end();
  6934. }
  6935. inline std::string Result::get_request_header_value(const std::string &key,
  6936. const char *def,
  6937. size_t id) const {
  6938. return detail::get_header_value(request_headers_, key, def, id);
  6939. }
  6940. inline size_t
  6941. Result::get_request_header_value_count(const std::string &key) const {
  6942. auto r = request_headers_.equal_range(key);
  6943. return static_cast<size_t>(std::distance(r.first, r.second));
  6944. }
  6945. // Stream implementation
  6946. inline ssize_t Stream::write(const char *ptr) {
  6947. return write(ptr, strlen(ptr));
  6948. }
  6949. inline ssize_t Stream::write(const std::string &s) {
  6950. return write(s.data(), s.size());
  6951. }
  6952. // BodyReader implementation
  6953. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  6954. if (!stream) {
  6955. last_error = Error::Connection;
  6956. return -1;
  6957. }
  6958. if (eof) { return 0; }
  6959. if (!chunked) {
  6960. // Content-Length based reading
  6961. if (bytes_read >= content_length) {
  6962. eof = true;
  6963. return 0;
  6964. }
  6965. auto remaining = content_length - bytes_read;
  6966. auto to_read = (std::min)(len, remaining);
  6967. auto n = stream->read(buf, to_read);
  6968. if (n < 0) {
  6969. last_error = stream->get_error();
  6970. if (last_error == Error::Success) { last_error = Error::Read; }
  6971. eof = true;
  6972. return n;
  6973. }
  6974. if (n == 0) {
  6975. // Unexpected EOF before content_length
  6976. last_error = stream->get_error();
  6977. if (last_error == Error::Success) { last_error = Error::Read; }
  6978. eof = true;
  6979. return 0;
  6980. }
  6981. bytes_read += static_cast<size_t>(n);
  6982. if (bytes_read >= content_length) { eof = true; }
  6983. return n;
  6984. }
  6985. // Chunked transfer encoding: delegate to shared decoder instance.
  6986. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  6987. size_t chunk_offset = 0;
  6988. size_t chunk_total = 0;
  6989. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  6990. if (n < 0) {
  6991. last_error = stream->get_error();
  6992. if (last_error == Error::Success) { last_error = Error::Read; }
  6993. eof = true;
  6994. return n;
  6995. }
  6996. if (n == 0) {
  6997. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  6998. eof = true;
  6999. return 0;
  7000. }
  7001. bytes_read += static_cast<size_t>(n);
  7002. return n;
  7003. }
  7004. namespace detail {
  7005. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  7006. time_t timeout_sec, time_t timeout_usec,
  7007. time_t &actual_timeout_sec,
  7008. time_t &actual_timeout_usec) {
  7009. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  7010. auto actual_timeout_msec =
  7011. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  7012. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  7013. actual_timeout_sec = actual_timeout_msec / 1000;
  7014. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  7015. }
  7016. // Socket stream implementation
  7017. inline SocketStream::SocketStream(
  7018. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  7019. time_t write_timeout_sec, time_t write_timeout_usec,
  7020. time_t max_timeout_msec,
  7021. std::chrono::time_point<std::chrono::steady_clock> start_time)
  7022. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  7023. read_timeout_usec_(read_timeout_usec),
  7024. write_timeout_sec_(write_timeout_sec),
  7025. write_timeout_usec_(write_timeout_usec),
  7026. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  7027. read_buff_(read_buff_size_, 0) {}
  7028. inline SocketStream::~SocketStream() = default;
  7029. inline bool SocketStream::is_readable() const {
  7030. return read_buff_off_ < read_buff_content_size_;
  7031. }
  7032. inline bool SocketStream::wait_readable() const {
  7033. if (max_timeout_msec_ <= 0) {
  7034. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  7035. }
  7036. time_t read_timeout_sec;
  7037. time_t read_timeout_usec;
  7038. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  7039. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  7040. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  7041. }
  7042. inline bool SocketStream::wait_writable() const {
  7043. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  7044. is_socket_alive(sock_);
  7045. }
  7046. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  7047. #ifdef _WIN32
  7048. size =
  7049. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7050. #else
  7051. size = (std::min)(size,
  7052. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  7053. #endif
  7054. if (read_buff_off_ < read_buff_content_size_) {
  7055. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  7056. if (size <= remaining_size) {
  7057. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  7058. read_buff_off_ += size;
  7059. return static_cast<ssize_t>(size);
  7060. } else {
  7061. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  7062. read_buff_off_ += remaining_size;
  7063. return static_cast<ssize_t>(remaining_size);
  7064. }
  7065. }
  7066. if (!wait_readable()) {
  7067. error_ = Error::Timeout;
  7068. return -1;
  7069. }
  7070. read_buff_off_ = 0;
  7071. read_buff_content_size_ = 0;
  7072. if (size < read_buff_size_) {
  7073. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  7074. CPPHTTPLIB_RECV_FLAGS);
  7075. if (n <= 0) {
  7076. if (n == 0) {
  7077. error_ = Error::ConnectionClosed;
  7078. } else {
  7079. error_ = Error::Read;
  7080. }
  7081. return n;
  7082. } else if (n <= static_cast<ssize_t>(size)) {
  7083. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  7084. return n;
  7085. } else {
  7086. memcpy(ptr, read_buff_.data(), size);
  7087. read_buff_off_ = size;
  7088. read_buff_content_size_ = static_cast<size_t>(n);
  7089. return static_cast<ssize_t>(size);
  7090. }
  7091. } else {
  7092. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  7093. if (n <= 0) {
  7094. if (n == 0) {
  7095. error_ = Error::ConnectionClosed;
  7096. } else {
  7097. error_ = Error::Read;
  7098. }
  7099. }
  7100. return n;
  7101. }
  7102. }
  7103. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  7104. if (!wait_writable()) { return -1; }
  7105. #if defined(_WIN32) && !defined(_WIN64)
  7106. size =
  7107. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7108. #endif
  7109. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  7110. }
  7111. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  7112. int &port) const {
  7113. return detail::get_remote_ip_and_port(sock_, ip, port);
  7114. }
  7115. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  7116. int &port) const {
  7117. return detail::get_local_ip_and_port(sock_, ip, port);
  7118. }
  7119. inline socket_t SocketStream::socket() const { return sock_; }
  7120. inline time_t SocketStream::duration() const {
  7121. return std::chrono::duration_cast<std::chrono::milliseconds>(
  7122. std::chrono::steady_clock::now() - start_time_)
  7123. .count();
  7124. }
  7125. // Buffer stream implementation
  7126. inline bool BufferStream::is_readable() const { return true; }
  7127. inline bool BufferStream::wait_readable() const { return true; }
  7128. inline bool BufferStream::wait_writable() const { return true; }
  7129. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  7130. #if defined(_MSC_VER) && _MSC_VER < 1910
  7131. auto len_read = buffer._Copy_s(ptr, size, size, position);
  7132. #else
  7133. auto len_read = buffer.copy(ptr, size, position);
  7134. #endif
  7135. position += static_cast<size_t>(len_read);
  7136. return static_cast<ssize_t>(len_read);
  7137. }
  7138. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  7139. buffer.append(ptr, size);
  7140. return static_cast<ssize_t>(size);
  7141. }
  7142. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  7143. int & /*port*/) const {}
  7144. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  7145. int & /*port*/) const {}
  7146. inline socket_t BufferStream::socket() const { return 0; }
  7147. inline time_t BufferStream::duration() const { return 0; }
  7148. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  7149. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  7150. : MatcherBase(pattern) {
  7151. constexpr const char marker[] = "/:";
  7152. // One past the last ending position of a path param substring
  7153. std::size_t last_param_end = 0;
  7154. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7155. // Needed to ensure that parameter names are unique during matcher
  7156. // construction
  7157. // If exceptions are disabled, only last duplicate path
  7158. // parameter will be set
  7159. std::unordered_set<std::string> param_name_set;
  7160. #endif
  7161. while (true) {
  7162. const auto marker_pos = pattern.find(
  7163. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  7164. if (marker_pos == std::string::npos) { break; }
  7165. static_fragments_.push_back(
  7166. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  7167. const auto param_name_start = marker_pos + str_len(marker);
  7168. auto sep_pos = pattern.find(separator, param_name_start);
  7169. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  7170. auto param_name =
  7171. pattern.substr(param_name_start, sep_pos - param_name_start);
  7172. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7173. if (param_name_set.find(param_name) != param_name_set.cend()) {
  7174. std::string msg = "Encountered path parameter '" + param_name +
  7175. "' multiple times in route pattern '" + pattern + "'.";
  7176. throw std::invalid_argument(msg);
  7177. }
  7178. #endif
  7179. param_names_.push_back(std::move(param_name));
  7180. last_param_end = sep_pos + 1;
  7181. }
  7182. if (last_param_end < pattern.length()) {
  7183. static_fragments_.push_back(pattern.substr(last_param_end));
  7184. }
  7185. }
  7186. inline bool PathParamsMatcher::match(Request &request) const {
  7187. request.matches = std::smatch();
  7188. request.path_params.clear();
  7189. request.path_params.reserve(param_names_.size());
  7190. // One past the position at which the path matched the pattern last time
  7191. std::size_t starting_pos = 0;
  7192. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  7193. const auto &fragment = static_fragments_[i];
  7194. if (starting_pos + fragment.length() > request.path.length()) {
  7195. return false;
  7196. }
  7197. // Avoid unnecessary allocation by using strncmp instead of substr +
  7198. // comparison
  7199. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  7200. fragment.length()) != 0) {
  7201. return false;
  7202. }
  7203. starting_pos += fragment.length();
  7204. // Should only happen when we have a static fragment after a param
  7205. // Example: '/users/:id/subscriptions'
  7206. // The 'subscriptions' fragment here does not have a corresponding param
  7207. if (i >= param_names_.size()) { continue; }
  7208. auto sep_pos = request.path.find(separator, starting_pos);
  7209. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  7210. const auto &param_name = param_names_[i];
  7211. request.path_params.emplace(
  7212. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  7213. // Mark everything up to '/' as matched
  7214. starting_pos = sep_pos + 1;
  7215. }
  7216. // Returns false if the path is longer than the pattern
  7217. return starting_pos >= request.path.length();
  7218. }
  7219. inline bool RegexMatcher::match(Request &request) const {
  7220. request.path_params.clear();
  7221. return std::regex_match(request.path, request.matches, regex_);
  7222. }
  7223. // Enclose IPv6 address in brackets if needed
  7224. inline std::string prepare_host_string(const std::string &host) {
  7225. // Enclose IPv6 address in brackets (but not if already enclosed)
  7226. if (host.find(':') == std::string::npos ||
  7227. (!host.empty() && host[0] == '[')) {
  7228. // IPv4, hostname, or already bracketed IPv6
  7229. return host;
  7230. } else {
  7231. // IPv6 address without brackets
  7232. return "[" + host + "]";
  7233. }
  7234. }
  7235. inline std::string make_host_and_port_string(const std::string &host, int port,
  7236. bool is_ssl) {
  7237. auto result = prepare_host_string(host);
  7238. // Append port if not default
  7239. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  7240. ; // do nothing
  7241. } else {
  7242. result += ":" + std::to_string(port);
  7243. }
  7244. return result;
  7245. }
  7246. // Create "host:port" string always including port number (for CONNECT method)
  7247. inline std::string
  7248. make_host_and_port_string_always_port(const std::string &host, int port) {
  7249. return prepare_host_string(host) + ":" + std::to_string(port);
  7250. }
  7251. template <typename T>
  7252. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  7253. T header_writer, Error &error) {
  7254. for (const auto &h : headers) {
  7255. if (!detail::fields::is_field_name(h.first) ||
  7256. !detail::fields::is_field_value(h.second)) {
  7257. error = Error::InvalidHeaders;
  7258. return false;
  7259. }
  7260. }
  7261. if (header_writer(strm, headers) <= 0) {
  7262. error = Error::Write;
  7263. return false;
  7264. }
  7265. return true;
  7266. }
  7267. } // namespace detail
  7268. // HTTP server implementation
  7269. inline Server::Server()
  7270. : new_task_queue(
  7271. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  7272. #ifndef _WIN32
  7273. signal(SIGPIPE, SIG_IGN);
  7274. #endif
  7275. }
  7276. inline Server::~Server() = default;
  7277. inline std::unique_ptr<detail::MatcherBase>
  7278. Server::make_matcher(const std::string &pattern) {
  7279. if (pattern.find("/:") != std::string::npos) {
  7280. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  7281. } else {
  7282. return detail::make_unique<detail::RegexMatcher>(pattern);
  7283. }
  7284. }
  7285. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  7286. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7287. return *this;
  7288. }
  7289. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  7290. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7291. return *this;
  7292. }
  7293. inline Server &Server::Post(const std::string &pattern,
  7294. HandlerWithContentReader handler) {
  7295. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7296. std::move(handler));
  7297. return *this;
  7298. }
  7299. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  7300. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7301. return *this;
  7302. }
  7303. inline Server &Server::Put(const std::string &pattern,
  7304. HandlerWithContentReader handler) {
  7305. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7306. std::move(handler));
  7307. return *this;
  7308. }
  7309. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  7310. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7311. return *this;
  7312. }
  7313. inline Server &Server::Patch(const std::string &pattern,
  7314. HandlerWithContentReader handler) {
  7315. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7316. std::move(handler));
  7317. return *this;
  7318. }
  7319. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  7320. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7321. return *this;
  7322. }
  7323. inline Server &Server::Delete(const std::string &pattern,
  7324. HandlerWithContentReader handler) {
  7325. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7326. std::move(handler));
  7327. return *this;
  7328. }
  7329. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  7330. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7331. return *this;
  7332. }
  7333. inline bool Server::set_base_dir(const std::string &dir,
  7334. const std::string &mount_point) {
  7335. return set_mount_point(mount_point, dir);
  7336. }
  7337. inline bool Server::set_mount_point(const std::string &mount_point,
  7338. const std::string &dir, Headers headers) {
  7339. detail::FileStat stat(dir);
  7340. if (stat.is_dir()) {
  7341. std::string mnt = !mount_point.empty() ? mount_point : "/";
  7342. if (!mnt.empty() && mnt[0] == '/') {
  7343. base_dirs_.push_back({std::move(mnt), dir, std::move(headers)});
  7344. return true;
  7345. }
  7346. }
  7347. return false;
  7348. }
  7349. inline bool Server::remove_mount_point(const std::string &mount_point) {
  7350. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  7351. if (it->mount_point == mount_point) {
  7352. base_dirs_.erase(it);
  7353. return true;
  7354. }
  7355. }
  7356. return false;
  7357. }
  7358. inline Server &
  7359. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  7360. const std::string &mime) {
  7361. file_extension_and_mimetype_map_[ext] = mime;
  7362. return *this;
  7363. }
  7364. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  7365. default_file_mimetype_ = mime;
  7366. return *this;
  7367. }
  7368. inline Server &Server::set_file_request_handler(Handler handler) {
  7369. file_request_handler_ = std::move(handler);
  7370. return *this;
  7371. }
  7372. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  7373. std::true_type) {
  7374. error_handler_ = std::move(handler);
  7375. return *this;
  7376. }
  7377. inline Server &Server::set_error_handler_core(Handler handler,
  7378. std::false_type) {
  7379. error_handler_ = [handler](const Request &req, Response &res) {
  7380. handler(req, res);
  7381. return HandlerResponse::Handled;
  7382. };
  7383. return *this;
  7384. }
  7385. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  7386. exception_handler_ = std::move(handler);
  7387. return *this;
  7388. }
  7389. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  7390. pre_routing_handler_ = std::move(handler);
  7391. return *this;
  7392. }
  7393. inline Server &Server::set_post_routing_handler(Handler handler) {
  7394. post_routing_handler_ = std::move(handler);
  7395. return *this;
  7396. }
  7397. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  7398. pre_request_handler_ = std::move(handler);
  7399. return *this;
  7400. }
  7401. inline Server &Server::set_logger(Logger logger) {
  7402. logger_ = std::move(logger);
  7403. return *this;
  7404. }
  7405. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  7406. error_logger_ = std::move(error_logger);
  7407. return *this;
  7408. }
  7409. inline Server &Server::set_pre_compression_logger(Logger logger) {
  7410. pre_compression_logger_ = std::move(logger);
  7411. return *this;
  7412. }
  7413. inline Server &
  7414. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  7415. expect_100_continue_handler_ = std::move(handler);
  7416. return *this;
  7417. }
  7418. inline Server &Server::set_address_family(int family) {
  7419. address_family_ = family;
  7420. return *this;
  7421. }
  7422. inline Server &Server::set_tcp_nodelay(bool on) {
  7423. tcp_nodelay_ = on;
  7424. return *this;
  7425. }
  7426. inline Server &Server::set_ipv6_v6only(bool on) {
  7427. ipv6_v6only_ = on;
  7428. return *this;
  7429. }
  7430. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  7431. socket_options_ = std::move(socket_options);
  7432. return *this;
  7433. }
  7434. inline Server &Server::set_default_headers(Headers headers) {
  7435. default_headers_ = std::move(headers);
  7436. return *this;
  7437. }
  7438. inline Server &Server::set_header_writer(
  7439. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7440. header_writer_ = writer;
  7441. return *this;
  7442. }
  7443. inline Server &
  7444. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  7445. trusted_proxies_ = proxies;
  7446. return *this;
  7447. }
  7448. inline Server &Server::set_keep_alive_max_count(size_t count) {
  7449. keep_alive_max_count_ = count;
  7450. return *this;
  7451. }
  7452. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  7453. keep_alive_timeout_sec_ = sec;
  7454. return *this;
  7455. }
  7456. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  7457. read_timeout_sec_ = sec;
  7458. read_timeout_usec_ = usec;
  7459. return *this;
  7460. }
  7461. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  7462. write_timeout_sec_ = sec;
  7463. write_timeout_usec_ = usec;
  7464. return *this;
  7465. }
  7466. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  7467. idle_interval_sec_ = sec;
  7468. idle_interval_usec_ = usec;
  7469. return *this;
  7470. }
  7471. inline Server &Server::set_payload_max_length(size_t length) {
  7472. payload_max_length_ = length;
  7473. return *this;
  7474. }
  7475. inline bool Server::bind_to_port(const std::string &host, int port,
  7476. int socket_flags) {
  7477. auto ret = bind_internal(host, port, socket_flags);
  7478. if (ret == -1) { is_decommissioned = true; }
  7479. return ret >= 0;
  7480. }
  7481. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  7482. auto ret = bind_internal(host, 0, socket_flags);
  7483. if (ret == -1) { is_decommissioned = true; }
  7484. return ret;
  7485. }
  7486. inline bool Server::listen_after_bind() { return listen_internal(); }
  7487. inline bool Server::listen(const std::string &host, int port,
  7488. int socket_flags) {
  7489. return bind_to_port(host, port, socket_flags) && listen_internal();
  7490. }
  7491. inline bool Server::is_running() const { return is_running_; }
  7492. inline void Server::wait_until_ready() const {
  7493. while (!is_running_ && !is_decommissioned) {
  7494. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7495. }
  7496. }
  7497. inline void Server::stop() {
  7498. if (is_running_) {
  7499. assert(svr_sock_ != INVALID_SOCKET);
  7500. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  7501. detail::shutdown_socket(sock);
  7502. detail::close_socket(sock);
  7503. }
  7504. is_decommissioned = false;
  7505. }
  7506. inline void Server::decommission() { is_decommissioned = true; }
  7507. inline bool Server::parse_request_line(const char *s, Request &req) const {
  7508. auto len = strlen(s);
  7509. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  7510. len -= 2;
  7511. {
  7512. size_t count = 0;
  7513. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  7514. switch (count) {
  7515. case 0: req.method = std::string(b, e); break;
  7516. case 1: req.target = std::string(b, e); break;
  7517. case 2: req.version = std::string(b, e); break;
  7518. default: break;
  7519. }
  7520. count++;
  7521. });
  7522. if (count != 3) { return false; }
  7523. }
  7524. thread_local const std::set<std::string> methods{
  7525. "GET", "HEAD", "POST", "PUT", "DELETE",
  7526. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7527. if (methods.find(req.method) == methods.end()) {
  7528. output_error_log(Error::InvalidHTTPMethod, &req);
  7529. return false;
  7530. }
  7531. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  7532. output_error_log(Error::InvalidHTTPVersion, &req);
  7533. return false;
  7534. }
  7535. {
  7536. // Skip URL fragment
  7537. for (size_t i = 0; i < req.target.size(); i++) {
  7538. if (req.target[i] == '#') {
  7539. req.target.erase(i);
  7540. break;
  7541. }
  7542. }
  7543. detail::divide(req.target, '?',
  7544. [&](const char *lhs_data, std::size_t lhs_size,
  7545. const char *rhs_data, std::size_t rhs_size) {
  7546. req.path =
  7547. decode_path_component(std::string(lhs_data, lhs_size));
  7548. detail::parse_query_text(rhs_data, rhs_size, req.params);
  7549. });
  7550. }
  7551. return true;
  7552. }
  7553. inline bool Server::write_response(Stream &strm, bool close_connection,
  7554. Request &req, Response &res) {
  7555. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  7556. // incorrectly to the error content.
  7557. req.ranges.clear();
  7558. return write_response_core(strm, close_connection, req, res, false);
  7559. }
  7560. inline bool Server::write_response_with_content(Stream &strm,
  7561. bool close_connection,
  7562. const Request &req,
  7563. Response &res) {
  7564. return write_response_core(strm, close_connection, req, res, true);
  7565. }
  7566. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  7567. const Request &req, Response &res,
  7568. bool need_apply_ranges) {
  7569. assert(res.status != -1);
  7570. if (400 <= res.status && error_handler_ &&
  7571. error_handler_(req, res) == HandlerResponse::Handled) {
  7572. need_apply_ranges = true;
  7573. }
  7574. std::string content_type;
  7575. std::string boundary;
  7576. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  7577. // Prepare additional headers
  7578. if (close_connection || req.get_header_value("Connection") == "close" ||
  7579. 400 <= res.status) { // Don't leave connections open after errors
  7580. res.set_header("Connection", "close");
  7581. } else {
  7582. std::string s = "timeout=";
  7583. s += std::to_string(keep_alive_timeout_sec_);
  7584. s += ", max=";
  7585. s += std::to_string(keep_alive_max_count_);
  7586. res.set_header("Keep-Alive", s);
  7587. }
  7588. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  7589. !res.has_header("Content-Type")) {
  7590. res.set_header("Content-Type", "text/plain");
  7591. }
  7592. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  7593. !res.has_header("Content-Length")) {
  7594. res.set_header("Content-Length", "0");
  7595. }
  7596. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  7597. res.set_header("Accept-Ranges", "bytes");
  7598. }
  7599. if (post_routing_handler_) { post_routing_handler_(req, res); }
  7600. // Response line and headers
  7601. {
  7602. detail::BufferStream bstrm;
  7603. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  7604. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  7605. // Flush buffer
  7606. auto &data = bstrm.get_buffer();
  7607. detail::write_data(strm, data.data(), data.size());
  7608. }
  7609. // Body
  7610. auto ret = true;
  7611. if (req.method != "HEAD") {
  7612. if (!res.body.empty()) {
  7613. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  7614. ret = false;
  7615. }
  7616. } else if (res.content_provider_) {
  7617. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  7618. res.content_provider_success_ = true;
  7619. } else {
  7620. ret = false;
  7621. }
  7622. }
  7623. }
  7624. // Log
  7625. output_log(req, res);
  7626. return ret;
  7627. }
  7628. inline bool
  7629. Server::write_content_with_provider(Stream &strm, const Request &req,
  7630. Response &res, const std::string &boundary,
  7631. const std::string &content_type) {
  7632. auto is_shutting_down = [this]() {
  7633. return this->svr_sock_ == INVALID_SOCKET;
  7634. };
  7635. if (res.content_length_ > 0) {
  7636. if (req.ranges.empty()) {
  7637. return detail::write_content(strm, res.content_provider_, 0,
  7638. res.content_length_, is_shutting_down);
  7639. } else if (req.ranges.size() == 1) {
  7640. auto offset_and_length = detail::get_range_offset_and_length(
  7641. req.ranges[0], res.content_length_);
  7642. return detail::write_content(strm, res.content_provider_,
  7643. offset_and_length.first,
  7644. offset_and_length.second, is_shutting_down);
  7645. } else {
  7646. return detail::write_multipart_ranges_data(
  7647. strm, req, res, boundary, content_type, res.content_length_,
  7648. is_shutting_down);
  7649. }
  7650. } else {
  7651. if (res.is_chunked_content_provider_) {
  7652. auto type = detail::encoding_type(req, res);
  7653. std::unique_ptr<detail::compressor> compressor;
  7654. if (type == detail::EncodingType::Gzip) {
  7655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7656. compressor = detail::make_unique<detail::gzip_compressor>();
  7657. #endif
  7658. } else if (type == detail::EncodingType::Brotli) {
  7659. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7660. compressor = detail::make_unique<detail::brotli_compressor>();
  7661. #endif
  7662. } else if (type == detail::EncodingType::Zstd) {
  7663. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7664. compressor = detail::make_unique<detail::zstd_compressor>();
  7665. #endif
  7666. } else {
  7667. compressor = detail::make_unique<detail::nocompressor>();
  7668. }
  7669. assert(compressor != nullptr);
  7670. return detail::write_content_chunked(strm, res.content_provider_,
  7671. is_shutting_down, *compressor);
  7672. } else {
  7673. return detail::write_content_without_length(strm, res.content_provider_,
  7674. is_shutting_down);
  7675. }
  7676. }
  7677. }
  7678. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  7679. FormFields::iterator cur_field;
  7680. FormFiles::iterator cur_file;
  7681. auto is_text_field = false;
  7682. size_t count = 0;
  7683. if (read_content_core(
  7684. strm, req, res,
  7685. // Regular
  7686. [&](const char *buf, size_t n) {
  7687. // Prevent arithmetic overflow when checking sizes.
  7688. // Avoid computing (req.body.size() + n) directly because
  7689. // adding two unsigned `size_t` values can wrap around and
  7690. // produce a small result instead of indicating overflow.
  7691. // Instead, check using subtraction: ensure `n` does not
  7692. // exceed the remaining capacity `max_size() - size()`.
  7693. if (req.body.size() >= req.body.max_size() ||
  7694. n > req.body.max_size() - req.body.size()) {
  7695. return false;
  7696. }
  7697. // Limit decompressed body size to payload_max_length_ to protect
  7698. // against "zip bomb" attacks where a small compressed payload
  7699. // decompresses to a massive size.
  7700. if (payload_max_length_ > 0 &&
  7701. (req.body.size() >= payload_max_length_ ||
  7702. n > payload_max_length_ - req.body.size())) {
  7703. return false;
  7704. }
  7705. req.body.append(buf, n);
  7706. return true;
  7707. },
  7708. // Multipart FormData
  7709. [&](const FormData &file) {
  7710. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  7711. output_error_log(Error::TooManyFormDataFiles, &req);
  7712. return false;
  7713. }
  7714. if (file.filename.empty()) {
  7715. cur_field = req.form.fields.emplace(
  7716. file.name, FormField{file.name, file.content, file.headers});
  7717. is_text_field = true;
  7718. } else {
  7719. cur_file = req.form.files.emplace(file.name, file);
  7720. is_text_field = false;
  7721. }
  7722. return true;
  7723. },
  7724. [&](const char *buf, size_t n) {
  7725. if (is_text_field) {
  7726. auto &content = cur_field->second.content;
  7727. if (content.size() + n > content.max_size()) { return false; }
  7728. content.append(buf, n);
  7729. } else {
  7730. auto &content = cur_file->second.content;
  7731. if (content.size() + n > content.max_size()) { return false; }
  7732. content.append(buf, n);
  7733. }
  7734. return true;
  7735. })) {
  7736. const auto &content_type = req.get_header_value("Content-Type");
  7737. if (!content_type.find("application/x-www-form-urlencoded")) {
  7738. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  7739. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  7740. output_error_log(Error::ExceedMaxPayloadSize, &req);
  7741. return false;
  7742. }
  7743. detail::parse_query_text(req.body, req.params);
  7744. }
  7745. return true;
  7746. }
  7747. return false;
  7748. }
  7749. inline bool Server::read_content_with_content_receiver(
  7750. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7751. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  7752. return read_content_core(strm, req, res, std::move(receiver),
  7753. std::move(multipart_header),
  7754. std::move(multipart_receiver));
  7755. }
  7756. inline bool Server::read_content_core(
  7757. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7758. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  7759. detail::FormDataParser multipart_form_data_parser;
  7760. ContentReceiverWithProgress out;
  7761. if (req.is_multipart_form_data()) {
  7762. const auto &content_type = req.get_header_value("Content-Type");
  7763. std::string boundary;
  7764. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  7765. res.status = StatusCode::BadRequest_400;
  7766. output_error_log(Error::MultipartParsing, &req);
  7767. return false;
  7768. }
  7769. multipart_form_data_parser.set_boundary(std::move(boundary));
  7770. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  7771. return multipart_form_data_parser.parse(buf, n, multipart_header,
  7772. multipart_receiver);
  7773. };
  7774. } else {
  7775. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  7776. size_t /*len*/) { return receiver(buf, n); };
  7777. }
  7778. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  7779. // are true (no Transfer-Encoding and no Content-Length), then the message
  7780. // body length is zero (no message body is present).
  7781. //
  7782. // For non-SSL builds, peek into the socket to detect clients that send a
  7783. // body without a Content-Length header (raw HTTP over TCP). If there is
  7784. // pending data that exceeds the configured payload limit, treat this as an
  7785. // oversized request and fail early (causing connection close). For SSL
  7786. // builds we cannot reliably peek the decrypted application bytes, so keep
  7787. // the original behaviour.
  7788. #if !defined(CPPHTTPLIB_OPENSSL_SUPPORT)
  7789. if (!req.has_header("Content-Length") &&
  7790. !detail::is_chunked_transfer_encoding(req.headers)) {
  7791. // Only peek if payload_max_length is set to a finite value
  7792. if (payload_max_length_ > 0 &&
  7793. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  7794. socket_t s = strm.socket();
  7795. if (s != INVALID_SOCKET) {
  7796. // Peek to check if there is any pending data
  7797. char peekbuf[1];
  7798. ssize_t n = ::recv(s, peekbuf, 1, MSG_PEEK);
  7799. if (n > 0) {
  7800. // There is data, so read it with payload limit enforcement
  7801. auto result = detail::read_content_without_length(
  7802. strm, payload_max_length_, out);
  7803. if (result == detail::ReadContentResult::PayloadTooLarge) {
  7804. res.status = StatusCode::PayloadTooLarge_413;
  7805. return false;
  7806. } else if (result != detail::ReadContentResult::Success) {
  7807. return false;
  7808. }
  7809. return true;
  7810. }
  7811. }
  7812. }
  7813. return true;
  7814. }
  7815. #else
  7816. if (!req.has_header("Content-Length") &&
  7817. !detail::is_chunked_transfer_encoding(req.headers)) {
  7818. return true;
  7819. }
  7820. #endif
  7821. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  7822. out, true)) {
  7823. return false;
  7824. }
  7825. if (req.is_multipart_form_data()) {
  7826. if (!multipart_form_data_parser.is_valid()) {
  7827. res.status = StatusCode::BadRequest_400;
  7828. output_error_log(Error::MultipartParsing, &req);
  7829. return false;
  7830. }
  7831. }
  7832. return true;
  7833. }
  7834. inline bool Server::handle_file_request(Request &req, Response &res) {
  7835. for (const auto &entry : base_dirs_) {
  7836. // Prefix match
  7837. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  7838. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  7839. if (detail::is_valid_path(sub_path)) {
  7840. auto path = entry.base_dir + sub_path;
  7841. if (path.back() == '/') { path += "index.html"; }
  7842. detail::FileStat stat(path);
  7843. if (stat.is_dir()) {
  7844. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  7845. return true;
  7846. }
  7847. if (stat.is_file()) {
  7848. for (const auto &kv : entry.headers) {
  7849. res.set_header(kv.first, kv.second);
  7850. }
  7851. auto etag = detail::compute_etag(stat);
  7852. if (!etag.empty()) { res.set_header("ETag", etag); }
  7853. auto mtime = stat.mtime();
  7854. auto last_modified = detail::file_mtime_to_http_date(mtime);
  7855. if (!last_modified.empty()) {
  7856. res.set_header("Last-Modified", last_modified);
  7857. }
  7858. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  7859. check_if_range(req, etag, mtime);
  7860. auto mm = std::make_shared<detail::mmap>(path.c_str());
  7861. if (!mm->is_open()) {
  7862. output_error_log(Error::OpenFile, &req);
  7863. return false;
  7864. }
  7865. res.set_content_provider(
  7866. mm->size(),
  7867. detail::find_content_type(path, file_extension_and_mimetype_map_,
  7868. default_file_mimetype_),
  7869. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  7870. sink.write(mm->data() + offset, length);
  7871. return true;
  7872. });
  7873. if (req.method != "HEAD" && file_request_handler_) {
  7874. file_request_handler_(req, res);
  7875. }
  7876. return true;
  7877. } else {
  7878. output_error_log(Error::OpenFile, &req);
  7879. }
  7880. }
  7881. }
  7882. }
  7883. return false;
  7884. }
  7885. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  7886. const std::string &etag,
  7887. time_t mtime) const {
  7888. // Handle conditional GET:
  7889. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  7890. // 2. If-Modified-Since is checked only when If-None-Match is absent
  7891. if (req.has_header("If-None-Match")) {
  7892. if (!etag.empty()) {
  7893. auto val = req.get_header_value("If-None-Match");
  7894. // NOTE: We use exact string matching here. This works correctly
  7895. // because our server always generates weak ETags (W/"..."), and
  7896. // clients typically send back the same ETag they received.
  7897. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  7898. // If-None-Match, where W/"x" and "x" would match, but this
  7899. // simplified implementation requires exact matches.
  7900. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  7901. [&](const char *b, const char *e) {
  7902. return std::equal(b, e, "*") ||
  7903. std::equal(b, e, etag.begin());
  7904. });
  7905. if (ret) {
  7906. res.status = StatusCode::NotModified_304;
  7907. return true;
  7908. }
  7909. }
  7910. } else if (req.has_header("If-Modified-Since")) {
  7911. auto val = req.get_header_value("If-Modified-Since");
  7912. auto t = detail::parse_http_date(val);
  7913. if (t != static_cast<time_t>(-1) && mtime <= t) {
  7914. res.status = StatusCode::NotModified_304;
  7915. return true;
  7916. }
  7917. }
  7918. return false;
  7919. }
  7920. inline bool Server::check_if_range(Request &req, const std::string &etag,
  7921. time_t mtime) const {
  7922. // Handle If-Range for partial content requests (RFC 9110
  7923. // Section 13.1.5). If-Range is only evaluated when Range header is
  7924. // present. If the validator matches, serve partial content; otherwise
  7925. // serve full content.
  7926. if (!req.ranges.empty() && req.has_header("If-Range")) {
  7927. auto val = req.get_header_value("If-Range");
  7928. auto is_valid_range = [&]() {
  7929. if (detail::is_strong_etag(val)) {
  7930. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  7931. // comparison.
  7932. return (!etag.empty() && val == etag);
  7933. } else if (detail::is_weak_etag(val)) {
  7934. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  7935. return false;
  7936. } else {
  7937. // HTTP-date comparison
  7938. auto t = detail::parse_http_date(val);
  7939. return (t != static_cast<time_t>(-1) && mtime <= t);
  7940. }
  7941. };
  7942. if (!is_valid_range()) {
  7943. // Validator doesn't match: ignore Range and serve full content
  7944. req.ranges.clear();
  7945. return false;
  7946. }
  7947. }
  7948. return true;
  7949. }
  7950. inline socket_t
  7951. Server::create_server_socket(const std::string &host, int port,
  7952. int socket_flags,
  7953. SocketOptions socket_options) const {
  7954. return detail::create_socket(
  7955. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  7956. ipv6_v6only_, std::move(socket_options),
  7957. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  7958. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  7959. output_error_log(Error::BindIPAddress, nullptr);
  7960. return false;
  7961. }
  7962. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  7963. output_error_log(Error::Listen, nullptr);
  7964. return false;
  7965. }
  7966. return true;
  7967. });
  7968. }
  7969. inline int Server::bind_internal(const std::string &host, int port,
  7970. int socket_flags) {
  7971. if (is_decommissioned) { return -1; }
  7972. if (!is_valid()) { return -1; }
  7973. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  7974. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  7975. if (port == 0) {
  7976. struct sockaddr_storage addr;
  7977. socklen_t addr_len = sizeof(addr);
  7978. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  7979. &addr_len) == -1) {
  7980. output_error_log(Error::GetSockName, nullptr);
  7981. return -1;
  7982. }
  7983. if (addr.ss_family == AF_INET) {
  7984. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  7985. } else if (addr.ss_family == AF_INET6) {
  7986. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  7987. } else {
  7988. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  7989. return -1;
  7990. }
  7991. } else {
  7992. return port;
  7993. }
  7994. }
  7995. inline bool Server::listen_internal() {
  7996. if (is_decommissioned) { return false; }
  7997. auto ret = true;
  7998. is_running_ = true;
  7999. auto se = detail::scope_exit([&]() { is_running_ = false; });
  8000. {
  8001. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  8002. while (svr_sock_ != INVALID_SOCKET) {
  8003. #ifndef _WIN32
  8004. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  8005. #endif
  8006. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  8007. idle_interval_usec_);
  8008. if (val == 0) { // Timeout
  8009. task_queue->on_idle();
  8010. continue;
  8011. }
  8012. #ifndef _WIN32
  8013. }
  8014. #endif
  8015. #if defined _WIN32
  8016. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  8017. // OVERLAPPED
  8018. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  8019. #elif defined SOCK_CLOEXEC
  8020. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  8021. #else
  8022. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  8023. #endif
  8024. if (sock == INVALID_SOCKET) {
  8025. if (errno == EMFILE) {
  8026. // The per-process limit of open file descriptors has been reached.
  8027. // Try to accept new connections after a short sleep.
  8028. std::this_thread::sleep_for(std::chrono::microseconds{1});
  8029. continue;
  8030. } else if (errno == EINTR || errno == EAGAIN) {
  8031. continue;
  8032. }
  8033. if (svr_sock_ != INVALID_SOCKET) {
  8034. detail::close_socket(svr_sock_);
  8035. ret = false;
  8036. output_error_log(Error::Connection, nullptr);
  8037. } else {
  8038. ; // The server socket was closed by user.
  8039. }
  8040. break;
  8041. }
  8042. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  8043. read_timeout_sec_, read_timeout_usec_);
  8044. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  8045. write_timeout_sec_, write_timeout_usec_);
  8046. if (!task_queue->enqueue(
  8047. [this, sock]() { process_and_close_socket(sock); })) {
  8048. output_error_log(Error::ResourceExhaustion, nullptr);
  8049. detail::shutdown_socket(sock);
  8050. detail::close_socket(sock);
  8051. }
  8052. }
  8053. task_queue->shutdown();
  8054. }
  8055. is_decommissioned = !ret;
  8056. return ret;
  8057. }
  8058. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  8059. if (pre_routing_handler_ &&
  8060. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  8061. return true;
  8062. }
  8063. // File handler
  8064. if ((req.method == "GET" || req.method == "HEAD") &&
  8065. handle_file_request(req, res)) {
  8066. return true;
  8067. }
  8068. if (detail::expect_content(req)) {
  8069. // Content reader handler
  8070. {
  8071. ContentReader reader(
  8072. [&](ContentReceiver receiver) {
  8073. auto result = read_content_with_content_receiver(
  8074. strm, req, res, std::move(receiver), nullptr, nullptr);
  8075. if (!result) { output_error_log(Error::Read, &req); }
  8076. return result;
  8077. },
  8078. [&](FormDataHeader header, ContentReceiver receiver) {
  8079. auto result = read_content_with_content_receiver(
  8080. strm, req, res, nullptr, std::move(header),
  8081. std::move(receiver));
  8082. if (!result) { output_error_log(Error::Read, &req); }
  8083. return result;
  8084. });
  8085. if (req.method == "POST") {
  8086. if (dispatch_request_for_content_reader(
  8087. req, res, std::move(reader),
  8088. post_handlers_for_content_reader_)) {
  8089. return true;
  8090. }
  8091. } else if (req.method == "PUT") {
  8092. if (dispatch_request_for_content_reader(
  8093. req, res, std::move(reader),
  8094. put_handlers_for_content_reader_)) {
  8095. return true;
  8096. }
  8097. } else if (req.method == "PATCH") {
  8098. if (dispatch_request_for_content_reader(
  8099. req, res, std::move(reader),
  8100. patch_handlers_for_content_reader_)) {
  8101. return true;
  8102. }
  8103. } else if (req.method == "DELETE") {
  8104. if (dispatch_request_for_content_reader(
  8105. req, res, std::move(reader),
  8106. delete_handlers_for_content_reader_)) {
  8107. return true;
  8108. }
  8109. }
  8110. }
  8111. // Read content into `req.body`
  8112. if (!read_content(strm, req, res)) {
  8113. output_error_log(Error::Read, &req);
  8114. return false;
  8115. }
  8116. }
  8117. // Regular handler
  8118. if (req.method == "GET" || req.method == "HEAD") {
  8119. return dispatch_request(req, res, get_handlers_);
  8120. } else if (req.method == "POST") {
  8121. return dispatch_request(req, res, post_handlers_);
  8122. } else if (req.method == "PUT") {
  8123. return dispatch_request(req, res, put_handlers_);
  8124. } else if (req.method == "DELETE") {
  8125. return dispatch_request(req, res, delete_handlers_);
  8126. } else if (req.method == "OPTIONS") {
  8127. return dispatch_request(req, res, options_handlers_);
  8128. } else if (req.method == "PATCH") {
  8129. return dispatch_request(req, res, patch_handlers_);
  8130. }
  8131. res.status = StatusCode::BadRequest_400;
  8132. return false;
  8133. }
  8134. inline bool Server::dispatch_request(Request &req, Response &res,
  8135. const Handlers &handlers) const {
  8136. for (const auto &x : handlers) {
  8137. const auto &matcher = x.first;
  8138. const auto &handler = x.second;
  8139. if (matcher->match(req)) {
  8140. req.matched_route = matcher->pattern();
  8141. if (!pre_request_handler_ ||
  8142. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8143. handler(req, res);
  8144. }
  8145. return true;
  8146. }
  8147. }
  8148. return false;
  8149. }
  8150. inline void Server::apply_ranges(const Request &req, Response &res,
  8151. std::string &content_type,
  8152. std::string &boundary) const {
  8153. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  8154. auto it = res.headers.find("Content-Type");
  8155. if (it != res.headers.end()) {
  8156. content_type = it->second;
  8157. res.headers.erase(it);
  8158. }
  8159. boundary = detail::make_multipart_data_boundary();
  8160. res.set_header("Content-Type",
  8161. "multipart/byteranges; boundary=" + boundary);
  8162. }
  8163. auto type = detail::encoding_type(req, res);
  8164. if (res.body.empty()) {
  8165. if (res.content_length_ > 0) {
  8166. size_t length = 0;
  8167. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8168. length = res.content_length_;
  8169. } else if (req.ranges.size() == 1) {
  8170. auto offset_and_length = detail::get_range_offset_and_length(
  8171. req.ranges[0], res.content_length_);
  8172. length = offset_and_length.second;
  8173. auto content_range = detail::make_content_range_header_field(
  8174. offset_and_length, res.content_length_);
  8175. res.set_header("Content-Range", content_range);
  8176. } else {
  8177. length = detail::get_multipart_ranges_data_length(
  8178. req, boundary, content_type, res.content_length_);
  8179. }
  8180. res.set_header("Content-Length", std::to_string(length));
  8181. } else {
  8182. if (res.content_provider_) {
  8183. if (res.is_chunked_content_provider_) {
  8184. res.set_header("Transfer-Encoding", "chunked");
  8185. if (type == detail::EncodingType::Gzip) {
  8186. res.set_header("Content-Encoding", "gzip");
  8187. res.set_header("Vary", "Accept-Encoding");
  8188. } else if (type == detail::EncodingType::Brotli) {
  8189. res.set_header("Content-Encoding", "br");
  8190. res.set_header("Vary", "Accept-Encoding");
  8191. } else if (type == detail::EncodingType::Zstd) {
  8192. res.set_header("Content-Encoding", "zstd");
  8193. res.set_header("Vary", "Accept-Encoding");
  8194. }
  8195. }
  8196. }
  8197. }
  8198. } else {
  8199. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8200. ;
  8201. } else if (req.ranges.size() == 1) {
  8202. auto offset_and_length =
  8203. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  8204. auto offset = offset_and_length.first;
  8205. auto length = offset_and_length.second;
  8206. auto content_range = detail::make_content_range_header_field(
  8207. offset_and_length, res.body.size());
  8208. res.set_header("Content-Range", content_range);
  8209. assert(offset + length <= res.body.size());
  8210. res.body = res.body.substr(offset, length);
  8211. } else {
  8212. std::string data;
  8213. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  8214. res.body.size(), data);
  8215. res.body.swap(data);
  8216. }
  8217. if (type != detail::EncodingType::None) {
  8218. output_pre_compression_log(req, res);
  8219. std::unique_ptr<detail::compressor> compressor;
  8220. std::string content_encoding;
  8221. if (type == detail::EncodingType::Gzip) {
  8222. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8223. compressor = detail::make_unique<detail::gzip_compressor>();
  8224. content_encoding = "gzip";
  8225. #endif
  8226. } else if (type == detail::EncodingType::Brotli) {
  8227. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8228. compressor = detail::make_unique<detail::brotli_compressor>();
  8229. content_encoding = "br";
  8230. #endif
  8231. } else if (type == detail::EncodingType::Zstd) {
  8232. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8233. compressor = detail::make_unique<detail::zstd_compressor>();
  8234. content_encoding = "zstd";
  8235. #endif
  8236. }
  8237. if (compressor) {
  8238. std::string compressed;
  8239. if (compressor->compress(res.body.data(), res.body.size(), true,
  8240. [&](const char *data, size_t data_len) {
  8241. compressed.append(data, data_len);
  8242. return true;
  8243. })) {
  8244. res.body.swap(compressed);
  8245. res.set_header("Content-Encoding", content_encoding);
  8246. res.set_header("Vary", "Accept-Encoding");
  8247. }
  8248. }
  8249. }
  8250. auto length = std::to_string(res.body.size());
  8251. res.set_header("Content-Length", length);
  8252. }
  8253. }
  8254. inline bool Server::dispatch_request_for_content_reader(
  8255. Request &req, Response &res, ContentReader content_reader,
  8256. const HandlersForContentReader &handlers) const {
  8257. for (const auto &x : handlers) {
  8258. const auto &matcher = x.first;
  8259. const auto &handler = x.second;
  8260. if (matcher->match(req)) {
  8261. req.matched_route = matcher->pattern();
  8262. if (!pre_request_handler_ ||
  8263. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8264. handler(req, res, content_reader);
  8265. }
  8266. return true;
  8267. }
  8268. }
  8269. return false;
  8270. }
  8271. inline std::string
  8272. get_client_ip(const std::string &x_forwarded_for,
  8273. const std::vector<std::string> &trusted_proxies) {
  8274. // X-Forwarded-For is a comma-separated list per RFC 7239
  8275. std::vector<std::string> ip_list;
  8276. detail::split(x_forwarded_for.data(),
  8277. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  8278. [&](const char *b, const char *e) {
  8279. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  8280. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  8281. });
  8282. for (size_t i = 0; i < ip_list.size(); ++i) {
  8283. auto ip = ip_list[i];
  8284. auto is_trusted_proxy =
  8285. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  8286. [&](const std::string &proxy) { return ip == proxy; });
  8287. if (is_trusted_proxy) {
  8288. if (i == 0) {
  8289. // If the trusted proxy is the first IP, there's no preceding client IP
  8290. return ip;
  8291. } else {
  8292. // Return the IP immediately before the trusted proxy
  8293. return ip_list[i - 1];
  8294. }
  8295. }
  8296. }
  8297. // If no trusted proxy is found, return the first IP in the list
  8298. return ip_list.front();
  8299. }
  8300. inline bool
  8301. Server::process_request(Stream &strm, const std::string &remote_addr,
  8302. int remote_port, const std::string &local_addr,
  8303. int local_port, bool close_connection,
  8304. bool &connection_closed,
  8305. const std::function<void(Request &)> &setup_request) {
  8306. std::array<char, 2048> buf{};
  8307. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8308. // Connection has been closed on client
  8309. if (!line_reader.getline()) { return false; }
  8310. Request req;
  8311. req.start_time_ = std::chrono::steady_clock::now();
  8312. req.remote_addr = remote_addr;
  8313. req.remote_port = remote_port;
  8314. req.local_addr = local_addr;
  8315. req.local_port = local_port;
  8316. Response res;
  8317. res.version = "HTTP/1.1";
  8318. res.headers = default_headers_;
  8319. #ifdef __APPLE__
  8320. // Socket file descriptor exceeded FD_SETSIZE...
  8321. if (strm.socket() >= FD_SETSIZE) {
  8322. Headers dummy;
  8323. detail::read_headers(strm, dummy);
  8324. res.status = StatusCode::InternalServerError_500;
  8325. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  8326. return write_response(strm, close_connection, req, res);
  8327. }
  8328. #endif
  8329. // Request line and headers
  8330. if (!parse_request_line(line_reader.ptr(), req)) {
  8331. res.status = StatusCode::BadRequest_400;
  8332. output_error_log(Error::InvalidRequestLine, &req);
  8333. return write_response(strm, close_connection, req, res);
  8334. }
  8335. // Request headers
  8336. if (!detail::read_headers(strm, req.headers)) {
  8337. res.status = StatusCode::BadRequest_400;
  8338. output_error_log(Error::InvalidHeaders, &req);
  8339. return write_response(strm, close_connection, req, res);
  8340. }
  8341. // Check if the request URI doesn't exceed the limit
  8342. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  8343. res.status = StatusCode::UriTooLong_414;
  8344. output_error_log(Error::ExceedUriMaxLength, &req);
  8345. return write_response(strm, close_connection, req, res);
  8346. }
  8347. if (req.get_header_value("Connection") == "close") {
  8348. connection_closed = true;
  8349. }
  8350. if (req.version == "HTTP/1.0" &&
  8351. req.get_header_value("Connection") != "Keep-Alive") {
  8352. connection_closed = true;
  8353. }
  8354. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  8355. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  8356. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  8357. } else {
  8358. req.remote_addr = remote_addr;
  8359. }
  8360. req.remote_port = remote_port;
  8361. req.local_addr = local_addr;
  8362. req.local_port = local_port;
  8363. if (req.has_header("Accept")) {
  8364. const auto &accept_header = req.get_header_value("Accept");
  8365. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  8366. res.status = StatusCode::BadRequest_400;
  8367. output_error_log(Error::HTTPParsing, &req);
  8368. return write_response(strm, close_connection, req, res);
  8369. }
  8370. }
  8371. if (req.has_header("Range")) {
  8372. const auto &range_header_value = req.get_header_value("Range");
  8373. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  8374. res.status = StatusCode::RangeNotSatisfiable_416;
  8375. output_error_log(Error::InvalidRangeHeader, &req);
  8376. return write_response(strm, close_connection, req, res);
  8377. }
  8378. }
  8379. if (setup_request) { setup_request(req); }
  8380. if (req.get_header_value("Expect") == "100-continue") {
  8381. int status = StatusCode::Continue_100;
  8382. if (expect_100_continue_handler_) {
  8383. status = expect_100_continue_handler_(req, res);
  8384. }
  8385. switch (status) {
  8386. case StatusCode::Continue_100:
  8387. case StatusCode::ExpectationFailed_417:
  8388. detail::write_response_line(strm, status);
  8389. strm.write("\r\n");
  8390. break;
  8391. default:
  8392. connection_closed = true;
  8393. return write_response(strm, true, req, res);
  8394. }
  8395. }
  8396. // Setup `is_connection_closed` method
  8397. auto sock = strm.socket();
  8398. req.is_connection_closed = [sock]() {
  8399. return !detail::is_socket_alive(sock);
  8400. };
  8401. // Routing
  8402. auto routed = false;
  8403. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8404. routed = routing(req, res, strm);
  8405. #else
  8406. try {
  8407. routed = routing(req, res, strm);
  8408. } catch (std::exception &e) {
  8409. if (exception_handler_) {
  8410. auto ep = std::current_exception();
  8411. exception_handler_(req, res, ep);
  8412. routed = true;
  8413. } else {
  8414. res.status = StatusCode::InternalServerError_500;
  8415. std::string val;
  8416. auto s = e.what();
  8417. for (size_t i = 0; s[i]; i++) {
  8418. switch (s[i]) {
  8419. case '\r': val += "\\r"; break;
  8420. case '\n': val += "\\n"; break;
  8421. default: val += s[i]; break;
  8422. }
  8423. }
  8424. res.set_header("EXCEPTION_WHAT", val);
  8425. }
  8426. } catch (...) {
  8427. if (exception_handler_) {
  8428. auto ep = std::current_exception();
  8429. exception_handler_(req, res, ep);
  8430. routed = true;
  8431. } else {
  8432. res.status = StatusCode::InternalServerError_500;
  8433. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  8434. }
  8435. }
  8436. #endif
  8437. if (routed) {
  8438. if (res.status == -1) {
  8439. res.status = req.ranges.empty() ? StatusCode::OK_200
  8440. : StatusCode::PartialContent_206;
  8441. }
  8442. // Serve file content by using a content provider
  8443. if (!res.file_content_path_.empty()) {
  8444. const auto &path = res.file_content_path_;
  8445. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8446. if (!mm->is_open()) {
  8447. res.body.clear();
  8448. res.content_length_ = 0;
  8449. res.content_provider_ = nullptr;
  8450. res.status = StatusCode::NotFound_404;
  8451. output_error_log(Error::OpenFile, &req);
  8452. return write_response(strm, close_connection, req, res);
  8453. }
  8454. auto content_type = res.file_content_content_type_;
  8455. if (content_type.empty()) {
  8456. content_type = detail::find_content_type(
  8457. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  8458. }
  8459. res.set_content_provider(
  8460. mm->size(), content_type,
  8461. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8462. sink.write(mm->data() + offset, length);
  8463. return true;
  8464. });
  8465. }
  8466. if (detail::range_error(req, res)) {
  8467. res.body.clear();
  8468. res.content_length_ = 0;
  8469. res.content_provider_ = nullptr;
  8470. res.status = StatusCode::RangeNotSatisfiable_416;
  8471. return write_response(strm, close_connection, req, res);
  8472. }
  8473. return write_response_with_content(strm, close_connection, req, res);
  8474. } else {
  8475. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  8476. return write_response(strm, close_connection, req, res);
  8477. }
  8478. }
  8479. inline bool Server::is_valid() const { return true; }
  8480. inline bool Server::process_and_close_socket(socket_t sock) {
  8481. std::string remote_addr;
  8482. int remote_port = 0;
  8483. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8484. std::string local_addr;
  8485. int local_port = 0;
  8486. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8487. auto ret = detail::process_server_socket(
  8488. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8489. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8490. write_timeout_usec_,
  8491. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8492. return process_request(strm, remote_addr, remote_port, local_addr,
  8493. local_port, close_connection, connection_closed,
  8494. nullptr);
  8495. });
  8496. detail::shutdown_socket(sock);
  8497. detail::close_socket(sock);
  8498. return ret;
  8499. }
  8500. inline void Server::output_log(const Request &req, const Response &res) const {
  8501. if (logger_) {
  8502. std::lock_guard<std::mutex> guard(logger_mutex_);
  8503. logger_(req, res);
  8504. }
  8505. }
  8506. inline void Server::output_pre_compression_log(const Request &req,
  8507. const Response &res) const {
  8508. if (pre_compression_logger_) {
  8509. std::lock_guard<std::mutex> guard(logger_mutex_);
  8510. pre_compression_logger_(req, res);
  8511. }
  8512. }
  8513. inline void Server::output_error_log(const Error &err,
  8514. const Request *req) const {
  8515. if (error_logger_) {
  8516. std::lock_guard<std::mutex> guard(logger_mutex_);
  8517. error_logger_(err, req);
  8518. }
  8519. }
  8520. // HTTP client implementation
  8521. inline ClientImpl::ClientImpl(const std::string &host)
  8522. : ClientImpl(host, 80, std::string(), std::string()) {}
  8523. inline ClientImpl::ClientImpl(const std::string &host, int port)
  8524. : ClientImpl(host, port, std::string(), std::string()) {}
  8525. inline ClientImpl::ClientImpl(const std::string &host, int port,
  8526. const std::string &client_cert_path,
  8527. const std::string &client_key_path)
  8528. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  8529. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  8530. inline ClientImpl::~ClientImpl() {
  8531. // Wait until all the requests in flight are handled.
  8532. size_t retry_count = 10;
  8533. while (retry_count-- > 0) {
  8534. {
  8535. std::lock_guard<std::mutex> guard(socket_mutex_);
  8536. if (socket_requests_in_flight_ == 0) { break; }
  8537. }
  8538. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  8539. }
  8540. std::lock_guard<std::mutex> guard(socket_mutex_);
  8541. shutdown_socket(socket_);
  8542. close_socket(socket_);
  8543. }
  8544. inline bool ClientImpl::is_valid() const { return true; }
  8545. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  8546. client_cert_path_ = rhs.client_cert_path_;
  8547. client_key_path_ = rhs.client_key_path_;
  8548. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  8549. read_timeout_sec_ = rhs.read_timeout_sec_;
  8550. read_timeout_usec_ = rhs.read_timeout_usec_;
  8551. write_timeout_sec_ = rhs.write_timeout_sec_;
  8552. write_timeout_usec_ = rhs.write_timeout_usec_;
  8553. max_timeout_msec_ = rhs.max_timeout_msec_;
  8554. basic_auth_username_ = rhs.basic_auth_username_;
  8555. basic_auth_password_ = rhs.basic_auth_password_;
  8556. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  8557. keep_alive_ = rhs.keep_alive_;
  8558. follow_location_ = rhs.follow_location_;
  8559. path_encode_ = rhs.path_encode_;
  8560. address_family_ = rhs.address_family_;
  8561. tcp_nodelay_ = rhs.tcp_nodelay_;
  8562. ipv6_v6only_ = rhs.ipv6_v6only_;
  8563. socket_options_ = rhs.socket_options_;
  8564. compress_ = rhs.compress_;
  8565. decompress_ = rhs.decompress_;
  8566. interface_ = rhs.interface_;
  8567. proxy_host_ = rhs.proxy_host_;
  8568. proxy_port_ = rhs.proxy_port_;
  8569. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  8570. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  8571. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  8572. logger_ = rhs.logger_;
  8573. error_logger_ = rhs.error_logger_;
  8574. #ifdef CPPHTTPLIB_SSL_ENABLED
  8575. digest_auth_username_ = rhs.digest_auth_username_;
  8576. digest_auth_password_ = rhs.digest_auth_password_;
  8577. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  8578. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  8579. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  8580. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  8581. server_certificate_verification_ = rhs.server_certificate_verification_;
  8582. server_hostname_verification_ = rhs.server_hostname_verification_;
  8583. #endif
  8584. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8585. ca_cert_store_ = rhs.ca_cert_store_;
  8586. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  8587. #endif
  8588. }
  8589. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  8590. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8591. return detail::create_client_socket(
  8592. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  8593. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  8594. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  8595. write_timeout_sec_, write_timeout_usec_, interface_, error);
  8596. }
  8597. // Check is custom IP specified for host_
  8598. std::string ip;
  8599. auto it = addr_map_.find(host_);
  8600. if (it != addr_map_.end()) { ip = it->second; }
  8601. return detail::create_client_socket(
  8602. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  8603. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  8604. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8605. write_timeout_usec_, interface_, error);
  8606. }
  8607. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  8608. Error &error) {
  8609. auto sock = create_client_socket(error);
  8610. if (sock == INVALID_SOCKET) { return false; }
  8611. socket.sock = sock;
  8612. return true;
  8613. }
  8614. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  8615. return create_and_connect_socket(socket, error);
  8616. }
  8617. #ifdef CPPHTTPLIB_SSL_ENABLED
  8618. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  8619. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  8620. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  8621. if (!initialize_ssl(socket, error)) {
  8622. shutdown_socket(socket);
  8623. close_socket(socket);
  8624. return false;
  8625. }
  8626. return true;
  8627. }
  8628. #endif
  8629. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  8630. bool /*shutdown_gracefully*/) {
  8631. // If there are any requests in flight from threads other than us, then it's
  8632. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  8633. assert(socket_requests_in_flight_ == 0 ||
  8634. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8635. }
  8636. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  8637. if (socket.sock == INVALID_SOCKET) { return; }
  8638. detail::shutdown_socket(socket.sock);
  8639. }
  8640. inline void ClientImpl::close_socket(Socket &socket) {
  8641. // If there are requests in flight in another thread, usually closing
  8642. // the socket will be fine and they will simply receive an error when
  8643. // using the closed socket, but it is still a bug since rarely the OS
  8644. // may reassign the socket id to be used for a new socket, and then
  8645. // suddenly they will be operating on a live socket that is different
  8646. // than the one they intended!
  8647. assert(socket_requests_in_flight_ == 0 ||
  8648. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8649. // It is also a bug if this happens while SSL is still active
  8650. #ifdef CPPHTTPLIB_SSL_ENABLED
  8651. assert(socket.ssl == nullptr);
  8652. #endif
  8653. if (socket.sock == INVALID_SOCKET) { return; }
  8654. detail::close_socket(socket.sock);
  8655. socket.sock = INVALID_SOCKET;
  8656. }
  8657. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  8658. Response &res,
  8659. bool skip_100_continue) const {
  8660. std::array<char, 2048> buf{};
  8661. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8662. if (!line_reader.getline()) { return false; }
  8663. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  8664. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  8665. #else
  8666. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  8667. #endif
  8668. std::cmatch m;
  8669. if (!std::regex_match(line_reader.ptr(), m, re)) {
  8670. return req.method == "CONNECT";
  8671. }
  8672. res.version = std::string(m[1]);
  8673. res.status = std::stoi(std::string(m[2]));
  8674. res.reason = std::string(m[3]);
  8675. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  8676. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  8677. if (!line_reader.getline()) { return false; } // CRLF
  8678. if (!line_reader.getline()) { return false; } // next response line
  8679. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  8680. res.version = std::string(m[1]);
  8681. res.status = std::stoi(std::string(m[2]));
  8682. res.reason = std::string(m[3]);
  8683. }
  8684. return true;
  8685. }
  8686. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  8687. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  8688. auto ret = send_(req, res, error);
  8689. if (error == Error::SSLPeerCouldBeClosed_) {
  8690. assert(!ret);
  8691. ret = send_(req, res, error);
  8692. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  8693. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  8694. }
  8695. return ret;
  8696. }
  8697. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  8698. {
  8699. std::lock_guard<std::mutex> guard(socket_mutex_);
  8700. // Set this to false immediately - if it ever gets set to true by the end
  8701. // of the request, we know another thread instructed us to close the
  8702. // socket.
  8703. socket_should_be_closed_when_request_is_done_ = false;
  8704. auto is_alive = false;
  8705. if (socket_.is_open()) {
  8706. is_alive = detail::is_socket_alive(socket_.sock);
  8707. #ifdef CPPHTTPLIB_SSL_ENABLED
  8708. if (is_alive && is_ssl()) {
  8709. if (tls::tls_is_peer_closed(socket_.ssl, socket_.sock)) {
  8710. is_alive = false;
  8711. }
  8712. }
  8713. #endif
  8714. if (!is_alive) {
  8715. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  8716. // seems like the other side has already closed the connection Also,
  8717. // there cannot be any requests in flight from other threads since we
  8718. // locked request_mutex_, so safe to close everything immediately
  8719. const bool shutdown_gracefully = false;
  8720. shutdown_ssl(socket_, shutdown_gracefully);
  8721. shutdown_socket(socket_);
  8722. close_socket(socket_);
  8723. }
  8724. }
  8725. if (!is_alive) {
  8726. if (!ensure_socket_connection(socket_, error)) {
  8727. output_error_log(error, &req);
  8728. return false;
  8729. }
  8730. #ifdef CPPHTTPLIB_SSL_ENABLED
  8731. // TODO: refactoring
  8732. if (is_ssl()) {
  8733. auto &scli = static_cast<SSLClient &>(*this);
  8734. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8735. auto success = false;
  8736. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  8737. error)) {
  8738. if (!success) { output_error_log(error, &req); }
  8739. return success;
  8740. }
  8741. }
  8742. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8743. if (!scli.initialize_ssl(socket_, error)) {
  8744. output_error_log(error, &req);
  8745. return false;
  8746. }
  8747. }
  8748. }
  8749. #endif
  8750. }
  8751. // Mark the current socket as being in use so that it cannot be closed by
  8752. // anyone else while this request is ongoing, even though we will be
  8753. // releasing the mutex.
  8754. if (socket_requests_in_flight_ > 1) {
  8755. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  8756. }
  8757. socket_requests_in_flight_ += 1;
  8758. socket_requests_are_from_thread_ = std::this_thread::get_id();
  8759. }
  8760. for (const auto &header : default_headers_) {
  8761. if (req.headers.find(header.first) == req.headers.end()) {
  8762. req.headers.insert(header);
  8763. }
  8764. }
  8765. auto ret = false;
  8766. auto close_connection = !keep_alive_;
  8767. auto se = detail::scope_exit([&]() {
  8768. // Briefly lock mutex in order to mark that a request is no longer ongoing
  8769. std::lock_guard<std::mutex> guard(socket_mutex_);
  8770. socket_requests_in_flight_ -= 1;
  8771. if (socket_requests_in_flight_ <= 0) {
  8772. assert(socket_requests_in_flight_ == 0);
  8773. socket_requests_are_from_thread_ = std::thread::id();
  8774. }
  8775. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  8776. !ret) {
  8777. shutdown_ssl(socket_, true);
  8778. shutdown_socket(socket_);
  8779. close_socket(socket_);
  8780. }
  8781. });
  8782. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  8783. return handle_request(strm, req, res, close_connection, error);
  8784. });
  8785. if (!ret) {
  8786. if (error == Error::Success) {
  8787. error = Error::Unknown;
  8788. output_error_log(error, &req);
  8789. }
  8790. }
  8791. return ret;
  8792. }
  8793. inline Result ClientImpl::send(const Request &req) {
  8794. auto req2 = req;
  8795. return send_(std::move(req2));
  8796. }
  8797. inline Result ClientImpl::send_(Request &&req) {
  8798. auto res = detail::make_unique<Response>();
  8799. auto error = Error::Success;
  8800. auto ret = send(req, *res, error);
  8801. #ifdef CPPHTTPLIB_SSL_ENABLED
  8802. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  8803. last_ssl_error_, last_backend_error_};
  8804. #else
  8805. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  8806. #endif
  8807. }
  8808. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  8809. const std::string &ct) {
  8810. (void)for_stream;
  8811. for (const auto &header : default_headers_) {
  8812. if (!r.has_header(header.first)) { r.headers.insert(header); }
  8813. }
  8814. if (!r.has_header("Host")) {
  8815. if (address_family_ == AF_UNIX) {
  8816. r.headers.emplace("Host", "localhost");
  8817. } else {
  8818. r.headers.emplace(
  8819. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  8820. }
  8821. }
  8822. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  8823. if (!r.content_receiver) {
  8824. if (!r.has_header("Accept-Encoding")) {
  8825. std::string accept_encoding;
  8826. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8827. accept_encoding = "br";
  8828. #endif
  8829. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8830. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8831. accept_encoding += "gzip, deflate";
  8832. #endif
  8833. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8834. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8835. accept_encoding += "zstd";
  8836. #endif
  8837. r.set_header("Accept-Encoding", accept_encoding);
  8838. }
  8839. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  8840. if (!r.has_header("User-Agent")) {
  8841. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  8842. r.set_header("User-Agent", agent);
  8843. }
  8844. #endif
  8845. }
  8846. if (!r.body.empty()) {
  8847. if (!ct.empty() && !r.has_header("Content-Type")) {
  8848. r.headers.emplace("Content-Type", ct);
  8849. }
  8850. if (!r.has_header("Content-Length")) {
  8851. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  8852. }
  8853. }
  8854. }
  8855. inline ClientImpl::StreamHandle
  8856. ClientImpl::open_stream(const std::string &method, const std::string &path,
  8857. const Params &params, const Headers &headers,
  8858. const std::string &body,
  8859. const std::string &content_type) {
  8860. StreamHandle handle;
  8861. handle.response = detail::make_unique<Response>();
  8862. handle.error = Error::Success;
  8863. auto query_path = params.empty() ? path : append_query_params(path, params);
  8864. handle.connection_ = detail::make_unique<ClientConnection>();
  8865. {
  8866. std::lock_guard<std::mutex> guard(socket_mutex_);
  8867. auto is_alive = false;
  8868. if (socket_.is_open()) {
  8869. is_alive = detail::is_socket_alive(socket_.sock);
  8870. #ifdef CPPHTTPLIB_SSL_ENABLED
  8871. if (is_alive && is_ssl()) {
  8872. if (tls::tls_is_peer_closed(socket_.ssl, socket_.sock)) {
  8873. is_alive = false;
  8874. }
  8875. }
  8876. #endif
  8877. if (!is_alive) {
  8878. shutdown_ssl(socket_, false);
  8879. shutdown_socket(socket_);
  8880. close_socket(socket_);
  8881. }
  8882. }
  8883. if (!is_alive) {
  8884. if (!ensure_socket_connection(socket_, handle.error)) {
  8885. handle.response.reset();
  8886. return handle;
  8887. }
  8888. #ifdef CPPHTTPLIB_SSL_ENABLED
  8889. if (is_ssl()) {
  8890. auto &scli = static_cast<SSLClient &>(*this);
  8891. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8892. if (!scli.initialize_ssl(socket_, handle.error)) {
  8893. handle.response.reset();
  8894. return handle;
  8895. }
  8896. }
  8897. }
  8898. #endif
  8899. }
  8900. transfer_socket_ownership_to_handle(handle);
  8901. }
  8902. #ifdef CPPHTTPLIB_SSL_ENABLED
  8903. if (is_ssl() && handle.connection_->session) {
  8904. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  8905. handle.connection_->sock, handle.connection_->session,
  8906. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8907. write_timeout_usec_);
  8908. } else {
  8909. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8910. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8911. write_timeout_sec_, write_timeout_usec_);
  8912. }
  8913. #else
  8914. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8915. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8916. write_timeout_sec_, write_timeout_usec_);
  8917. #endif
  8918. handle.stream_ = handle.socket_stream_.get();
  8919. Request req;
  8920. req.method = method;
  8921. req.path = query_path;
  8922. req.headers = headers;
  8923. req.body = body;
  8924. prepare_default_headers(req, true, content_type);
  8925. auto &strm = *handle.stream_;
  8926. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  8927. handle.error = Error::Write;
  8928. handle.response.reset();
  8929. return handle;
  8930. }
  8931. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  8932. handle.error)) {
  8933. handle.response.reset();
  8934. return handle;
  8935. }
  8936. if (!body.empty()) {
  8937. if (strm.write(body.data(), body.size()) < 0) {
  8938. handle.error = Error::Write;
  8939. handle.response.reset();
  8940. return handle;
  8941. }
  8942. }
  8943. if (!read_response_line(strm, req, *handle.response) ||
  8944. !detail::read_headers(strm, handle.response->headers)) {
  8945. handle.error = Error::Read;
  8946. handle.response.reset();
  8947. return handle;
  8948. }
  8949. handle.body_reader_.stream = handle.stream_;
  8950. auto content_length_str = handle.response->get_header_value("Content-Length");
  8951. if (!content_length_str.empty()) {
  8952. handle.body_reader_.content_length =
  8953. static_cast<size_t>(std::stoull(content_length_str));
  8954. }
  8955. auto transfer_encoding =
  8956. handle.response->get_header_value("Transfer-Encoding");
  8957. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  8958. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  8959. if (!content_encoding.empty()) {
  8960. handle.decompressor_ = detail::create_decompressor(content_encoding);
  8961. }
  8962. return handle;
  8963. }
  8964. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  8965. if (!is_valid() || !response) { return -1; }
  8966. if (decompressor_) { return read_with_decompression(buf, len); }
  8967. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  8968. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  8969. trailers_parsed_ = true;
  8970. if (body_reader_.chunked_decoder) {
  8971. if (!body_reader_.chunked_decoder->parse_trailers_into(
  8972. response->trailers, response->headers)) {
  8973. return n;
  8974. }
  8975. } else {
  8976. detail::ChunkedDecoder dec(*stream_);
  8977. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  8978. return n;
  8979. }
  8980. }
  8981. }
  8982. return n;
  8983. }
  8984. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  8985. size_t len) {
  8986. if (decompress_offset_ < decompress_buffer_.size()) {
  8987. auto available = decompress_buffer_.size() - decompress_offset_;
  8988. auto to_copy = (std::min)(len, available);
  8989. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  8990. decompress_offset_ += to_copy;
  8991. return static_cast<ssize_t>(to_copy);
  8992. }
  8993. decompress_buffer_.clear();
  8994. decompress_offset_ = 0;
  8995. constexpr size_t kDecompressionBufferSize = 8192;
  8996. char compressed_buf[kDecompressionBufferSize];
  8997. while (true) {
  8998. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  8999. sizeof(compressed_buf));
  9000. if (n <= 0) { return n; }
  9001. bool decompress_ok =
  9002. decompressor_->decompress(compressed_buf, static_cast<size_t>(n),
  9003. [this](const char *data, size_t data_len) {
  9004. decompress_buffer_.append(data, data_len);
  9005. return true;
  9006. });
  9007. if (!decompress_ok) {
  9008. body_reader_.last_error = Error::Read;
  9009. return -1;
  9010. }
  9011. if (!decompress_buffer_.empty()) { break; }
  9012. }
  9013. auto to_copy = (std::min)(len, decompress_buffer_.size());
  9014. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  9015. decompress_offset_ = to_copy;
  9016. return static_cast<ssize_t>(to_copy);
  9017. }
  9018. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  9019. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  9020. return;
  9021. }
  9022. trailers_parsed_ = true;
  9023. const auto bufsiz = 128;
  9024. char line_buf[bufsiz];
  9025. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  9026. if (!line_reader.getline()) { return; }
  9027. if (!detail::parse_trailers(line_reader, response->trailers,
  9028. response->headers)) {
  9029. return;
  9030. }
  9031. }
  9032. // Inline method implementations for `ChunkedDecoder`.
  9033. namespace detail {
  9034. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  9035. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  9036. size_t &out_chunk_offset,
  9037. size_t &out_chunk_total) {
  9038. if (finished) { return 0; }
  9039. if (chunk_remaining == 0) {
  9040. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9041. if (!lr.getline()) { return -1; }
  9042. char *endptr = nullptr;
  9043. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  9044. if (endptr == lr.ptr()) { return -1; }
  9045. if (chunk_len == ULONG_MAX) { return -1; }
  9046. if (chunk_len == 0) {
  9047. chunk_remaining = 0;
  9048. finished = true;
  9049. out_chunk_offset = 0;
  9050. out_chunk_total = 0;
  9051. return 0;
  9052. }
  9053. chunk_remaining = static_cast<size_t>(chunk_len);
  9054. last_chunk_total = chunk_remaining;
  9055. last_chunk_offset = 0;
  9056. }
  9057. auto to_read = (std::min)(chunk_remaining, len);
  9058. auto n = strm.read(buf, to_read);
  9059. if (n <= 0) { return -1; }
  9060. auto offset_before = last_chunk_offset;
  9061. last_chunk_offset += static_cast<size_t>(n);
  9062. chunk_remaining -= static_cast<size_t>(n);
  9063. out_chunk_offset = offset_before;
  9064. out_chunk_total = last_chunk_total;
  9065. if (chunk_remaining == 0) {
  9066. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9067. if (!lr.getline()) { return -1; }
  9068. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  9069. }
  9070. return n;
  9071. }
  9072. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  9073. const Headers &src_headers) {
  9074. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9075. if (!lr.getline()) { return false; }
  9076. return parse_trailers(lr, dest, src_headers);
  9077. }
  9078. } // namespace detail
  9079. inline void
  9080. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  9081. handle.connection_->sock = socket_.sock;
  9082. #ifdef CPPHTTPLIB_SSL_ENABLED
  9083. handle.connection_->session = socket_.ssl;
  9084. socket_.ssl = nullptr;
  9085. #endif
  9086. socket_.sock = INVALID_SOCKET;
  9087. }
  9088. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  9089. Response &res, bool close_connection,
  9090. Error &error) {
  9091. if (req.path.empty()) {
  9092. error = Error::Connection;
  9093. output_error_log(error, &req);
  9094. return false;
  9095. }
  9096. auto req_save = req;
  9097. bool ret;
  9098. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  9099. auto req2 = req;
  9100. req2.path = "http://" +
  9101. detail::make_host_and_port_string(host_, port_, false) +
  9102. req.path;
  9103. ret = process_request(strm, req2, res, close_connection, error);
  9104. req = std::move(req2);
  9105. req.path = req_save.path;
  9106. } else {
  9107. ret = process_request(strm, req, res, close_connection, error);
  9108. }
  9109. if (!ret) { return false; }
  9110. if (res.get_header_value("Connection") == "close" ||
  9111. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  9112. // TODO this requires a not-entirely-obvious chain of calls to be correct
  9113. // for this to be safe.
  9114. // This is safe to call because handle_request is only called by send_
  9115. // which locks the request mutex during the process. It would be a bug
  9116. // to call it from a different thread since it's a thread-safety issue
  9117. // to do these things to the socket if another thread is using the socket.
  9118. std::lock_guard<std::mutex> guard(socket_mutex_);
  9119. shutdown_ssl(socket_, true);
  9120. shutdown_socket(socket_);
  9121. close_socket(socket_);
  9122. }
  9123. if (300 < res.status && res.status < 400 && follow_location_) {
  9124. req = std::move(req_save);
  9125. ret = redirect(req, res, error);
  9126. }
  9127. #ifdef CPPHTTPLIB_SSL_ENABLED
  9128. if ((res.status == StatusCode::Unauthorized_401 ||
  9129. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  9130. req.authorization_count_ < 5) {
  9131. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  9132. const auto &username =
  9133. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  9134. const auto &password =
  9135. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  9136. if (!username.empty() && !password.empty()) {
  9137. std::map<std::string, std::string> auth;
  9138. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  9139. Request new_req = req;
  9140. new_req.authorization_count_ += 1;
  9141. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  9142. : "Authorization");
  9143. new_req.headers.insert(detail::make_digest_authentication_header(
  9144. req, auth, new_req.authorization_count_, detail::random_string(10),
  9145. username, password, is_proxy));
  9146. Response new_res;
  9147. ret = send(new_req, new_res, error);
  9148. if (ret) { res = std::move(new_res); }
  9149. }
  9150. }
  9151. }
  9152. #endif
  9153. return ret;
  9154. }
  9155. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  9156. if (req.redirect_count_ == 0) {
  9157. error = Error::ExceedRedirectCount;
  9158. output_error_log(error, &req);
  9159. return false;
  9160. }
  9161. auto location = res.get_header_value("location");
  9162. if (location.empty()) { return false; }
  9163. thread_local const std::regex re(
  9164. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  9165. std::smatch m;
  9166. if (!std::regex_match(location, m, re)) { return false; }
  9167. auto scheme = is_ssl() ? "https" : "http";
  9168. auto next_scheme = m[1].str();
  9169. auto next_host = m[2].str();
  9170. if (next_host.empty()) { next_host = m[3].str(); }
  9171. auto port_str = m[4].str();
  9172. auto next_path = m[5].str();
  9173. auto next_query = m[6].str();
  9174. auto next_port = port_;
  9175. if (!port_str.empty()) {
  9176. next_port = std::stoi(port_str);
  9177. } else if (!next_scheme.empty()) {
  9178. next_port = next_scheme == "https" ? 443 : 80;
  9179. }
  9180. if (next_scheme.empty()) { next_scheme = scheme; }
  9181. if (next_host.empty()) { next_host = host_; }
  9182. if (next_path.empty()) { next_path = "/"; }
  9183. auto path = decode_query_component(next_path, true) + next_query;
  9184. // Same host redirect - use current client
  9185. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  9186. return detail::redirect(*this, req, res, path, location, error);
  9187. }
  9188. // Cross-host/scheme redirect - create new client with robust setup
  9189. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  9190. path, location, error);
  9191. }
  9192. // New method for robust redirect client creation
  9193. inline bool ClientImpl::create_redirect_client(
  9194. const std::string &scheme, const std::string &host, int port, Request &req,
  9195. Response &res, const std::string &path, const std::string &location,
  9196. Error &error) {
  9197. // Determine if we need SSL
  9198. auto need_ssl = (scheme == "https");
  9199. // Clean up request headers that are host/client specific
  9200. // Remove headers that should not be carried over to new host
  9201. auto headers_to_remove =
  9202. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  9203. for (const auto &header_name : headers_to_remove) {
  9204. auto it = req.headers.find(header_name);
  9205. while (it != req.headers.end()) {
  9206. it = req.headers.erase(it);
  9207. it = req.headers.find(header_name);
  9208. }
  9209. }
  9210. // Create appropriate client type and handle redirect
  9211. if (need_ssl) {
  9212. #ifdef CPPHTTPLIB_SSL_ENABLED
  9213. // Create SSL client for HTTPS redirect
  9214. SSLClient redirect_client(host, port);
  9215. // Setup basic client configuration first
  9216. setup_redirect_client(redirect_client);
  9217. // SSL-specific configuration for proxy environments
  9218. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9219. // Critical: Disable SSL verification for proxy environments
  9220. redirect_client.enable_server_certificate_verification(false);
  9221. redirect_client.enable_server_hostname_verification(false);
  9222. } else {
  9223. // For direct SSL connections, copy SSL verification settings
  9224. redirect_client.enable_server_certificate_verification(
  9225. server_certificate_verification_);
  9226. redirect_client.enable_server_hostname_verification(
  9227. server_hostname_verification_);
  9228. }
  9229. // Transfer CA certificate to redirect client
  9230. if (!ca_cert_pem_.empty()) {
  9231. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  9232. ca_cert_pem_.size());
  9233. }
  9234. if (!ca_cert_file_path_.empty()) {
  9235. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  9236. }
  9237. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9238. // OpenSSL-specific: Handle CA certificate store
  9239. if (ca_cert_store_ && X509_STORE_up_ref(ca_cert_store_)) {
  9240. redirect_client.set_ca_cert_store(ca_cert_store_);
  9241. }
  9242. #endif
  9243. // Client certificates are set through constructor for SSLClient
  9244. // NOTE: SSLClient constructor already takes client_cert_path and
  9245. // client_key_path so we need to create it properly if client certs are
  9246. // needed
  9247. // Execute the redirect
  9248. return detail::redirect(redirect_client, req, res, path, location, error);
  9249. #else
  9250. // SSL not supported - set appropriate error
  9251. error = Error::SSLConnection;
  9252. output_error_log(error, &req);
  9253. return false;
  9254. #endif
  9255. } else {
  9256. // HTTP redirect
  9257. ClientImpl redirect_client(host, port);
  9258. // Setup client with robust configuration
  9259. setup_redirect_client(redirect_client);
  9260. // Execute the redirect
  9261. return detail::redirect(redirect_client, req, res, path, location, error);
  9262. }
  9263. }
  9264. // New method for robust client setup (based on basic_manual_redirect.cpp
  9265. // logic)
  9266. template <typename ClientType>
  9267. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  9268. // Copy basic settings first
  9269. client.set_connection_timeout(connection_timeout_sec_);
  9270. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  9271. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  9272. client.set_keep_alive(keep_alive_);
  9273. client.set_follow_location(
  9274. true); // Enable redirects to handle multi-step redirects
  9275. client.set_path_encode(path_encode_);
  9276. client.set_compress(compress_);
  9277. client.set_decompress(decompress_);
  9278. // Copy authentication settings BEFORE proxy setup
  9279. if (!basic_auth_username_.empty()) {
  9280. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  9281. }
  9282. if (!bearer_token_auth_token_.empty()) {
  9283. client.set_bearer_token_auth(bearer_token_auth_token_);
  9284. }
  9285. #ifdef CPPHTTPLIB_SSL_ENABLED
  9286. if (!digest_auth_username_.empty()) {
  9287. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  9288. }
  9289. #endif
  9290. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  9291. // before proxy auth)
  9292. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9293. // First set proxy host and port
  9294. client.set_proxy(proxy_host_, proxy_port_);
  9295. // Then set proxy authentication (order matters!)
  9296. if (!proxy_basic_auth_username_.empty()) {
  9297. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  9298. proxy_basic_auth_password_);
  9299. }
  9300. if (!proxy_bearer_token_auth_token_.empty()) {
  9301. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  9302. }
  9303. #ifdef CPPHTTPLIB_SSL_ENABLED
  9304. if (!proxy_digest_auth_username_.empty()) {
  9305. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  9306. proxy_digest_auth_password_);
  9307. }
  9308. #endif
  9309. }
  9310. // Copy network and socket settings
  9311. client.set_address_family(address_family_);
  9312. client.set_tcp_nodelay(tcp_nodelay_);
  9313. client.set_ipv6_v6only(ipv6_v6only_);
  9314. if (socket_options_) { client.set_socket_options(socket_options_); }
  9315. if (!interface_.empty()) { client.set_interface(interface_); }
  9316. // Copy logging and headers
  9317. if (logger_) { client.set_logger(logger_); }
  9318. if (error_logger_) { client.set_error_logger(error_logger_); }
  9319. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  9320. // Each new client should generate its own headers based on its target host
  9321. }
  9322. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  9323. const Request &req,
  9324. Error &error) const {
  9325. auto is_shutting_down = []() { return false; };
  9326. if (req.is_chunked_content_provider_) {
  9327. // TODO: Brotli support
  9328. std::unique_ptr<detail::compressor> compressor;
  9329. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9330. if (compress_) {
  9331. compressor = detail::make_unique<detail::gzip_compressor>();
  9332. } else
  9333. #endif
  9334. {
  9335. compressor = detail::make_unique<detail::nocompressor>();
  9336. }
  9337. return detail::write_content_chunked(strm, req.content_provider_,
  9338. is_shutting_down, *compressor, error);
  9339. } else {
  9340. return detail::write_content_with_progress(
  9341. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  9342. req.upload_progress, error);
  9343. }
  9344. }
  9345. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  9346. bool close_connection, Error &error,
  9347. bool skip_body) {
  9348. // Prepare additional headers
  9349. if (close_connection) {
  9350. if (!req.has_header("Connection")) {
  9351. req.set_header("Connection", "close");
  9352. }
  9353. }
  9354. std::string ct_for_defaults;
  9355. if (!req.has_header("Content-Type") && !req.body.empty()) {
  9356. ct_for_defaults = "text/plain";
  9357. }
  9358. prepare_default_headers(req, false, ct_for_defaults);
  9359. if (req.body.empty()) {
  9360. if (req.content_provider_) {
  9361. if (!req.is_chunked_content_provider_) {
  9362. if (!req.has_header("Content-Length")) {
  9363. auto length = std::to_string(req.content_length_);
  9364. req.set_header("Content-Length", length);
  9365. }
  9366. }
  9367. } else {
  9368. if (req.method == "POST" || req.method == "PUT" ||
  9369. req.method == "PATCH") {
  9370. req.set_header("Content-Length", "0");
  9371. }
  9372. }
  9373. }
  9374. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  9375. if (!req.has_header("Authorization")) {
  9376. req.headers.insert(make_basic_authentication_header(
  9377. basic_auth_username_, basic_auth_password_, false));
  9378. }
  9379. }
  9380. if (!proxy_basic_auth_username_.empty() &&
  9381. !proxy_basic_auth_password_.empty()) {
  9382. if (!req.has_header("Proxy-Authorization")) {
  9383. req.headers.insert(make_basic_authentication_header(
  9384. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  9385. }
  9386. }
  9387. if (!bearer_token_auth_token_.empty()) {
  9388. if (!req.has_header("Authorization")) {
  9389. req.headers.insert(make_bearer_token_authentication_header(
  9390. bearer_token_auth_token_, false));
  9391. }
  9392. }
  9393. if (!proxy_bearer_token_auth_token_.empty()) {
  9394. if (!req.has_header("Proxy-Authorization")) {
  9395. req.headers.insert(make_bearer_token_authentication_header(
  9396. proxy_bearer_token_auth_token_, true));
  9397. }
  9398. }
  9399. // Request line and headers
  9400. {
  9401. detail::BufferStream bstrm;
  9402. // Extract path and query from req.path
  9403. std::string path_part, query_part;
  9404. auto query_pos = req.path.find('?');
  9405. if (query_pos != std::string::npos) {
  9406. path_part = req.path.substr(0, query_pos);
  9407. query_part = req.path.substr(query_pos + 1);
  9408. } else {
  9409. path_part = req.path;
  9410. query_part = "";
  9411. }
  9412. // Encode path part. If the original `req.path` already contained a
  9413. // query component, preserve its raw query string (including parameter
  9414. // order) instead of reparsing and reassembling it which may reorder
  9415. // parameters due to container ordering (e.g. `Params` uses
  9416. // `std::multimap`). When there is no query in `req.path`, fall back to
  9417. // building a query from `req.params` so existing callers that pass
  9418. // `Params` continue to work.
  9419. auto path_with_query =
  9420. path_encode_ ? detail::encode_path(path_part) : path_part;
  9421. if (!query_part.empty()) {
  9422. // Normalize the query string (decode then re-encode) while preserving
  9423. // the original parameter order.
  9424. auto normalized = detail::normalize_query_string(query_part);
  9425. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  9426. // Still populate req.params for handlers/users who read them.
  9427. detail::parse_query_text(query_part, req.params);
  9428. } else {
  9429. // No query in path; parse any query_part (empty) and append params
  9430. // from `req.params` when present (preserves prior behavior for
  9431. // callers who provide Params separately).
  9432. detail::parse_query_text(query_part, req.params);
  9433. if (!req.params.empty()) {
  9434. path_with_query = append_query_params(path_with_query, req.params);
  9435. }
  9436. }
  9437. // Write request line and headers
  9438. detail::write_request_line(bstrm, req.method, path_with_query);
  9439. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  9440. error)) {
  9441. output_error_log(error, &req);
  9442. return false;
  9443. }
  9444. // Flush buffer
  9445. auto &data = bstrm.get_buffer();
  9446. if (!detail::write_data(strm, data.data(), data.size())) {
  9447. error = Error::Write;
  9448. output_error_log(error, &req);
  9449. return false;
  9450. }
  9451. }
  9452. // After sending request line and headers, wait briefly for an early server
  9453. // response (e.g. 4xx) and avoid sending a potentially large request body
  9454. // unnecessarily. This workaround is only enabled on Windows because Unix
  9455. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  9456. // buffering can accept large writes even when the peer already responded.
  9457. // Check the stream first (which covers SSL via `is_readable()`), then
  9458. // fall back to select on the socket. Only perform the wait for very large
  9459. // request bodies to avoid interfering with normal small requests and
  9460. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  9461. // response. Skip this check when using Expect: 100-continue, as the protocol
  9462. // handles early responses properly.
  9463. #if defined(_WIN32)
  9464. if (!skip_body &&
  9465. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  9466. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  9467. auto start = std::chrono::high_resolution_clock::now();
  9468. for (;;) {
  9469. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  9470. // from SSL internals. If the underlying socket is readable, assume an
  9471. // early response may be present.
  9472. auto sock = strm.socket();
  9473. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  9474. return false;
  9475. }
  9476. // Fallback to stream-level check for non-socket streams or when the
  9477. // socket isn't reporting readable. Avoid using `is_readable()` for
  9478. // SSL, since `SSL_pending()` may report buffered records that do not
  9479. // indicate a complete application-level response yet.
  9480. if (!is_ssl() && strm.is_readable()) { return false; }
  9481. auto now = std::chrono::high_resolution_clock::now();
  9482. auto elapsed =
  9483. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  9484. .count();
  9485. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  9486. break;
  9487. }
  9488. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  9489. }
  9490. }
  9491. #endif
  9492. // Body
  9493. if (skip_body) { return true; }
  9494. return write_request_body(strm, req, error);
  9495. }
  9496. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  9497. Error &error) {
  9498. if (req.body.empty()) {
  9499. return write_content_with_provider(strm, req, error);
  9500. }
  9501. if (req.upload_progress) {
  9502. auto body_size = req.body.size();
  9503. size_t written = 0;
  9504. auto data = req.body.data();
  9505. while (written < body_size) {
  9506. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  9507. if (!detail::write_data(strm, data + written, to_write)) {
  9508. error = Error::Write;
  9509. output_error_log(error, &req);
  9510. return false;
  9511. }
  9512. written += to_write;
  9513. if (!req.upload_progress(written, body_size)) {
  9514. error = Error::Canceled;
  9515. output_error_log(error, &req);
  9516. return false;
  9517. }
  9518. }
  9519. } else {
  9520. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  9521. error = Error::Write;
  9522. output_error_log(error, &req);
  9523. return false;
  9524. }
  9525. }
  9526. return true;
  9527. }
  9528. inline std::unique_ptr<Response>
  9529. ClientImpl::send_with_content_provider_and_receiver(
  9530. Request &req, const char *body, size_t content_length,
  9531. ContentProvider content_provider,
  9532. ContentProviderWithoutLength content_provider_without_length,
  9533. const std::string &content_type, ContentReceiver content_receiver,
  9534. Error &error) {
  9535. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9536. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9537. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  9538. #endif
  9539. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9540. if (compress_ && !content_provider_without_length) {
  9541. // TODO: Brotli support
  9542. detail::gzip_compressor compressor;
  9543. if (content_provider) {
  9544. auto ok = true;
  9545. size_t offset = 0;
  9546. DataSink data_sink;
  9547. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  9548. if (ok) {
  9549. auto last = offset + data_len == content_length;
  9550. auto ret = compressor.compress(
  9551. data, data_len, last,
  9552. [&](const char *compressed_data, size_t compressed_data_len) {
  9553. req.body.append(compressed_data, compressed_data_len);
  9554. return true;
  9555. });
  9556. if (ret) {
  9557. offset += data_len;
  9558. } else {
  9559. ok = false;
  9560. }
  9561. }
  9562. return ok;
  9563. };
  9564. while (ok && offset < content_length) {
  9565. if (!content_provider(offset, content_length - offset, data_sink)) {
  9566. error = Error::Canceled;
  9567. output_error_log(error, &req);
  9568. return nullptr;
  9569. }
  9570. }
  9571. } else {
  9572. if (!compressor.compress(body, content_length, true,
  9573. [&](const char *data, size_t data_len) {
  9574. req.body.append(data, data_len);
  9575. return true;
  9576. })) {
  9577. error = Error::Compression;
  9578. output_error_log(error, &req);
  9579. return nullptr;
  9580. }
  9581. }
  9582. } else
  9583. #endif
  9584. {
  9585. if (content_provider) {
  9586. req.content_length_ = content_length;
  9587. req.content_provider_ = std::move(content_provider);
  9588. req.is_chunked_content_provider_ = false;
  9589. } else if (content_provider_without_length) {
  9590. req.content_length_ = 0;
  9591. req.content_provider_ = detail::ContentProviderAdapter(
  9592. std::move(content_provider_without_length));
  9593. req.is_chunked_content_provider_ = true;
  9594. req.set_header("Transfer-Encoding", "chunked");
  9595. } else {
  9596. req.body.assign(body, content_length);
  9597. }
  9598. }
  9599. if (content_receiver) {
  9600. req.content_receiver =
  9601. [content_receiver](const char *data, size_t data_length,
  9602. size_t /*offset*/, size_t /*total_length*/) {
  9603. return content_receiver(data, data_length);
  9604. };
  9605. }
  9606. auto res = detail::make_unique<Response>();
  9607. return send(req, *res, error) ? std::move(res) : nullptr;
  9608. }
  9609. inline Result ClientImpl::send_with_content_provider_and_receiver(
  9610. const std::string &method, const std::string &path, const Headers &headers,
  9611. const char *body, size_t content_length, ContentProvider content_provider,
  9612. ContentProviderWithoutLength content_provider_without_length,
  9613. const std::string &content_type, ContentReceiver content_receiver,
  9614. UploadProgress progress) {
  9615. Request req;
  9616. req.method = method;
  9617. req.headers = headers;
  9618. req.path = path;
  9619. req.upload_progress = std::move(progress);
  9620. if (max_timeout_msec_ > 0) {
  9621. req.start_time_ = std::chrono::steady_clock::now();
  9622. }
  9623. auto error = Error::Success;
  9624. auto res = send_with_content_provider_and_receiver(
  9625. req, body, content_length, std::move(content_provider),
  9626. std::move(content_provider_without_length), content_type,
  9627. std::move(content_receiver), error);
  9628. #ifdef CPPHTTPLIB_SSL_ENABLED
  9629. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  9630. last_backend_error_};
  9631. #else
  9632. return Result{std::move(res), error, std::move(req.headers)};
  9633. #endif
  9634. }
  9635. inline void ClientImpl::output_log(const Request &req,
  9636. const Response &res) const {
  9637. if (logger_) {
  9638. std::lock_guard<std::mutex> guard(logger_mutex_);
  9639. logger_(req, res);
  9640. }
  9641. }
  9642. inline void ClientImpl::output_error_log(const Error &err,
  9643. const Request *req) const {
  9644. if (error_logger_) {
  9645. std::lock_guard<std::mutex> guard(logger_mutex_);
  9646. error_logger_(err, req);
  9647. }
  9648. }
  9649. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  9650. Response &res, bool close_connection,
  9651. Error &error) {
  9652. // Auto-add Expect: 100-continue for large bodies
  9653. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  9654. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  9655. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  9656. req.set_header("Expect", "100-continue");
  9657. }
  9658. }
  9659. // Check for Expect: 100-continue
  9660. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  9661. // Send request (skip body if using Expect: 100-continue)
  9662. auto write_request_success =
  9663. write_request(strm, req, close_connection, error, expect_100_continue);
  9664. #ifdef CPPHTTPLIB_SSL_ENABLED
  9665. if (is_ssl()) {
  9666. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  9667. if (!is_proxy_enabled) {
  9668. if (tls::tls_is_peer_closed(socket_.ssl, socket_.sock)) {
  9669. error = Error::SSLPeerCouldBeClosed_;
  9670. output_error_log(error, &req);
  9671. return false;
  9672. }
  9673. }
  9674. }
  9675. #endif
  9676. // Handle Expect: 100-continue with timeout
  9677. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  9678. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  9679. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  9680. auto ret = detail::select_read(strm.socket(), sec, usec);
  9681. if (ret <= 0) {
  9682. // Timeout or error: send body anyway (server didn't respond in time)
  9683. if (!write_request_body(strm, req, error)) { return false; }
  9684. expect_100_continue = false; // Switch to normal response handling
  9685. }
  9686. }
  9687. // Receive response and headers
  9688. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  9689. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  9690. !detail::read_headers(strm, res.headers)) {
  9691. if (write_request_success) { error = Error::Read; }
  9692. output_error_log(error, &req);
  9693. return false;
  9694. }
  9695. if (!write_request_success) { return false; }
  9696. // Handle Expect: 100-continue response
  9697. if (expect_100_continue) {
  9698. if (res.status == StatusCode::Continue_100) {
  9699. // Server accepted, send the body
  9700. if (!write_request_body(strm, req, error)) { return false; }
  9701. // Read the actual response
  9702. res.headers.clear();
  9703. res.body.clear();
  9704. if (!read_response_line(strm, req, res) ||
  9705. !detail::read_headers(strm, res.headers)) {
  9706. error = Error::Read;
  9707. output_error_log(error, &req);
  9708. return false;
  9709. }
  9710. }
  9711. // If not 100 Continue, server returned an error; proceed with that response
  9712. }
  9713. // Body
  9714. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  9715. req.method != "CONNECT") {
  9716. auto redirect = 300 < res.status && res.status < 400 &&
  9717. res.status != StatusCode::NotModified_304 &&
  9718. follow_location_;
  9719. if (req.response_handler && !redirect) {
  9720. if (!req.response_handler(res)) {
  9721. error = Error::Canceled;
  9722. output_error_log(error, &req);
  9723. return false;
  9724. }
  9725. }
  9726. auto out =
  9727. req.content_receiver
  9728. ? static_cast<ContentReceiverWithProgress>(
  9729. [&](const char *buf, size_t n, size_t off, size_t len) {
  9730. if (redirect) { return true; }
  9731. auto ret = req.content_receiver(buf, n, off, len);
  9732. if (!ret) {
  9733. error = Error::Canceled;
  9734. output_error_log(error, &req);
  9735. }
  9736. return ret;
  9737. })
  9738. : static_cast<ContentReceiverWithProgress>(
  9739. [&](const char *buf, size_t n, size_t /*off*/,
  9740. size_t /*len*/) {
  9741. assert(res.body.size() + n <= res.body.max_size());
  9742. res.body.append(buf, n);
  9743. return true;
  9744. });
  9745. auto progress = [&](size_t current, size_t total) {
  9746. if (!req.download_progress || redirect) { return true; }
  9747. auto ret = req.download_progress(current, total);
  9748. if (!ret) {
  9749. error = Error::Canceled;
  9750. output_error_log(error, &req);
  9751. }
  9752. return ret;
  9753. };
  9754. if (res.has_header("Content-Length")) {
  9755. if (!req.content_receiver) {
  9756. auto len = res.get_header_value_u64("Content-Length");
  9757. if (len > res.body.max_size()) {
  9758. error = Error::Read;
  9759. output_error_log(error, &req);
  9760. return false;
  9761. }
  9762. res.body.reserve(static_cast<size_t>(len));
  9763. }
  9764. }
  9765. if (res.status != StatusCode::NotModified_304) {
  9766. int dummy_status;
  9767. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  9768. dummy_status, std::move(progress),
  9769. std::move(out), decompress_)) {
  9770. if (error != Error::Canceled) { error = Error::Read; }
  9771. output_error_log(error, &req);
  9772. return false;
  9773. }
  9774. }
  9775. }
  9776. // Log
  9777. output_log(req, res);
  9778. return true;
  9779. }
  9780. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  9781. const std::string &boundary, const UploadFormDataItems &items,
  9782. const FormDataProviderItems &provider_items) const {
  9783. size_t cur_item = 0;
  9784. size_t cur_start = 0;
  9785. // cur_item and cur_start are copied to within the std::function and
  9786. // maintain state between successive calls
  9787. return [&, cur_item, cur_start](size_t offset,
  9788. DataSink &sink) mutable -> bool {
  9789. if (!offset && !items.empty()) {
  9790. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  9791. return true;
  9792. } else if (cur_item < provider_items.size()) {
  9793. if (!cur_start) {
  9794. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  9795. provider_items[cur_item], boundary);
  9796. offset += begin.size();
  9797. cur_start = offset;
  9798. sink.os << begin;
  9799. }
  9800. DataSink cur_sink;
  9801. auto has_data = true;
  9802. cur_sink.write = sink.write;
  9803. cur_sink.done = [&]() { has_data = false; };
  9804. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  9805. return false;
  9806. }
  9807. if (!has_data) {
  9808. sink.os << detail::serialize_multipart_formdata_item_end();
  9809. cur_item++;
  9810. cur_start = 0;
  9811. }
  9812. return true;
  9813. } else {
  9814. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  9815. sink.done();
  9816. return true;
  9817. }
  9818. };
  9819. }
  9820. inline bool ClientImpl::process_socket(
  9821. const Socket &socket,
  9822. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9823. std::function<bool(Stream &strm)> callback) {
  9824. return detail::process_client_socket(
  9825. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9826. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  9827. }
  9828. inline bool ClientImpl::is_ssl() const { return false; }
  9829. inline Result ClientImpl::Get(const std::string &path,
  9830. DownloadProgress progress) {
  9831. return Get(path, Headers(), std::move(progress));
  9832. }
  9833. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9834. const Headers &headers,
  9835. DownloadProgress progress) {
  9836. if (params.empty()) { return Get(path, headers); }
  9837. std::string path_with_query = append_query_params(path, params);
  9838. return Get(path_with_query, headers, std::move(progress));
  9839. }
  9840. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9841. DownloadProgress progress) {
  9842. Request req;
  9843. req.method = "GET";
  9844. req.path = path;
  9845. req.headers = headers;
  9846. req.download_progress = std::move(progress);
  9847. if (max_timeout_msec_ > 0) {
  9848. req.start_time_ = std::chrono::steady_clock::now();
  9849. }
  9850. return send_(std::move(req));
  9851. }
  9852. inline Result ClientImpl::Get(const std::string &path,
  9853. ContentReceiver content_receiver,
  9854. DownloadProgress progress) {
  9855. return Get(path, Headers(), nullptr, std::move(content_receiver),
  9856. std::move(progress));
  9857. }
  9858. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9859. ContentReceiver content_receiver,
  9860. DownloadProgress progress) {
  9861. return Get(path, headers, nullptr, std::move(content_receiver),
  9862. std::move(progress));
  9863. }
  9864. inline Result ClientImpl::Get(const std::string &path,
  9865. ResponseHandler response_handler,
  9866. ContentReceiver content_receiver,
  9867. DownloadProgress progress) {
  9868. return Get(path, Headers(), std::move(response_handler),
  9869. std::move(content_receiver), std::move(progress));
  9870. }
  9871. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9872. ResponseHandler response_handler,
  9873. ContentReceiver content_receiver,
  9874. DownloadProgress progress) {
  9875. Request req;
  9876. req.method = "GET";
  9877. req.path = path;
  9878. req.headers = headers;
  9879. req.response_handler = std::move(response_handler);
  9880. req.content_receiver =
  9881. [content_receiver](const char *data, size_t data_length,
  9882. size_t /*offset*/, size_t /*total_length*/) {
  9883. return content_receiver(data, data_length);
  9884. };
  9885. req.download_progress = std::move(progress);
  9886. if (max_timeout_msec_ > 0) {
  9887. req.start_time_ = std::chrono::steady_clock::now();
  9888. }
  9889. return send_(std::move(req));
  9890. }
  9891. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9892. const Headers &headers,
  9893. ContentReceiver content_receiver,
  9894. DownloadProgress progress) {
  9895. return Get(path, params, headers, nullptr, std::move(content_receiver),
  9896. std::move(progress));
  9897. }
  9898. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9899. const Headers &headers,
  9900. ResponseHandler response_handler,
  9901. ContentReceiver content_receiver,
  9902. DownloadProgress progress) {
  9903. if (params.empty()) {
  9904. return Get(path, headers, std::move(response_handler),
  9905. std::move(content_receiver), std::move(progress));
  9906. }
  9907. std::string path_with_query = append_query_params(path, params);
  9908. return Get(path_with_query, headers, std::move(response_handler),
  9909. std::move(content_receiver), std::move(progress));
  9910. }
  9911. inline Result ClientImpl::Head(const std::string &path) {
  9912. return Head(path, Headers());
  9913. }
  9914. inline Result ClientImpl::Head(const std::string &path,
  9915. const Headers &headers) {
  9916. Request req;
  9917. req.method = "HEAD";
  9918. req.headers = headers;
  9919. req.path = path;
  9920. if (max_timeout_msec_ > 0) {
  9921. req.start_time_ = std::chrono::steady_clock::now();
  9922. }
  9923. return send_(std::move(req));
  9924. }
  9925. inline Result ClientImpl::Post(const std::string &path) {
  9926. return Post(path, std::string(), std::string());
  9927. }
  9928. inline Result ClientImpl::Post(const std::string &path,
  9929. const Headers &headers) {
  9930. return Post(path, headers, nullptr, 0, std::string());
  9931. }
  9932. inline Result ClientImpl::Post(const std::string &path, const char *body,
  9933. size_t content_length,
  9934. const std::string &content_type,
  9935. UploadProgress progress) {
  9936. return Post(path, Headers(), body, content_length, content_type, progress);
  9937. }
  9938. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  9939. const std::string &content_type,
  9940. UploadProgress progress) {
  9941. return Post(path, Headers(), body, content_type, progress);
  9942. }
  9943. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  9944. return Post(path, Headers(), params);
  9945. }
  9946. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9947. ContentProvider content_provider,
  9948. const std::string &content_type,
  9949. UploadProgress progress) {
  9950. return Post(path, Headers(), content_length, std::move(content_provider),
  9951. content_type, progress);
  9952. }
  9953. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9954. ContentProvider content_provider,
  9955. const std::string &content_type,
  9956. ContentReceiver content_receiver,
  9957. UploadProgress progress) {
  9958. return Post(path, Headers(), content_length, std::move(content_provider),
  9959. content_type, std::move(content_receiver), progress);
  9960. }
  9961. inline Result ClientImpl::Post(const std::string &path,
  9962. ContentProviderWithoutLength content_provider,
  9963. const std::string &content_type,
  9964. UploadProgress progress) {
  9965. return Post(path, Headers(), std::move(content_provider), content_type,
  9966. progress);
  9967. }
  9968. inline Result ClientImpl::Post(const std::string &path,
  9969. ContentProviderWithoutLength content_provider,
  9970. const std::string &content_type,
  9971. ContentReceiver content_receiver,
  9972. UploadProgress progress) {
  9973. return Post(path, Headers(), std::move(content_provider), content_type,
  9974. std::move(content_receiver), progress);
  9975. }
  9976. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9977. const Params &params) {
  9978. auto query = detail::params_to_query_str(params);
  9979. return Post(path, headers, query, "application/x-www-form-urlencoded");
  9980. }
  9981. inline Result ClientImpl::Post(const std::string &path,
  9982. const UploadFormDataItems &items,
  9983. UploadProgress progress) {
  9984. return Post(path, Headers(), items, progress);
  9985. }
  9986. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9987. const UploadFormDataItems &items,
  9988. UploadProgress progress) {
  9989. const auto &boundary = detail::make_multipart_data_boundary();
  9990. const auto &content_type =
  9991. detail::serialize_multipart_formdata_get_content_type(boundary);
  9992. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9993. return Post(path, headers, body, content_type, progress);
  9994. }
  9995. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9996. const UploadFormDataItems &items,
  9997. const std::string &boundary,
  9998. UploadProgress progress) {
  9999. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10000. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10001. }
  10002. const auto &content_type =
  10003. detail::serialize_multipart_formdata_get_content_type(boundary);
  10004. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10005. return Post(path, headers, body, content_type, progress);
  10006. }
  10007. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10008. const char *body, size_t content_length,
  10009. const std::string &content_type,
  10010. UploadProgress progress) {
  10011. return send_with_content_provider_and_receiver(
  10012. "POST", path, headers, body, content_length, nullptr, nullptr,
  10013. content_type, nullptr, progress);
  10014. }
  10015. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10016. const std::string &body,
  10017. const std::string &content_type,
  10018. UploadProgress progress) {
  10019. return send_with_content_provider_and_receiver(
  10020. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  10021. content_type, nullptr, progress);
  10022. }
  10023. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10024. size_t content_length,
  10025. ContentProvider content_provider,
  10026. const std::string &content_type,
  10027. UploadProgress progress) {
  10028. return send_with_content_provider_and_receiver(
  10029. "POST", path, headers, nullptr, content_length,
  10030. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10031. }
  10032. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10033. size_t content_length,
  10034. ContentProvider content_provider,
  10035. const std::string &content_type,
  10036. ContentReceiver content_receiver,
  10037. DownloadProgress progress) {
  10038. return send_with_content_provider_and_receiver(
  10039. "POST", path, headers, nullptr, content_length,
  10040. std::move(content_provider), nullptr, content_type,
  10041. std::move(content_receiver), std::move(progress));
  10042. }
  10043. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10044. ContentProviderWithoutLength content_provider,
  10045. const std::string &content_type,
  10046. UploadProgress progress) {
  10047. return send_with_content_provider_and_receiver(
  10048. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10049. content_type, nullptr, progress);
  10050. }
  10051. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10052. ContentProviderWithoutLength content_provider,
  10053. const std::string &content_type,
  10054. ContentReceiver content_receiver,
  10055. DownloadProgress progress) {
  10056. return send_with_content_provider_and_receiver(
  10057. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10058. content_type, std::move(content_receiver), std::move(progress));
  10059. }
  10060. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10061. const UploadFormDataItems &items,
  10062. const FormDataProviderItems &provider_items,
  10063. UploadProgress progress) {
  10064. const auto &boundary = detail::make_multipart_data_boundary();
  10065. const auto &content_type =
  10066. detail::serialize_multipart_formdata_get_content_type(boundary);
  10067. return send_with_content_provider_and_receiver(
  10068. "POST", path, headers, nullptr, 0, nullptr,
  10069. get_multipart_content_provider(boundary, items, provider_items),
  10070. content_type, nullptr, progress);
  10071. }
  10072. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10073. const std::string &body,
  10074. const std::string &content_type,
  10075. ContentReceiver content_receiver,
  10076. DownloadProgress progress) {
  10077. Request req;
  10078. req.method = "POST";
  10079. req.path = path;
  10080. req.headers = headers;
  10081. req.body = body;
  10082. req.content_receiver =
  10083. [content_receiver](const char *data, size_t data_length,
  10084. size_t /*offset*/, size_t /*total_length*/) {
  10085. return content_receiver(data, data_length);
  10086. };
  10087. req.download_progress = std::move(progress);
  10088. if (max_timeout_msec_ > 0) {
  10089. req.start_time_ = std::chrono::steady_clock::now();
  10090. }
  10091. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10092. return send_(std::move(req));
  10093. }
  10094. inline Result ClientImpl::Put(const std::string &path) {
  10095. return Put(path, std::string(), std::string());
  10096. }
  10097. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  10098. return Put(path, headers, nullptr, 0, std::string());
  10099. }
  10100. inline Result ClientImpl::Put(const std::string &path, const char *body,
  10101. size_t content_length,
  10102. const std::string &content_type,
  10103. UploadProgress progress) {
  10104. return Put(path, Headers(), body, content_length, content_type, progress);
  10105. }
  10106. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  10107. const std::string &content_type,
  10108. UploadProgress progress) {
  10109. return Put(path, Headers(), body, content_type, progress);
  10110. }
  10111. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  10112. return Put(path, Headers(), params);
  10113. }
  10114. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10115. ContentProvider content_provider,
  10116. const std::string &content_type,
  10117. UploadProgress progress) {
  10118. return Put(path, Headers(), content_length, std::move(content_provider),
  10119. content_type, progress);
  10120. }
  10121. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10122. ContentProvider content_provider,
  10123. const std::string &content_type,
  10124. ContentReceiver content_receiver,
  10125. UploadProgress progress) {
  10126. return Put(path, Headers(), content_length, std::move(content_provider),
  10127. content_type, std::move(content_receiver), progress);
  10128. }
  10129. inline Result ClientImpl::Put(const std::string &path,
  10130. ContentProviderWithoutLength content_provider,
  10131. const std::string &content_type,
  10132. UploadProgress progress) {
  10133. return Put(path, Headers(), std::move(content_provider), content_type,
  10134. progress);
  10135. }
  10136. inline Result ClientImpl::Put(const std::string &path,
  10137. ContentProviderWithoutLength content_provider,
  10138. const std::string &content_type,
  10139. ContentReceiver content_receiver,
  10140. UploadProgress progress) {
  10141. return Put(path, Headers(), std::move(content_provider), content_type,
  10142. std::move(content_receiver), progress);
  10143. }
  10144. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10145. const Params &params) {
  10146. auto query = detail::params_to_query_str(params);
  10147. return Put(path, headers, query, "application/x-www-form-urlencoded");
  10148. }
  10149. inline Result ClientImpl::Put(const std::string &path,
  10150. const UploadFormDataItems &items,
  10151. UploadProgress progress) {
  10152. return Put(path, Headers(), items, progress);
  10153. }
  10154. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10155. const UploadFormDataItems &items,
  10156. UploadProgress progress) {
  10157. const auto &boundary = detail::make_multipart_data_boundary();
  10158. const auto &content_type =
  10159. detail::serialize_multipart_formdata_get_content_type(boundary);
  10160. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10161. return Put(path, headers, body, content_type, progress);
  10162. }
  10163. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10164. const UploadFormDataItems &items,
  10165. const std::string &boundary,
  10166. UploadProgress progress) {
  10167. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10168. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10169. }
  10170. const auto &content_type =
  10171. detail::serialize_multipart_formdata_get_content_type(boundary);
  10172. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10173. return Put(path, headers, body, content_type, progress);
  10174. }
  10175. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10176. const char *body, size_t content_length,
  10177. const std::string &content_type,
  10178. UploadProgress progress) {
  10179. return send_with_content_provider_and_receiver(
  10180. "PUT", path, headers, body, content_length, nullptr, nullptr,
  10181. content_type, nullptr, progress);
  10182. }
  10183. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10184. const std::string &body,
  10185. const std::string &content_type,
  10186. UploadProgress progress) {
  10187. return send_with_content_provider_and_receiver(
  10188. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  10189. content_type, nullptr, progress);
  10190. }
  10191. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10192. size_t content_length,
  10193. ContentProvider content_provider,
  10194. const std::string &content_type,
  10195. UploadProgress progress) {
  10196. return send_with_content_provider_and_receiver(
  10197. "PUT", path, headers, nullptr, content_length,
  10198. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10199. }
  10200. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10201. size_t content_length,
  10202. ContentProvider content_provider,
  10203. const std::string &content_type,
  10204. ContentReceiver content_receiver,
  10205. UploadProgress progress) {
  10206. return send_with_content_provider_and_receiver(
  10207. "PUT", path, headers, nullptr, content_length,
  10208. std::move(content_provider), nullptr, content_type,
  10209. std::move(content_receiver), progress);
  10210. }
  10211. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10212. ContentProviderWithoutLength content_provider,
  10213. const std::string &content_type,
  10214. UploadProgress progress) {
  10215. return send_with_content_provider_and_receiver(
  10216. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10217. content_type, nullptr, progress);
  10218. }
  10219. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10220. ContentProviderWithoutLength content_provider,
  10221. const std::string &content_type,
  10222. ContentReceiver content_receiver,
  10223. UploadProgress progress) {
  10224. return send_with_content_provider_and_receiver(
  10225. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10226. content_type, std::move(content_receiver), progress);
  10227. }
  10228. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10229. const UploadFormDataItems &items,
  10230. const FormDataProviderItems &provider_items,
  10231. UploadProgress progress) {
  10232. const auto &boundary = detail::make_multipart_data_boundary();
  10233. const auto &content_type =
  10234. detail::serialize_multipart_formdata_get_content_type(boundary);
  10235. return send_with_content_provider_and_receiver(
  10236. "PUT", path, headers, nullptr, 0, nullptr,
  10237. get_multipart_content_provider(boundary, items, provider_items),
  10238. content_type, nullptr, progress);
  10239. }
  10240. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10241. const std::string &body,
  10242. const std::string &content_type,
  10243. ContentReceiver content_receiver,
  10244. DownloadProgress progress) {
  10245. Request req;
  10246. req.method = "PUT";
  10247. req.path = path;
  10248. req.headers = headers;
  10249. req.body = body;
  10250. req.content_receiver =
  10251. [content_receiver](const char *data, size_t data_length,
  10252. size_t /*offset*/, size_t /*total_length*/) {
  10253. return content_receiver(data, data_length);
  10254. };
  10255. req.download_progress = std::move(progress);
  10256. if (max_timeout_msec_ > 0) {
  10257. req.start_time_ = std::chrono::steady_clock::now();
  10258. }
  10259. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10260. return send_(std::move(req));
  10261. }
  10262. inline Result ClientImpl::Patch(const std::string &path) {
  10263. return Patch(path, std::string(), std::string());
  10264. }
  10265. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10266. UploadProgress progress) {
  10267. return Patch(path, headers, nullptr, 0, std::string(), progress);
  10268. }
  10269. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  10270. size_t content_length,
  10271. const std::string &content_type,
  10272. UploadProgress progress) {
  10273. return Patch(path, Headers(), body, content_length, content_type, progress);
  10274. }
  10275. inline Result ClientImpl::Patch(const std::string &path,
  10276. const std::string &body,
  10277. const std::string &content_type,
  10278. UploadProgress progress) {
  10279. return Patch(path, Headers(), body, content_type, progress);
  10280. }
  10281. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  10282. return Patch(path, Headers(), params);
  10283. }
  10284. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10285. ContentProvider content_provider,
  10286. const std::string &content_type,
  10287. UploadProgress progress) {
  10288. return Patch(path, Headers(), content_length, std::move(content_provider),
  10289. content_type, progress);
  10290. }
  10291. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10292. ContentProvider content_provider,
  10293. const std::string &content_type,
  10294. ContentReceiver content_receiver,
  10295. UploadProgress progress) {
  10296. return Patch(path, Headers(), content_length, std::move(content_provider),
  10297. content_type, std::move(content_receiver), progress);
  10298. }
  10299. inline Result ClientImpl::Patch(const std::string &path,
  10300. ContentProviderWithoutLength content_provider,
  10301. const std::string &content_type,
  10302. UploadProgress progress) {
  10303. return Patch(path, Headers(), std::move(content_provider), content_type,
  10304. progress);
  10305. }
  10306. inline Result ClientImpl::Patch(const std::string &path,
  10307. ContentProviderWithoutLength content_provider,
  10308. const std::string &content_type,
  10309. ContentReceiver content_receiver,
  10310. UploadProgress progress) {
  10311. return Patch(path, Headers(), std::move(content_provider), content_type,
  10312. std::move(content_receiver), progress);
  10313. }
  10314. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10315. const Params &params) {
  10316. auto query = detail::params_to_query_str(params);
  10317. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  10318. }
  10319. inline Result ClientImpl::Patch(const std::string &path,
  10320. const UploadFormDataItems &items,
  10321. UploadProgress progress) {
  10322. return Patch(path, Headers(), items, progress);
  10323. }
  10324. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10325. const UploadFormDataItems &items,
  10326. UploadProgress progress) {
  10327. const auto &boundary = detail::make_multipart_data_boundary();
  10328. const auto &content_type =
  10329. detail::serialize_multipart_formdata_get_content_type(boundary);
  10330. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10331. return Patch(path, headers, body, content_type, progress);
  10332. }
  10333. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10334. const UploadFormDataItems &items,
  10335. const std::string &boundary,
  10336. UploadProgress progress) {
  10337. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10338. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10339. }
  10340. const auto &content_type =
  10341. detail::serialize_multipart_formdata_get_content_type(boundary);
  10342. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10343. return Patch(path, headers, body, content_type, progress);
  10344. }
  10345. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10346. const char *body, size_t content_length,
  10347. const std::string &content_type,
  10348. UploadProgress progress) {
  10349. return send_with_content_provider_and_receiver(
  10350. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  10351. content_type, nullptr, progress);
  10352. }
  10353. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10354. const std::string &body,
  10355. const std::string &content_type,
  10356. UploadProgress progress) {
  10357. return send_with_content_provider_and_receiver(
  10358. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  10359. content_type, nullptr, progress);
  10360. }
  10361. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10362. size_t content_length,
  10363. ContentProvider content_provider,
  10364. const std::string &content_type,
  10365. UploadProgress progress) {
  10366. return send_with_content_provider_and_receiver(
  10367. "PATCH", path, headers, nullptr, content_length,
  10368. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10369. }
  10370. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10371. size_t content_length,
  10372. ContentProvider content_provider,
  10373. const std::string &content_type,
  10374. ContentReceiver content_receiver,
  10375. UploadProgress progress) {
  10376. return send_with_content_provider_and_receiver(
  10377. "PATCH", path, headers, nullptr, content_length,
  10378. std::move(content_provider), nullptr, content_type,
  10379. std::move(content_receiver), progress);
  10380. }
  10381. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10382. ContentProviderWithoutLength content_provider,
  10383. const std::string &content_type,
  10384. UploadProgress progress) {
  10385. return send_with_content_provider_and_receiver(
  10386. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10387. content_type, nullptr, progress);
  10388. }
  10389. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10390. ContentProviderWithoutLength content_provider,
  10391. const std::string &content_type,
  10392. ContentReceiver content_receiver,
  10393. UploadProgress progress) {
  10394. return send_with_content_provider_and_receiver(
  10395. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10396. content_type, std::move(content_receiver), progress);
  10397. }
  10398. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10399. const UploadFormDataItems &items,
  10400. const FormDataProviderItems &provider_items,
  10401. UploadProgress progress) {
  10402. const auto &boundary = detail::make_multipart_data_boundary();
  10403. const auto &content_type =
  10404. detail::serialize_multipart_formdata_get_content_type(boundary);
  10405. return send_with_content_provider_and_receiver(
  10406. "PATCH", path, headers, nullptr, 0, nullptr,
  10407. get_multipart_content_provider(boundary, items, provider_items),
  10408. content_type, nullptr, progress);
  10409. }
  10410. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10411. const std::string &body,
  10412. const std::string &content_type,
  10413. ContentReceiver content_receiver,
  10414. DownloadProgress progress) {
  10415. Request req;
  10416. req.method = "PATCH";
  10417. req.path = path;
  10418. req.headers = headers;
  10419. req.body = body;
  10420. req.content_receiver =
  10421. [content_receiver](const char *data, size_t data_length,
  10422. size_t /*offset*/, size_t /*total_length*/) {
  10423. return content_receiver(data, data_length);
  10424. };
  10425. req.download_progress = std::move(progress);
  10426. if (max_timeout_msec_ > 0) {
  10427. req.start_time_ = std::chrono::steady_clock::now();
  10428. }
  10429. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10430. return send_(std::move(req));
  10431. }
  10432. inline Result ClientImpl::Delete(const std::string &path,
  10433. DownloadProgress progress) {
  10434. return Delete(path, Headers(), std::string(), std::string(), progress);
  10435. }
  10436. inline Result ClientImpl::Delete(const std::string &path,
  10437. const Headers &headers,
  10438. DownloadProgress progress) {
  10439. return Delete(path, headers, std::string(), std::string(), progress);
  10440. }
  10441. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  10442. size_t content_length,
  10443. const std::string &content_type,
  10444. DownloadProgress progress) {
  10445. return Delete(path, Headers(), body, content_length, content_type, progress);
  10446. }
  10447. inline Result ClientImpl::Delete(const std::string &path,
  10448. const std::string &body,
  10449. const std::string &content_type,
  10450. DownloadProgress progress) {
  10451. return Delete(path, Headers(), body.data(), body.size(), content_type,
  10452. progress);
  10453. }
  10454. inline Result ClientImpl::Delete(const std::string &path,
  10455. const Headers &headers,
  10456. const std::string &body,
  10457. const std::string &content_type,
  10458. DownloadProgress progress) {
  10459. return Delete(path, headers, body.data(), body.size(), content_type,
  10460. progress);
  10461. }
  10462. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  10463. DownloadProgress progress) {
  10464. return Delete(path, Headers(), params, progress);
  10465. }
  10466. inline Result ClientImpl::Delete(const std::string &path,
  10467. const Headers &headers, const Params &params,
  10468. DownloadProgress progress) {
  10469. auto query = detail::params_to_query_str(params);
  10470. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  10471. progress);
  10472. }
  10473. inline Result ClientImpl::Delete(const std::string &path,
  10474. const Headers &headers, const char *body,
  10475. size_t content_length,
  10476. const std::string &content_type,
  10477. DownloadProgress progress) {
  10478. Request req;
  10479. req.method = "DELETE";
  10480. req.headers = headers;
  10481. req.path = path;
  10482. req.download_progress = std::move(progress);
  10483. if (max_timeout_msec_ > 0) {
  10484. req.start_time_ = std::chrono::steady_clock::now();
  10485. }
  10486. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10487. req.body.assign(body, content_length);
  10488. return send_(std::move(req));
  10489. }
  10490. inline Result ClientImpl::Options(const std::string &path) {
  10491. return Options(path, Headers());
  10492. }
  10493. inline Result ClientImpl::Options(const std::string &path,
  10494. const Headers &headers) {
  10495. Request req;
  10496. req.method = "OPTIONS";
  10497. req.headers = headers;
  10498. req.path = path;
  10499. if (max_timeout_msec_ > 0) {
  10500. req.start_time_ = std::chrono::steady_clock::now();
  10501. }
  10502. return send_(std::move(req));
  10503. }
  10504. inline void ClientImpl::stop() {
  10505. std::lock_guard<std::mutex> guard(socket_mutex_);
  10506. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  10507. // do is to shutdown_socket, so that threads using this socket suddenly
  10508. // discover they can't read/write any more and error out. Everything else
  10509. // (closing the socket, shutting ssl down) is unsafe because these actions
  10510. // are not thread-safe.
  10511. if (socket_requests_in_flight_ > 0) {
  10512. shutdown_socket(socket_);
  10513. // Aside from that, we set a flag for the socket to be closed when we're
  10514. // done.
  10515. socket_should_be_closed_when_request_is_done_ = true;
  10516. return;
  10517. }
  10518. // Otherwise, still holding the mutex, we can shut everything down ourselves
  10519. shutdown_ssl(socket_, true);
  10520. shutdown_socket(socket_);
  10521. close_socket(socket_);
  10522. }
  10523. inline std::string ClientImpl::host() const { return host_; }
  10524. inline int ClientImpl::port() const { return port_; }
  10525. inline size_t ClientImpl::is_socket_open() const {
  10526. std::lock_guard<std::mutex> guard(socket_mutex_);
  10527. return socket_.is_open();
  10528. }
  10529. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  10530. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  10531. connection_timeout_sec_ = sec;
  10532. connection_timeout_usec_ = usec;
  10533. }
  10534. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  10535. read_timeout_sec_ = sec;
  10536. read_timeout_usec_ = usec;
  10537. }
  10538. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  10539. write_timeout_sec_ = sec;
  10540. write_timeout_usec_ = usec;
  10541. }
  10542. inline void ClientImpl::set_max_timeout(time_t msec) {
  10543. max_timeout_msec_ = msec;
  10544. }
  10545. inline void ClientImpl::set_basic_auth(const std::string &username,
  10546. const std::string &password) {
  10547. basic_auth_username_ = username;
  10548. basic_auth_password_ = password;
  10549. }
  10550. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  10551. bearer_token_auth_token_ = token;
  10552. }
  10553. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  10554. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  10555. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  10556. inline void
  10557. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  10558. addr_map_ = std::move(addr_map);
  10559. }
  10560. inline void ClientImpl::set_default_headers(Headers headers) {
  10561. default_headers_ = std::move(headers);
  10562. }
  10563. inline void ClientImpl::set_header_writer(
  10564. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  10565. header_writer_ = writer;
  10566. }
  10567. inline void ClientImpl::set_address_family(int family) {
  10568. address_family_ = family;
  10569. }
  10570. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  10571. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  10572. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  10573. socket_options_ = std::move(socket_options);
  10574. }
  10575. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  10576. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  10577. inline void ClientImpl::set_interface(const std::string &intf) {
  10578. interface_ = intf;
  10579. }
  10580. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  10581. proxy_host_ = host;
  10582. proxy_port_ = port;
  10583. }
  10584. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  10585. const std::string &password) {
  10586. proxy_basic_auth_username_ = username;
  10587. proxy_basic_auth_password_ = password;
  10588. }
  10589. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  10590. proxy_bearer_token_auth_token_ = token;
  10591. }
  10592. #ifdef CPPHTTPLIB_SSL_ENABLED
  10593. inline void ClientImpl::set_digest_auth(const std::string &username,
  10594. const std::string &password) {
  10595. digest_auth_username_ = username;
  10596. digest_auth_password_ = password;
  10597. }
  10598. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  10599. const std::string &ca_cert_dir_path) {
  10600. ca_cert_file_path_ = ca_cert_file_path;
  10601. ca_cert_dir_path_ = ca_cert_dir_path;
  10602. }
  10603. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  10604. const std::string &password) {
  10605. proxy_digest_auth_username_ = username;
  10606. proxy_digest_auth_password_ = password;
  10607. }
  10608. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  10609. server_certificate_verification_ = enabled;
  10610. }
  10611. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  10612. server_hostname_verification_ = enabled;
  10613. }
  10614. #endif
  10615. // ClientImpl::set_ca_cert_store is defined after TLS namespace (uses helpers)
  10616. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10617. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  10618. std::size_t size) const {
  10619. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  10620. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  10621. if (!mem) { return nullptr; }
  10622. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  10623. if (!inf) { return nullptr; }
  10624. auto cts = X509_STORE_new();
  10625. if (cts) {
  10626. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  10627. auto itmp = sk_X509_INFO_value(inf, i);
  10628. if (!itmp) { continue; }
  10629. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  10630. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  10631. }
  10632. }
  10633. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  10634. return cts;
  10635. }
  10636. inline void ClientImpl::set_server_certificate_verifier(
  10637. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  10638. server_certificate_verifier_ = verifier;
  10639. }
  10640. #endif
  10641. inline void ClientImpl::set_logger(Logger logger) {
  10642. logger_ = std::move(logger);
  10643. }
  10644. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  10645. error_logger_ = std::move(error_logger);
  10646. }
  10647. /*
  10648. * OpenSSL Backend Implementation
  10649. */
  10650. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10651. namespace crypto {
  10652. inline size_t hash_size(HashAlgorithm algo) {
  10653. switch (algo) {
  10654. case HashAlgorithm::MD5: return 16;
  10655. case HashAlgorithm::SHA1: return 20;
  10656. case HashAlgorithm::SHA256: return 32;
  10657. case HashAlgorithm::SHA384: return 48;
  10658. case HashAlgorithm::SHA512: return 64;
  10659. default: return 0;
  10660. }
  10661. }
  10662. inline const EVP_MD *get_evp_md(HashAlgorithm algo) {
  10663. switch (algo) {
  10664. case HashAlgorithm::MD5: return EVP_md5();
  10665. case HashAlgorithm::SHA1: return EVP_sha1();
  10666. case HashAlgorithm::SHA256: return EVP_sha256();
  10667. case HashAlgorithm::SHA384: return EVP_sha384();
  10668. case HashAlgorithm::SHA512: return EVP_sha512();
  10669. default: return nullptr;
  10670. }
  10671. }
  10672. inline bool hash_raw(HashAlgorithm algo, const void *data, size_t len,
  10673. std::vector<uint8_t> &digest) {
  10674. auto md = get_evp_md(algo);
  10675. if (!md) { return false; }
  10676. auto ctx = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  10677. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  10678. if (!ctx) { return false; }
  10679. unsigned int hash_len = 0;
  10680. digest.resize(EVP_MAX_MD_SIZE);
  10681. if (EVP_DigestInit_ex(ctx.get(), md, nullptr) != 1) { return false; }
  10682. if (EVP_DigestUpdate(ctx.get(), data, len) != 1) { return false; }
  10683. if (EVP_DigestFinal_ex(ctx.get(), digest.data(), &hash_len) != 1) {
  10684. return false;
  10685. }
  10686. digest.resize(hash_len);
  10687. return true;
  10688. }
  10689. inline std::string hash(HashAlgorithm algo, const void *data, size_t len) {
  10690. std::vector<uint8_t> digest;
  10691. if (!hash_raw(algo, data, len, digest)) { return ""; }
  10692. std::stringstream ss;
  10693. for (auto byte : digest) {
  10694. ss << std::hex << std::setw(2) << std::setfill('0')
  10695. << static_cast<unsigned int>(byte);
  10696. }
  10697. return ss.str();
  10698. }
  10699. inline std::string hash(HashAlgorithm algo, const std::string &data) {
  10700. return hash(algo, data.c_str(), data.size());
  10701. }
  10702. } // namespace crypto
  10703. namespace tls {
  10704. // OpenSSL-specific helpers for converting native types to PEM
  10705. inline std::string x509_to_pem(X509 *cert) {
  10706. if (!cert) return {};
  10707. BIO *bio = BIO_new(BIO_s_mem());
  10708. if (!bio) return {};
  10709. if (PEM_write_bio_X509(bio, cert) != 1) {
  10710. BIO_free(bio);
  10711. return {};
  10712. }
  10713. char *data = nullptr;
  10714. long len = BIO_get_mem_data(bio, &data);
  10715. std::string pem(data, static_cast<size_t>(len));
  10716. BIO_free(bio);
  10717. return pem;
  10718. }
  10719. inline std::string evp_pkey_to_pem(EVP_PKEY *key) {
  10720. if (!key) return {};
  10721. BIO *bio = BIO_new(BIO_s_mem());
  10722. if (!bio) return {};
  10723. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr,
  10724. nullptr) != 1) {
  10725. BIO_free(bio);
  10726. return {};
  10727. }
  10728. char *data = nullptr;
  10729. long len = BIO_get_mem_data(bio, &data);
  10730. std::string pem(data, static_cast<size_t>(len));
  10731. BIO_free(bio);
  10732. return pem;
  10733. }
  10734. inline std::string x509_store_to_pem(X509_STORE *store) {
  10735. if (!store) return {};
  10736. std::string pem;
  10737. auto objs = X509_STORE_get0_objects(store);
  10738. if (!objs) return {};
  10739. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  10740. auto obj = sk_X509_OBJECT_value(objs, i);
  10741. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  10742. auto cert = X509_OBJECT_get0_X509(obj);
  10743. if (cert) { pem += x509_to_pem(cert); }
  10744. }
  10745. }
  10746. return pem;
  10747. }
  10748. // Helper to map OpenSSL SSL_get_error to ErrorCode
  10749. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  10750. switch (ssl_error) {
  10751. case SSL_ERROR_NONE: return ErrorCode::Success;
  10752. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  10753. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  10754. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  10755. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  10756. case SSL_ERROR_SSL:
  10757. default: return ErrorCode::Fatal;
  10758. }
  10759. }
  10760. inline bool tls_global_init() {
  10761. // OpenSSL 3.0+: OPENSSL_init_ssl() is called automatically
  10762. return OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS |
  10763. OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  10764. nullptr) == 1;
  10765. }
  10766. inline void tls_global_cleanup() {
  10767. // OpenSSL 3.0+: cleanup is automatic
  10768. }
  10769. inline tls_ctx_t tls_create_client_context() {
  10770. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  10771. if (ctx) {
  10772. // Disable auto-retry to properly handle non-blocking I/O
  10773. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  10774. // Set minimum TLS version
  10775. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  10776. }
  10777. return static_cast<tls_ctx_t>(ctx);
  10778. }
  10779. inline void tls_free_context(tls_ctx_t ctx) {
  10780. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  10781. }
  10782. inline bool tls_set_min_version(tls_ctx_t ctx, int version) {
  10783. if (!ctx) return false;
  10784. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx), version) ==
  10785. 1;
  10786. }
  10787. inline bool tls_load_ca_pem(tls_ctx_t ctx, const char *pem, size_t len) {
  10788. if (!ctx || !pem || len == 0) return false;
  10789. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10790. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  10791. if (!store) return false;
  10792. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  10793. if (!bio) return false;
  10794. bool ok = true;
  10795. X509 *cert = nullptr;
  10796. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  10797. nullptr) {
  10798. if (X509_STORE_add_cert(store, cert) != 1) {
  10799. // Ignore duplicate errors
  10800. auto err = ERR_peek_last_error();
  10801. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  10802. ok = false;
  10803. }
  10804. }
  10805. X509_free(cert);
  10806. if (!ok) break;
  10807. }
  10808. BIO_free(bio);
  10809. // Clear any "no more certificates" errors
  10810. ERR_clear_error();
  10811. return ok;
  10812. }
  10813. inline bool tls_load_ca_file(tls_ctx_t ctx, const char *file_path) {
  10814. if (!ctx || !file_path) return false;
  10815. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  10816. nullptr) == 1;
  10817. }
  10818. inline bool tls_load_ca_dir(tls_ctx_t ctx, const char *dir_path) {
  10819. if (!ctx || !dir_path) return false;
  10820. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  10821. dir_path) == 1;
  10822. }
  10823. inline bool tls_load_system_certs(tls_ctx_t ctx) {
  10824. if (!ctx) return false;
  10825. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10826. #ifdef _WIN32
  10827. // Windows: Load from system certificate store
  10828. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  10829. if (!store) return false;
  10830. auto hStore = CertOpenSystemStoreW(NULL, L"ROOT");
  10831. if (!hStore) return false;
  10832. bool loaded_any = false;
  10833. PCCERT_CONTEXT pContext = nullptr;
  10834. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  10835. nullptr) {
  10836. const unsigned char *data = pContext->pbCertEncoded;
  10837. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  10838. if (x509) {
  10839. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  10840. X509_free(x509);
  10841. }
  10842. }
  10843. CertCloseStore(hStore, 0);
  10844. return loaded_any;
  10845. #elif defined(__APPLE__)
  10846. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  10847. // macOS: Load from Keychain
  10848. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  10849. if (!store) return false;
  10850. CFArrayRef certs = nullptr;
  10851. if (SecTrustCopyAnchorCertificates(&certs) != errSecSuccess || !certs) {
  10852. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10853. }
  10854. bool loaded_any = false;
  10855. auto count = CFArrayGetCount(certs);
  10856. for (CFIndex i = 0; i < count; i++) {
  10857. auto cert = reinterpret_cast<SecCertificateRef>(
  10858. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  10859. CFDataRef der = SecCertificateCopyData(cert);
  10860. if (der) {
  10861. const unsigned char *data = CFDataGetBytePtr(der);
  10862. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  10863. if (x509) {
  10864. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  10865. X509_free(x509);
  10866. }
  10867. CFRelease(der);
  10868. }
  10869. }
  10870. CFRelease(certs);
  10871. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10872. #else
  10873. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10874. #endif
  10875. #else
  10876. // Other Unix: use default verify paths
  10877. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  10878. #endif
  10879. }
  10880. inline bool tls_set_client_cert_pem(tls_ctx_t ctx, const char *cert,
  10881. const char *key, const char *password) {
  10882. if (!ctx || !cert || !key) return false;
  10883. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10884. // Load certificate
  10885. auto cert_bio = BIO_new_mem_buf(cert, -1);
  10886. if (!cert_bio) return false;
  10887. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  10888. BIO_free(cert_bio);
  10889. if (!x509) return false;
  10890. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  10891. X509_free(x509);
  10892. if (!cert_ok) return false;
  10893. // Load private key
  10894. auto key_bio = BIO_new_mem_buf(key, -1);
  10895. if (!key_bio) return false;
  10896. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  10897. password ? const_cast<char *>(password)
  10898. : nullptr);
  10899. BIO_free(key_bio);
  10900. if (!pkey) return false;
  10901. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  10902. EVP_PKEY_free(pkey);
  10903. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  10904. }
  10905. inline bool tls_set_client_cert_file(tls_ctx_t ctx, const char *cert_path,
  10906. const char *key_path,
  10907. const char *password) {
  10908. if (!ctx || !cert_path || !key_path) return false;
  10909. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10910. if (password && password[0] != '\0') {
  10911. SSL_CTX_set_default_passwd_cb_userdata(
  10912. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  10913. }
  10914. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  10915. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  10916. }
  10917. inline tls_ctx_t tls_create_server_context() {
  10918. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  10919. if (ctx) {
  10920. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  10921. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  10922. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  10923. }
  10924. return static_cast<tls_ctx_t>(ctx);
  10925. }
  10926. inline bool tls_set_server_cert_pem(tls_ctx_t ctx, const char *cert,
  10927. const char *key, const char *password) {
  10928. // Same implementation as client cert
  10929. return tls_set_client_cert_pem(ctx, cert, key, password);
  10930. }
  10931. inline bool tls_set_server_cert_file(tls_ctx_t ctx, const char *cert_path,
  10932. const char *key_path,
  10933. const char *password) {
  10934. // Same implementation as client cert file
  10935. return tls_set_client_cert_file(ctx, cert_path, key_path, password);
  10936. }
  10937. inline bool tls_set_client_ca_file(tls_ctx_t ctx, const char *ca_file,
  10938. const char *ca_dir) {
  10939. if (!ctx) return false;
  10940. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10941. if (ca_file || ca_dir) {
  10942. if (SSL_CTX_load_verify_locations(ssl_ctx, ca_file, ca_dir) != 1) {
  10943. return false;
  10944. }
  10945. }
  10946. // Set CA list for client certificate request
  10947. if (ca_file) {
  10948. auto list = SSL_load_client_CA_file(ca_file);
  10949. if (list) { SSL_CTX_set_client_CA_list(ssl_ctx, list); }
  10950. }
  10951. return true;
  10952. }
  10953. inline void tls_set_verify_client(tls_ctx_t ctx, bool require) {
  10954. if (!ctx) return;
  10955. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  10956. require
  10957. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  10958. : SSL_VERIFY_NONE,
  10959. nullptr);
  10960. }
  10961. inline tls_session_t tls_create_session(tls_ctx_t ctx, socket_t sock) {
  10962. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  10963. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  10964. SSL *ssl = SSL_new(ssl_ctx);
  10965. if (!ssl) return nullptr;
  10966. // Disable auto-retry for proper non-blocking I/O handling
  10967. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  10968. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  10969. if (!bio) {
  10970. SSL_free(ssl);
  10971. return nullptr;
  10972. }
  10973. SSL_set_bio(ssl, bio, bio);
  10974. return static_cast<tls_session_t>(ssl);
  10975. }
  10976. inline void tls_free_session(tls_session_t session) {
  10977. if (session) { SSL_free(static_cast<SSL *>(session)); }
  10978. }
  10979. inline bool tls_set_sni(tls_session_t session, const char *hostname) {
  10980. if (!session || !hostname) return false;
  10981. auto ssl = static_cast<SSL *>(session);
  10982. // Set SNI (Server Name Indication) only - does not enable verification
  10983. #if defined(OPENSSL_IS_BORINGSSL)
  10984. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  10985. #else
  10986. // Direct call instead of macro to suppress -Wold-style-cast warning
  10987. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  10988. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  10989. #endif
  10990. }
  10991. inline bool tls_set_hostname(tls_session_t session, const char *hostname) {
  10992. if (!session || !hostname) return false;
  10993. auto ssl = static_cast<SSL *>(session);
  10994. // Set SNI (Server Name Indication)
  10995. if (!tls_set_sni(session, hostname)) { return false; }
  10996. // Enable hostname verification
  10997. auto param = SSL_get0_param(ssl);
  10998. if (!param) return false;
  10999. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  11000. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  11001. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  11002. return true;
  11003. }
  11004. inline TlsError tls_connect(tls_session_t session) {
  11005. if (!session) { return TlsError(); }
  11006. auto ssl = static_cast<SSL *>(session);
  11007. auto ret = SSL_connect(ssl);
  11008. TlsError err;
  11009. if (ret == 1) {
  11010. err.code = ErrorCode::Success;
  11011. } else {
  11012. auto ssl_err = SSL_get_error(ssl, ret);
  11013. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11014. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11015. }
  11016. return err;
  11017. }
  11018. inline TlsError tls_accept(tls_session_t session) {
  11019. if (!session) { return TlsError(); }
  11020. auto ssl = static_cast<SSL *>(session);
  11021. auto ret = SSL_accept(ssl);
  11022. TlsError err;
  11023. if (ret == 1) {
  11024. err.code = ErrorCode::Success;
  11025. } else {
  11026. auto ssl_err = SSL_get_error(ssl, ret);
  11027. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11028. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11029. }
  11030. return err;
  11031. }
  11032. inline bool tls_connect_nonblocking(tls_session_t session, socket_t sock,
  11033. time_t timeout_sec, time_t timeout_usec,
  11034. TlsError *err) {
  11035. if (!session) {
  11036. if (err) { err->code = ErrorCode::Fatal; }
  11037. return false;
  11038. }
  11039. auto ssl = static_cast<SSL *>(session);
  11040. auto bio = SSL_get_rbio(ssl);
  11041. // Set non-blocking mode for handshake
  11042. detail::set_nonblocking(sock, true);
  11043. if (bio) { BIO_set_nbio(bio, 1); }
  11044. auto cleanup = detail::scope_exit([&]() {
  11045. // Restore blocking mode after handshake
  11046. if (bio) { BIO_set_nbio(bio, 0); }
  11047. detail::set_nonblocking(sock, false);
  11048. });
  11049. auto res = 0;
  11050. while ((res = SSL_connect(ssl)) != 1) {
  11051. auto ssl_err = SSL_get_error(ssl, res);
  11052. switch (ssl_err) {
  11053. case SSL_ERROR_WANT_READ:
  11054. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  11055. continue;
  11056. }
  11057. break;
  11058. case SSL_ERROR_WANT_WRITE:
  11059. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  11060. continue;
  11061. }
  11062. break;
  11063. default: break;
  11064. }
  11065. if (err) {
  11066. err->code = map_ssl_error(ssl_err, err->sys_errno);
  11067. if (err->code == ErrorCode::Fatal) {
  11068. err->backend_code = ERR_get_error();
  11069. }
  11070. }
  11071. return false;
  11072. }
  11073. if (err) { err->code = ErrorCode::Success; }
  11074. return true;
  11075. }
  11076. inline bool tls_accept_nonblocking(tls_session_t session, socket_t sock,
  11077. time_t timeout_sec, time_t timeout_usec,
  11078. TlsError *err) {
  11079. if (!session) {
  11080. if (err) { err->code = ErrorCode::Fatal; }
  11081. return false;
  11082. }
  11083. auto ssl = static_cast<SSL *>(session);
  11084. auto bio = SSL_get_rbio(ssl);
  11085. // Set non-blocking mode for handshake
  11086. detail::set_nonblocking(sock, true);
  11087. if (bio) { BIO_set_nbio(bio, 1); }
  11088. auto cleanup = detail::scope_exit([&]() {
  11089. // Restore blocking mode after handshake
  11090. if (bio) { BIO_set_nbio(bio, 0); }
  11091. detail::set_nonblocking(sock, false);
  11092. });
  11093. auto res = 0;
  11094. while ((res = SSL_accept(ssl)) != 1) {
  11095. auto ssl_err = SSL_get_error(ssl, res);
  11096. switch (ssl_err) {
  11097. case SSL_ERROR_WANT_READ:
  11098. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  11099. continue;
  11100. }
  11101. break;
  11102. case SSL_ERROR_WANT_WRITE:
  11103. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  11104. continue;
  11105. }
  11106. break;
  11107. default: break;
  11108. }
  11109. if (err) {
  11110. err->code = map_ssl_error(ssl_err, err->sys_errno);
  11111. if (err->code == ErrorCode::Fatal) {
  11112. err->backend_code = ERR_get_error();
  11113. }
  11114. }
  11115. return false;
  11116. }
  11117. if (err) { err->code = ErrorCode::Success; }
  11118. return true;
  11119. }
  11120. inline ssize_t tls_read(tls_session_t session, void *buf, size_t len,
  11121. TlsError &err) {
  11122. if (!session || !buf) {
  11123. err.code = ErrorCode::Fatal;
  11124. return -1;
  11125. }
  11126. auto ssl = static_cast<SSL *>(session);
  11127. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  11128. if (ret > 0) {
  11129. err.code = ErrorCode::Success;
  11130. return ret;
  11131. }
  11132. auto ssl_err = SSL_get_error(ssl, ret);
  11133. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11134. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11135. return -1;
  11136. }
  11137. inline ssize_t tls_write(tls_session_t session, const void *buf, size_t len,
  11138. TlsError &err) {
  11139. if (!session || !buf) {
  11140. err.code = ErrorCode::Fatal;
  11141. return -1;
  11142. }
  11143. auto ssl = static_cast<SSL *>(session);
  11144. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  11145. if (ret > 0) {
  11146. err.code = ErrorCode::Success;
  11147. return ret;
  11148. }
  11149. auto ssl_err = SSL_get_error(ssl, ret);
  11150. err.code = map_ssl_error(ssl_err, err.sys_errno);
  11151. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  11152. return -1;
  11153. }
  11154. inline int tls_pending(tls_session_t session) {
  11155. if (!session) return 0;
  11156. return SSL_pending(static_cast<SSL *>(session));
  11157. }
  11158. inline void tls_shutdown(tls_session_t session, bool graceful) {
  11159. if (!session) return;
  11160. auto ssl = static_cast<SSL *>(session);
  11161. if (graceful) {
  11162. // First call sends close_notify
  11163. if (SSL_shutdown(ssl) == 0) {
  11164. // Second call waits for peer's close_notify
  11165. SSL_shutdown(ssl);
  11166. }
  11167. }
  11168. }
  11169. inline bool tls_is_peer_closed(tls_session_t session, socket_t sock) {
  11170. if (!session) return true;
  11171. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  11172. detail::set_nonblocking(sock, true);
  11173. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  11174. auto ssl = static_cast<SSL *>(session);
  11175. char buf;
  11176. auto ret = SSL_peek(ssl, &buf, 1);
  11177. if (ret > 0) return false;
  11178. auto err = SSL_get_error(ssl, ret);
  11179. return err == SSL_ERROR_ZERO_RETURN;
  11180. }
  11181. inline tls_cert_t tls_get_peer_cert(tls_session_t session) {
  11182. if (!session) return nullptr;
  11183. return static_cast<tls_cert_t>(
  11184. SSL_get1_peer_certificate(static_cast<SSL *>(session)));
  11185. }
  11186. inline void tls_free_cert(tls_cert_t cert) {
  11187. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  11188. }
  11189. inline bool tls_verify_hostname(tls_cert_t cert, const char *hostname) {
  11190. if (!cert || !hostname) return false;
  11191. auto x509 = static_cast<X509 *>(cert);
  11192. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  11193. }
  11194. inline long tls_get_verify_result(tls_session_t session) {
  11195. if (!session) return X509_V_ERR_UNSPECIFIED;
  11196. return SSL_get_verify_result(static_cast<SSL *>(session));
  11197. }
  11198. inline std::string tls_get_cert_subject_cn(tls_cert_t cert) {
  11199. if (!cert) return "";
  11200. auto x509 = static_cast<X509 *>(cert);
  11201. auto subject_name = X509_get_subject_name(x509);
  11202. if (!subject_name) return "";
  11203. char buf[256];
  11204. auto len =
  11205. X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf, sizeof(buf));
  11206. if (len < 0) return "";
  11207. return std::string(buf, static_cast<size_t>(len));
  11208. }
  11209. inline std::string tls_get_cert_issuer_name(tls_cert_t cert) {
  11210. if (!cert) return "";
  11211. auto x509 = static_cast<X509 *>(cert);
  11212. auto issuer_name = X509_get_issuer_name(x509);
  11213. if (!issuer_name) return "";
  11214. char buf[256];
  11215. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  11216. return std::string(buf);
  11217. }
  11218. inline bool tls_get_cert_sans(tls_cert_t cert, std::vector<TlsSanEntry> &sans) {
  11219. sans.clear();
  11220. if (!cert) return false;
  11221. auto x509 = static_cast<X509 *>(cert);
  11222. auto names = static_cast<GENERAL_NAMES *>(
  11223. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  11224. if (!names) return true; // No SANs is valid
  11225. auto count = sk_GENERAL_NAME_num(names);
  11226. for (int i = 0; i < count; i++) {
  11227. auto gen = sk_GENERAL_NAME_value(names, i);
  11228. if (!gen) continue;
  11229. TlsSanEntry entry;
  11230. switch (gen->type) {
  11231. case GEN_DNS:
  11232. entry.type = SanType::DNS;
  11233. if (gen->d.dNSName) {
  11234. entry.value = std::string(
  11235. reinterpret_cast<const char *>(
  11236. ASN1_STRING_get0_data(gen->d.dNSName)),
  11237. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  11238. }
  11239. break;
  11240. case GEN_IPADD:
  11241. entry.type = SanType::IP;
  11242. if (gen->d.iPAddress) {
  11243. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  11244. auto len = ASN1_STRING_length(gen->d.iPAddress);
  11245. if (len == 4) {
  11246. // IPv4
  11247. char buf[INET_ADDRSTRLEN];
  11248. inet_ntop(AF_INET, data, buf, sizeof(buf));
  11249. entry.value = buf;
  11250. } else if (len == 16) {
  11251. // IPv6
  11252. char buf[INET6_ADDRSTRLEN];
  11253. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  11254. entry.value = buf;
  11255. }
  11256. }
  11257. break;
  11258. case GEN_EMAIL:
  11259. entry.type = SanType::EMAIL;
  11260. if (gen->d.rfc822Name) {
  11261. entry.value = std::string(
  11262. reinterpret_cast<const char *>(
  11263. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  11264. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  11265. }
  11266. break;
  11267. case GEN_URI:
  11268. entry.type = SanType::URI;
  11269. if (gen->d.uniformResourceIdentifier) {
  11270. entry.value = std::string(
  11271. reinterpret_cast<const char *>(
  11272. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  11273. static_cast<size_t>(
  11274. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  11275. }
  11276. break;
  11277. default: entry.type = SanType::OTHER; break;
  11278. }
  11279. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  11280. }
  11281. GENERAL_NAMES_free(names);
  11282. return true;
  11283. }
  11284. inline bool tls_get_cert_validity(tls_cert_t cert, time_t &not_before,
  11285. time_t &not_after) {
  11286. if (!cert) return false;
  11287. auto x509 = static_cast<X509 *>(cert);
  11288. auto nb = X509_get0_notBefore(x509);
  11289. auto na = X509_get0_notAfter(x509);
  11290. if (!nb || !na) return false;
  11291. // Convert ASN1_TIME to time_t
  11292. struct tm tm_nb = {}, tm_na = {};
  11293. if (ASN1_TIME_to_tm(nb, &tm_nb) != 1) return false;
  11294. if (ASN1_TIME_to_tm(na, &tm_na) != 1) return false;
  11295. #ifdef _WIN32
  11296. not_before = _mkgmtime(&tm_nb);
  11297. not_after = _mkgmtime(&tm_na);
  11298. #else
  11299. not_before = timegm(&tm_nb);
  11300. not_after = timegm(&tm_na);
  11301. #endif
  11302. return true;
  11303. }
  11304. inline std::string tls_get_cert_serial(tls_cert_t cert) {
  11305. if (!cert) return "";
  11306. auto x509 = static_cast<X509 *>(cert);
  11307. auto serial = X509_get_serialNumber(x509);
  11308. if (!serial) return "";
  11309. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  11310. if (!bn) return "";
  11311. auto hex = BN_bn2hex(bn);
  11312. BN_free(bn);
  11313. if (!hex) return "";
  11314. std::string result(hex);
  11315. OPENSSL_free(hex);
  11316. return result;
  11317. }
  11318. inline const char *tls_get_sni(tls_session_t session) {
  11319. if (!session) return nullptr;
  11320. auto ssl = static_cast<SSL *>(session);
  11321. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  11322. }
  11323. inline uint64_t tls_peek_error() { return ERR_peek_last_error(); }
  11324. inline uint64_t tls_get_error() { return ERR_get_error(); }
  11325. inline std::string tls_error_string(uint64_t code) {
  11326. char buf[256];
  11327. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  11328. return std::string(buf);
  11329. }
  11330. inline tls_ca_store_t tls_create_ca_store(const char *pem, size_t len) {
  11331. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  11332. if (!mem) { return nullptr; }
  11333. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  11334. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  11335. if (!inf) { return nullptr; }
  11336. auto store = X509_STORE_new();
  11337. if (store) {
  11338. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  11339. auto itmp = sk_X509_INFO_value(inf, i);
  11340. if (!itmp) { continue; }
  11341. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  11342. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  11343. }
  11344. }
  11345. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  11346. return static_cast<tls_ca_store_t>(store);
  11347. }
  11348. inline void tls_free_ca_store(tls_ca_store_t store) {
  11349. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  11350. }
  11351. inline bool tls_set_ca_store(tls_ctx_t ctx, tls_ca_store_t store) {
  11352. if (!ctx || !store) { return false; }
  11353. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11354. auto x509_store = static_cast<X509_STORE *>(store);
  11355. // Check if same store is already set
  11356. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  11357. // SSL_CTX_set_cert_store takes ownership and frees the old store
  11358. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  11359. return true;
  11360. }
  11361. inline size_t tls_get_ca_certs(tls_ctx_t ctx, std::vector<tls_cert_t> &certs) {
  11362. certs.clear();
  11363. if (!ctx) { return 0; }
  11364. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11365. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  11366. if (!store) { return 0; }
  11367. auto objs = X509_STORE_get0_objects(store);
  11368. if (!objs) { return 0; }
  11369. int count = sk_X509_OBJECT_num(objs);
  11370. for (int i = 0; i < count; i++) {
  11371. auto obj = sk_X509_OBJECT_value(objs, i);
  11372. if (!obj) { continue; }
  11373. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  11374. auto x509 = X509_OBJECT_get0_X509(obj);
  11375. if (x509) {
  11376. // Increment reference count so caller can free it
  11377. X509_up_ref(x509);
  11378. certs.push_back(static_cast<tls_cert_t>(x509));
  11379. }
  11380. }
  11381. }
  11382. return certs.size();
  11383. }
  11384. inline std::vector<std::string> tls_get_ca_names(tls_ctx_t ctx) {
  11385. std::vector<std::string> names;
  11386. if (!ctx) { return names; }
  11387. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11388. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  11389. if (!store) { return names; }
  11390. auto objs = X509_STORE_get0_objects(store);
  11391. if (!objs) { return names; }
  11392. int count = sk_X509_OBJECT_num(objs);
  11393. for (int i = 0; i < count; i++) {
  11394. auto obj = sk_X509_OBJECT_value(objs, i);
  11395. if (!obj) { continue; }
  11396. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  11397. auto x509 = X509_OBJECT_get0_X509(obj);
  11398. if (x509) {
  11399. auto subject = X509_get_subject_name(x509);
  11400. if (subject) {
  11401. char buf[512];
  11402. X509_NAME_oneline(subject, buf, sizeof(buf));
  11403. names.push_back(buf);
  11404. }
  11405. }
  11406. }
  11407. }
  11408. return names;
  11409. }
  11410. inline bool tls_update_server_cert(tls_ctx_t ctx, const char *cert_pem,
  11411. const char *key_pem, const char *password) {
  11412. if (!ctx || !cert_pem || !key_pem) { return false; }
  11413. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11414. // Load certificate from PEM
  11415. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  11416. if (!cert_bio) { return false; }
  11417. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  11418. BIO_free(cert_bio);
  11419. if (!cert) { return false; }
  11420. // Load private key from PEM
  11421. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  11422. if (!key_bio) {
  11423. X509_free(cert);
  11424. return false;
  11425. }
  11426. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  11427. password ? const_cast<char *>(password)
  11428. : nullptr);
  11429. BIO_free(key_bio);
  11430. if (!key) {
  11431. X509_free(cert);
  11432. return false;
  11433. }
  11434. // Update certificate and key
  11435. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  11436. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  11437. X509_free(cert);
  11438. EVP_PKEY_free(key);
  11439. return ret;
  11440. }
  11441. // Helper: Create client CA list from PEM string
  11442. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  11443. // Caller takes ownership of returned list
  11444. inline STACK_OF(X509_NAME) *
  11445. create_client_ca_list_from_pem(const char *ca_pem) {
  11446. if (!ca_pem) { return nullptr; }
  11447. auto ca_list = sk_X509_NAME_new_null();
  11448. if (!ca_list) { return nullptr; }
  11449. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  11450. if (!bio) {
  11451. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  11452. return nullptr;
  11453. }
  11454. X509 *cert = nullptr;
  11455. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  11456. nullptr) {
  11457. X509_NAME *name = X509_get_subject_name(cert);
  11458. if (name) { sk_X509_NAME_push(ca_list, X509_NAME_dup(name)); }
  11459. X509_free(cert);
  11460. }
  11461. BIO_free(bio);
  11462. return ca_list;
  11463. }
  11464. // Helper: Extract CA names from X509_STORE
  11465. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  11466. // Caller takes ownership of returned list
  11467. inline STACK_OF(X509_NAME) *
  11468. extract_client_ca_list_from_store(X509_STORE *store) {
  11469. if (!store) { return nullptr; }
  11470. auto ca_list = sk_X509_NAME_new_null();
  11471. if (!ca_list) { return nullptr; }
  11472. auto objs = X509_STORE_get0_objects(store);
  11473. if (!objs) {
  11474. sk_X509_NAME_free(ca_list);
  11475. return nullptr;
  11476. }
  11477. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  11478. auto obj = sk_X509_OBJECT_value(objs, i);
  11479. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  11480. auto cert = X509_OBJECT_get0_X509(obj);
  11481. if (cert) {
  11482. auto subject = X509_get_subject_name(cert);
  11483. if (subject) {
  11484. auto name_dup = X509_NAME_dup(subject);
  11485. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  11486. }
  11487. }
  11488. }
  11489. }
  11490. if (sk_X509_NAME_num(ca_list) == 0) {
  11491. sk_X509_NAME_free(ca_list);
  11492. return nullptr;
  11493. }
  11494. return ca_list;
  11495. }
  11496. inline bool tls_update_server_client_ca(tls_ctx_t ctx, const char *ca_pem) {
  11497. if (!ctx || !ca_pem) { return false; }
  11498. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11499. // Create new X509_STORE from PEM
  11500. auto store = tls_create_ca_store(ca_pem, strlen(ca_pem));
  11501. if (!store) { return false; }
  11502. // SSL_CTX_set_cert_store takes ownership
  11503. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  11504. // Set client CA list for client certificate request
  11505. auto ca_list = create_client_ca_list_from_pem(ca_pem);
  11506. if (ca_list) {
  11507. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  11508. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  11509. }
  11510. return true;
  11511. }
  11512. // Thread-local storage for verify callback
  11513. inline TlsVerifyCallback &get_verify_callback() {
  11514. static thread_local TlsVerifyCallback callback;
  11515. return callback;
  11516. }
  11517. // OpenSSL verify callback wrapper
  11518. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  11519. auto &callback = get_verify_callback();
  11520. if (!callback) { return preverify_ok; }
  11521. // Get SSL object from X509_STORE_CTX
  11522. auto ssl = static_cast<SSL *>(
  11523. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  11524. if (!ssl) { return preverify_ok; }
  11525. // Get peer certificate
  11526. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  11527. if (!cert) { return preverify_ok; }
  11528. // Call user callback
  11529. return callback(static_cast<tls_session_t>(ssl),
  11530. static_cast<tls_cert_t>(cert))
  11531. ? 1
  11532. : 0;
  11533. }
  11534. inline bool tls_set_verify_callback(tls_ctx_t ctx, TlsVerifyCallback callback) {
  11535. if (!ctx) { return false; }
  11536. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11537. get_verify_callback() = std::move(callback);
  11538. if (get_verify_callback()) {
  11539. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, openssl_verify_callback);
  11540. } else {
  11541. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  11542. }
  11543. return true;
  11544. }
  11545. // Thread-local storage for extended verify callback
  11546. inline TlsVerifyCallbackEx &get_verify_callback_ex() {
  11547. static thread_local TlsVerifyCallbackEx callback;
  11548. return callback;
  11549. }
  11550. // OpenSSL extended verify callback wrapper
  11551. inline int openssl_verify_callback_ex(int preverify_ok, X509_STORE_CTX *ctx) {
  11552. auto &callback = get_verify_callback_ex();
  11553. if (!callback) { return preverify_ok; }
  11554. // Get SSL object from X509_STORE_CTX
  11555. auto ssl = static_cast<SSL *>(
  11556. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  11557. if (!ssl) { return preverify_ok; }
  11558. // Get current certificate and depth
  11559. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  11560. int depth = X509_STORE_CTX_get_error_depth(ctx);
  11561. int error = X509_STORE_CTX_get_error(ctx);
  11562. // Build context
  11563. TlsVerifyContext verify_ctx;
  11564. verify_ctx.session = static_cast<tls_session_t>(ssl);
  11565. verify_ctx.cert = static_cast<tls_cert_t>(cert);
  11566. verify_ctx.depth = depth;
  11567. verify_ctx.preverify_ok = (preverify_ok != 0);
  11568. verify_ctx.error_code = error;
  11569. verify_ctx.error_string =
  11570. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  11571. return callback(verify_ctx) ? 1 : 0;
  11572. }
  11573. inline bool tls_set_verify_callback_ex(tls_ctx_t ctx,
  11574. TlsVerifyCallbackEx callback) {
  11575. if (!ctx) { return false; }
  11576. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  11577. get_verify_callback_ex() = std::move(callback);
  11578. if (get_verify_callback_ex()) {
  11579. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, openssl_verify_callback_ex);
  11580. } else {
  11581. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  11582. }
  11583. return true;
  11584. }
  11585. inline long tls_get_verify_error(tls_session_t session) {
  11586. if (!session) { return -1; }
  11587. auto ssl = static_cast<SSL *>(session);
  11588. return SSL_get_verify_result(ssl);
  11589. }
  11590. inline std::string tls_verify_error_string(long error_code) {
  11591. if (error_code == X509_V_OK) { return ""; }
  11592. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  11593. return str ? str : "unknown error";
  11594. }
  11595. // OpenSSL-specific helpers for public API wrappers
  11596. inline tls_ctx_t create_server_context_from_x509(X509 *cert, EVP_PKEY *key,
  11597. X509_STORE *client_ca_store,
  11598. int &out_error) {
  11599. out_error = 0;
  11600. auto cert_pem = x509_to_pem(cert);
  11601. auto key_pem = evp_pkey_to_pem(key);
  11602. if (cert_pem.empty() || key_pem.empty()) {
  11603. out_error = static_cast<int>(ERR_get_error());
  11604. return nullptr;
  11605. }
  11606. auto ctx = tls_create_server_context();
  11607. if (!ctx) {
  11608. out_error = static_cast<int>(tls_get_error());
  11609. return nullptr;
  11610. }
  11611. if (!tls_set_server_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  11612. nullptr)) {
  11613. out_error = static_cast<int>(tls_get_error());
  11614. tls_free_context(ctx);
  11615. return nullptr;
  11616. }
  11617. if (client_ca_store) {
  11618. // Set cert store for verification (SSL_CTX_set_cert_store takes ownership)
  11619. SSL_CTX_set_cert_store(static_cast<SSL_CTX *>(ctx), client_ca_store);
  11620. // Extract and set client CA list directly from store (more efficient than
  11621. // PEM conversion)
  11622. auto ca_list = extract_client_ca_list_from_store(client_ca_store);
  11623. if (ca_list) {
  11624. SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), ca_list);
  11625. }
  11626. tls_set_verify_client(ctx, true);
  11627. }
  11628. return ctx;
  11629. }
  11630. inline void update_server_certs_from_x509(tls_ctx_t ctx, X509 *cert,
  11631. EVP_PKEY *key,
  11632. X509_STORE *client_ca_store) {
  11633. auto cert_pem = x509_to_pem(cert);
  11634. auto key_pem = evp_pkey_to_pem(key);
  11635. if (!cert_pem.empty() && !key_pem.empty()) {
  11636. tls_update_server_cert(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr);
  11637. }
  11638. if (client_ca_store) {
  11639. auto ca_pem = x509_store_to_pem(client_ca_store);
  11640. if (!ca_pem.empty()) { tls_update_server_client_ca(ctx, ca_pem.c_str()); }
  11641. X509_STORE_free(client_ca_store);
  11642. }
  11643. }
  11644. inline tls_ctx_t create_client_context_from_x509(X509 *cert, EVP_PKEY *key,
  11645. const char *password,
  11646. unsigned long &out_error) {
  11647. out_error = 0;
  11648. auto ctx = tls_create_client_context();
  11649. if (!ctx) {
  11650. out_error = static_cast<unsigned long>(tls_get_error());
  11651. return nullptr;
  11652. }
  11653. if (cert && key) {
  11654. auto cert_pem = x509_to_pem(cert);
  11655. auto key_pem = evp_pkey_to_pem(key);
  11656. if (cert_pem.empty() || key_pem.empty()) {
  11657. out_error = ERR_get_error();
  11658. tls_free_context(ctx);
  11659. return nullptr;
  11660. }
  11661. if (!tls_set_client_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  11662. password)) {
  11663. out_error = static_cast<unsigned long>(tls_get_error());
  11664. tls_free_context(ctx);
  11665. return nullptr;
  11666. }
  11667. }
  11668. return ctx;
  11669. }
  11670. } // namespace tls
  11671. // ClientImpl::set_ca_cert_store - defined here to use tls::x509_store_to_pem
  11672. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  11673. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  11674. ca_cert_pem_ = tls::x509_store_to_pem(ca_cert_store);
  11675. ca_cert_store_ = ca_cert_store;
  11676. }
  11677. }
  11678. inline bool SSLClient::check_host_name(const char *pattern,
  11679. size_t pattern_len) const {
  11680. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  11681. // Wildcard match
  11682. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  11683. std::vector<std::string> pattern_components;
  11684. detail::split(&pattern[0], &pattern[pattern_len], '.',
  11685. [&](const char *b, const char *e) {
  11686. pattern_components.emplace_back(b, e);
  11687. });
  11688. if (host_components_.size() != pattern_components.size()) { return false; }
  11689. auto itr = pattern_components.begin();
  11690. for (const auto &h : host_components_) {
  11691. auto &p = *itr;
  11692. if (p != h && p != "*") {
  11693. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  11694. !p.compare(0, p.size() - 1, h));
  11695. if (!partial_match) { return false; }
  11696. }
  11697. ++itr;
  11698. }
  11699. return true;
  11700. }
  11701. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  11702. X509_STORE *client_ca_cert_store) {
  11703. ctx_ = tls::create_server_context_from_x509(
  11704. cert, private_key, client_ca_cert_store, last_ssl_error_);
  11705. }
  11706. inline SSLServer::SSLServer(
  11707. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  11708. // Use abstract API to create context
  11709. ctx_ = tls::tls_create_server_context();
  11710. if (ctx_) {
  11711. // Pass to OpenSSL-specific callback (ctx_ is SSL_CTX* internally)
  11712. auto ssl_ctx = static_cast<SSL_CTX *>(ctx_);
  11713. if (!setup_ssl_ctx_callback(*ssl_ctx)) {
  11714. tls::tls_free_context(ctx_);
  11715. ctx_ = nullptr;
  11716. }
  11717. }
  11718. }
  11719. inline SSL_CTX *SSLServer::ssl_context() const {
  11720. return static_cast<SSL_CTX *>(ctx_);
  11721. }
  11722. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  11723. X509_STORE *client_ca_cert_store) {
  11724. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11725. tls::update_server_certs_from_x509(ctx_, cert, private_key,
  11726. client_ca_cert_store);
  11727. }
  11728. // SSL HTTP client implementation
  11729. inline SSLClient::SSLClient(const std::string &host)
  11730. : SSLClient(host, 443, std::string(), std::string()) {}
  11731. inline SSLClient::SSLClient(const std::string &host, int port)
  11732. : SSLClient(host, port, std::string(), std::string()) {}
  11733. inline SSLClient::SSLClient(const std::string &host, int port,
  11734. const std::string &client_cert_path,
  11735. const std::string &client_key_path,
  11736. const std::string &private_key_password)
  11737. : ClientImpl(host, port, client_cert_path, client_key_path) {
  11738. ctx_ = tls::tls_create_client_context();
  11739. // TODO: Add tls_set_min_protocol_version() to TLS abstraction API
  11740. // SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  11741. detail::split(&host_[0], &host_[host_.size()], '.',
  11742. [&](const char *b, const char *e) {
  11743. host_components_.emplace_back(b, e);
  11744. });
  11745. if (!client_cert_path.empty() && !client_key_path.empty()) {
  11746. const char *password =
  11747. private_key_password.empty() ? nullptr : private_key_password.c_str();
  11748. if (!tls::tls_set_client_cert_file(ctx_, client_cert_path.c_str(),
  11749. client_key_path.c_str(), password)) {
  11750. last_backend_error_ = ERR_get_error();
  11751. tls::tls_free_context(ctx_);
  11752. ctx_ = nullptr;
  11753. }
  11754. }
  11755. }
  11756. inline SSLClient::SSLClient(const std::string &host, int port,
  11757. X509 *client_cert, EVP_PKEY *client_key,
  11758. const std::string &private_key_password)
  11759. : ClientImpl(host, port) {
  11760. const char *password =
  11761. private_key_password.empty() ? nullptr : private_key_password.c_str();
  11762. ctx_ = tls::create_client_context_from_x509(client_cert, client_key, password,
  11763. last_backend_error_);
  11764. detail::split(&host_[0], &host_[host_.size()], '.',
  11765. [&](const char *b, const char *e) {
  11766. host_components_.emplace_back(b, e);
  11767. });
  11768. }
  11769. inline SSLClient::SSLClient(const std::string &host, int port,
  11770. const PemMemory &pem)
  11771. : ClientImpl(host, port) {
  11772. ctx_ = tls::tls_create_client_context();
  11773. detail::split(&host_[0], &host_[host_.size()], '.',
  11774. [&](const char *b, const char *e) {
  11775. host_components_.emplace_back(b, e);
  11776. });
  11777. if (ctx_ && pem.cert_pem && pem.key_pem) {
  11778. if (!tls::tls_set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  11779. pem.private_key_password)) {
  11780. last_backend_error_ = tls::tls_get_error();
  11781. tls::tls_free_context(ctx_);
  11782. ctx_ = nullptr;
  11783. }
  11784. }
  11785. }
  11786. inline void SSLClient::set_ca_cert_store(void *ca_cert_store) {
  11787. if (ca_cert_store && ctx_) {
  11788. // tls_set_ca_store takes ownership of ca_cert_store
  11789. tls::tls_set_ca_store(ctx_, ca_cert_store);
  11790. } else if (ca_cert_store) {
  11791. tls::tls_free_ca_store(ca_cert_store);
  11792. }
  11793. }
  11794. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  11795. std::size_t size) {
  11796. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  11797. set_ca_cert_store(tls::tls_create_ca_store(ca_cert, size));
  11798. }
  11799. inline void
  11800. SSLClient::set_server_certificate_verifier(TlsVerifyCallback verifier) {
  11801. if (!ctx_) { return; }
  11802. tls::tls_set_verify_callback(
  11803. ctx_, [verifier](tls::tls_session_t session, tls::tls_cert_t cert) {
  11804. return verifier(session, cert);
  11805. });
  11806. }
  11807. inline long SSLClient::get_openssl_verify_result() const {
  11808. return verify_result_;
  11809. }
  11810. inline SSL_CTX *SSLClient::ssl_context() const {
  11811. return static_cast<SSL_CTX *>(ctx_);
  11812. }
  11813. inline bool SSLClient::load_certs() {
  11814. auto ret = true;
  11815. std::call_once(initialize_cert_, [&]() {
  11816. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11817. if (!ca_cert_file_path_.empty()) {
  11818. if (!tls::tls_load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  11819. last_backend_error_ = ERR_get_error();
  11820. ret = false;
  11821. }
  11822. } else if (!ca_cert_dir_path_.empty()) {
  11823. if (!tls::tls_load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  11824. last_backend_error_ = ERR_get_error();
  11825. ret = false;
  11826. }
  11827. } else {
  11828. // Load system certificates
  11829. if (!tls::tls_load_system_certs(ctx_)) {
  11830. last_backend_error_ = ERR_get_error();
  11831. // Ignore error and continue - some systems may not have certs
  11832. }
  11833. }
  11834. });
  11835. return ret;
  11836. }
  11837. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  11838. using namespace tls;
  11839. // Load CA certificates if server verification is enabled
  11840. if (server_certificate_verification_) {
  11841. if (!load_certs()) {
  11842. error = Error::SSLLoadingCerts;
  11843. output_error_log(error, nullptr);
  11844. return false;
  11845. }
  11846. }
  11847. // Create TLS session (uses ctx_ which has SSL_VERIFY_NONE by default)
  11848. tls_session_t session = nullptr;
  11849. {
  11850. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11851. session = tls_create_session(ctx_, socket.sock);
  11852. }
  11853. if (!session) {
  11854. error = Error::SSLConnection;
  11855. last_backend_error_ = ERR_get_error();
  11856. return false;
  11857. }
  11858. // Use scope_exit to ensure session is freed on error paths
  11859. bool success = false;
  11860. auto session_guard = detail::scope_exit([&] {
  11861. if (!success) { tls_free_session(session); }
  11862. });
  11863. // Set SNI before handshake (only if host is not IP address)
  11864. if (!detail::is_ip_address(host_)) {
  11865. if (!tls_set_sni(session, host_.c_str())) {
  11866. error = Error::SSLConnection;
  11867. last_backend_error_ = ERR_get_error();
  11868. return false;
  11869. }
  11870. }
  11871. // Perform non-blocking TLS handshake with timeout
  11872. TlsError tls_err;
  11873. if (!tls_connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  11874. connection_timeout_usec_, &tls_err)) {
  11875. // Map TlsError to legacy ssl_error for backward compatibility
  11876. if (tls_err.code == ErrorCode::WantRead) {
  11877. last_ssl_error_ = SSL_ERROR_WANT_READ;
  11878. } else if (tls_err.code == ErrorCode::WantWrite) {
  11879. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  11880. } else {
  11881. last_ssl_error_ = SSL_ERROR_SSL;
  11882. }
  11883. error = Error::SSLConnection;
  11884. output_error_log(error, nullptr);
  11885. return false;
  11886. }
  11887. // Server certificate verification
  11888. if (server_certificate_verification_) {
  11889. // Cast to SSL* for backward compatibility with verifier callback
  11890. auto ssl = static_cast<SSL *>(session);
  11891. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  11892. if (server_certificate_verifier_) {
  11893. verification_status = server_certificate_verifier_(ssl);
  11894. }
  11895. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  11896. last_backend_error_ = ERR_get_error();
  11897. error = Error::SSLServerVerification;
  11898. output_error_log(error, nullptr);
  11899. return false;
  11900. }
  11901. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  11902. verify_result_ = tls_get_verify_result(session);
  11903. if (verify_result_ != X509_V_OK) {
  11904. last_backend_error_ = static_cast<unsigned long>(verify_result_);
  11905. error = Error::SSLServerVerification;
  11906. output_error_log(error, nullptr);
  11907. return false;
  11908. }
  11909. auto server_cert = tls_get_peer_cert(session);
  11910. if (!server_cert) {
  11911. last_backend_error_ = ERR_get_error();
  11912. error = Error::SSLServerVerification;
  11913. output_error_log(error, nullptr);
  11914. return false;
  11915. }
  11916. auto cert_guard = detail::scope_exit([&] { tls_free_cert(server_cert); });
  11917. if (server_hostname_verification_) {
  11918. // verify_host() expects X509*, so cast from tls_cert_t
  11919. if (!verify_host(static_cast<X509 *>(server_cert))) {
  11920. last_backend_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  11921. error = Error::SSLServerHostnameVerification;
  11922. output_error_log(error, nullptr);
  11923. return false;
  11924. }
  11925. }
  11926. }
  11927. }
  11928. success = true;
  11929. socket.ssl = session;
  11930. return true;
  11931. }
  11932. inline bool SSLClient::verify_host(X509 *server_cert) const {
  11933. /* Quote from RFC2818 section 3.1 "Server Identity"
  11934. If a subjectAltName extension of type dNSName is present, that MUST
  11935. be used as the identity. Otherwise, the (most specific) Common Name
  11936. field in the Subject field of the certificate MUST be used. Although
  11937. the use of the Common Name is existing practice, it is deprecated and
  11938. Certification Authorities are encouraged to use the dNSName instead.
  11939. Matching is performed using the matching rules specified by
  11940. [RFC2459]. If more than one identity of a given type is present in
  11941. the certificate (e.g., more than one dNSName name, a match in any one
  11942. of the set is considered acceptable.) Names may contain the wildcard
  11943. character * which is considered to match any single domain name
  11944. component or component fragment. E.g., *.a.com matches foo.a.com but
  11945. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  11946. In some cases, the URI is specified as an IP address rather than a
  11947. hostname. In this case, the iPAddress subjectAltName must be present
  11948. in the certificate and must exactly match the IP in the URI.
  11949. */
  11950. return verify_host_with_subject_alt_name(server_cert) ||
  11951. verify_host_with_common_name(server_cert);
  11952. }
  11953. inline bool
  11954. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  11955. auto ret = false;
  11956. auto type = GEN_DNS;
  11957. struct in6_addr addr6 = {};
  11958. struct in_addr addr = {};
  11959. size_t addr_len = 0;
  11960. #ifndef __MINGW32__
  11961. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  11962. type = GEN_IPADD;
  11963. addr_len = sizeof(struct in6_addr);
  11964. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  11965. type = GEN_IPADD;
  11966. addr_len = sizeof(struct in_addr);
  11967. }
  11968. #endif
  11969. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  11970. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  11971. if (alt_names) {
  11972. auto dsn_matched = false;
  11973. auto ip_matched = false;
  11974. auto count = sk_GENERAL_NAME_num(alt_names);
  11975. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  11976. auto val = sk_GENERAL_NAME_value(alt_names, i);
  11977. if (!val || val->type != type) { continue; }
  11978. auto name =
  11979. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  11980. if (name == nullptr) { continue; }
  11981. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  11982. switch (type) {
  11983. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  11984. case GEN_IPADD:
  11985. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  11986. ip_matched = true;
  11987. }
  11988. break;
  11989. }
  11990. }
  11991. if (dsn_matched || ip_matched) { ret = true; }
  11992. }
  11993. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  11994. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  11995. return ret;
  11996. }
  11997. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  11998. const auto subject_name = X509_get_subject_name(server_cert);
  11999. if (subject_name != nullptr) {
  12000. char name[BUFSIZ];
  12001. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  12002. name, sizeof(name));
  12003. if (name_len != -1) {
  12004. return check_host_name(name, static_cast<size_t>(name_len));
  12005. }
  12006. }
  12007. return false;
  12008. }
  12009. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  12010. /*
  12011. * Mbed TLS Backend Implementation
  12012. */
  12013. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  12014. namespace crypto {
  12015. inline size_t hash_size(HashAlgorithm algo) {
  12016. switch (algo) {
  12017. case HashAlgorithm::MD5: return 16;
  12018. case HashAlgorithm::SHA1: return 20;
  12019. case HashAlgorithm::SHA256: return 32;
  12020. case HashAlgorithm::SHA384: return 48;
  12021. case HashAlgorithm::SHA512: return 64;
  12022. default: return 0;
  12023. }
  12024. }
  12025. inline bool hash_raw(HashAlgorithm algo, const void *data, size_t len,
  12026. std::vector<uint8_t> &digest) {
  12027. size_t dsize = hash_size(algo);
  12028. if (dsize == 0) { return false; }
  12029. digest.resize(dsize);
  12030. int ret = 0;
  12031. switch (algo) {
  12032. case HashAlgorithm::MD5:
  12033. #if MBEDTLS_VERSION_MAJOR >= 3
  12034. ret = mbedtls_md5(static_cast<const unsigned char *>(data), len,
  12035. digest.data());
  12036. #else
  12037. ret = mbedtls_md5_ret(static_cast<const unsigned char *>(data), len,
  12038. digest.data());
  12039. #endif
  12040. break;
  12041. case HashAlgorithm::SHA1:
  12042. #if MBEDTLS_VERSION_MAJOR >= 3
  12043. ret = mbedtls_sha1(static_cast<const unsigned char *>(data), len,
  12044. digest.data());
  12045. #else
  12046. ret = mbedtls_sha1_ret(static_cast<const unsigned char *>(data), len,
  12047. digest.data());
  12048. #endif
  12049. break;
  12050. case HashAlgorithm::SHA256:
  12051. #if MBEDTLS_VERSION_MAJOR >= 3
  12052. ret = mbedtls_sha256(static_cast<const unsigned char *>(data), len,
  12053. digest.data(), 0);
  12054. #else
  12055. ret = mbedtls_sha256_ret(static_cast<const unsigned char *>(data), len,
  12056. digest.data(), 0);
  12057. #endif
  12058. break;
  12059. case HashAlgorithm::SHA384:
  12060. #if MBEDTLS_VERSION_MAJOR >= 3
  12061. ret = mbedtls_sha512(static_cast<const unsigned char *>(data), len,
  12062. digest.data(), 1); // is384 = 1
  12063. #else
  12064. ret = mbedtls_sha512_ret(static_cast<const unsigned char *>(data), len,
  12065. digest.data(), 1); // is384 = 1
  12066. #endif
  12067. break;
  12068. case HashAlgorithm::SHA512:
  12069. #if MBEDTLS_VERSION_MAJOR >= 3
  12070. ret = mbedtls_sha512(static_cast<const unsigned char *>(data), len,
  12071. digest.data(), 0);
  12072. #else
  12073. ret = mbedtls_sha512_ret(static_cast<const unsigned char *>(data), len,
  12074. digest.data(), 0);
  12075. #endif
  12076. break;
  12077. }
  12078. return ret == 0;
  12079. }
  12080. inline std::string hash(HashAlgorithm algo, const void *data, size_t len) {
  12081. std::vector<uint8_t> digest;
  12082. if (!hash_raw(algo, data, len, digest)) { return ""; }
  12083. std::stringstream ss;
  12084. for (auto byte : digest) {
  12085. ss << std::hex << std::setw(2) << std::setfill('0')
  12086. << static_cast<unsigned int>(byte);
  12087. }
  12088. return ss.str();
  12089. }
  12090. inline std::string hash(HashAlgorithm algo, const std::string &data) {
  12091. return hash(algo, data.c_str(), data.size());
  12092. }
  12093. } // namespace crypto
  12094. namespace tls {
  12095. // Mbed TLS session wrapper
  12096. struct MbedTlsSession {
  12097. mbedtls_ssl_context ssl;
  12098. socket_t sock = INVALID_SOCKET;
  12099. std::string hostname; // For client: set via tls_set_sni
  12100. std::string sni_hostname; // For server: received from client via SNI callback
  12101. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  12102. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  12103. // Non-copyable
  12104. MbedTlsSession(const MbedTlsSession &) = delete;
  12105. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  12106. };
  12107. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  12108. // queue)
  12109. inline int &mbedtls_last_error() {
  12110. static thread_local int err = 0;
  12111. return err;
  12112. }
  12113. // Helper to map Mbed TLS error to ErrorCode
  12114. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  12115. if (ret == 0) { return ErrorCode::Success; }
  12116. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  12117. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  12118. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  12119. return ErrorCode::PeerClosed;
  12120. }
  12121. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  12122. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  12123. out_errno = errno;
  12124. return ErrorCode::SyscallError;
  12125. }
  12126. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  12127. return ErrorCode::CertVerifyFailed;
  12128. }
  12129. return ErrorCode::Fatal;
  12130. }
  12131. inline bool tls_global_init() {
  12132. // Mbed TLS doesn't require global initialization
  12133. return true;
  12134. }
  12135. inline void tls_global_cleanup() {
  12136. // Mbed TLS doesn't require global cleanup
  12137. }
  12138. // BIO-like send callback for Mbed TLS
  12139. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  12140. size_t len) {
  12141. auto sock = *static_cast<socket_t *>(ctx);
  12142. #ifdef _WIN32
  12143. auto ret =
  12144. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  12145. if (ret == SOCKET_ERROR) {
  12146. int err = WSAGetLastError();
  12147. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  12148. return MBEDTLS_ERR_NET_SEND_FAILED;
  12149. }
  12150. #else
  12151. auto ret = send(sock, buf, len, 0);
  12152. if (ret < 0) {
  12153. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  12154. return MBEDTLS_ERR_SSL_WANT_WRITE;
  12155. }
  12156. return MBEDTLS_ERR_NET_SEND_FAILED;
  12157. }
  12158. #endif
  12159. return static_cast<int>(ret);
  12160. }
  12161. // BIO-like recv callback for Mbed TLS
  12162. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  12163. auto sock = *static_cast<socket_t *>(ctx);
  12164. #ifdef _WIN32
  12165. auto ret =
  12166. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  12167. if (ret == SOCKET_ERROR) {
  12168. int err = WSAGetLastError();
  12169. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  12170. return MBEDTLS_ERR_NET_RECV_FAILED;
  12171. }
  12172. #else
  12173. auto ret = recv(sock, buf, len, 0);
  12174. if (ret < 0) {
  12175. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  12176. return MBEDTLS_ERR_SSL_WANT_READ;
  12177. }
  12178. return MBEDTLS_ERR_NET_RECV_FAILED;
  12179. }
  12180. #endif
  12181. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  12182. return static_cast<int>(ret);
  12183. }
  12184. inline tls_ctx_t tls_create_client_context() {
  12185. auto ctx = new (std::nothrow) httplib::MbedTlsContext();
  12186. if (!ctx) { return nullptr; }
  12187. ctx->is_server = false;
  12188. // Seed the random number generator
  12189. const char *pers = "httplib_client";
  12190. int ret = mbedtls_ctr_drbg_seed(
  12191. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  12192. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  12193. if (ret != 0) {
  12194. mbedtls_last_error() = ret;
  12195. delete ctx;
  12196. return nullptr;
  12197. }
  12198. // Set up SSL config for client
  12199. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  12200. MBEDTLS_SSL_TRANSPORT_STREAM,
  12201. MBEDTLS_SSL_PRESET_DEFAULT);
  12202. if (ret != 0) {
  12203. mbedtls_last_error() = ret;
  12204. delete ctx;
  12205. return nullptr;
  12206. }
  12207. // Set random number generator
  12208. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  12209. // Default: verify peer certificate
  12210. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  12211. // Set minimum TLS version to 1.2
  12212. #if MBEDTLS_VERSION_MAJOR >= 3
  12213. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  12214. #else
  12215. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  12216. MBEDTLS_SSL_MINOR_VERSION_3);
  12217. #endif
  12218. return static_cast<tls_ctx_t>(ctx);
  12219. }
  12220. // Forward declaration for SNI callback (defined later)
  12221. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  12222. const unsigned char *name, size_t name_len);
  12223. inline tls_ctx_t tls_create_server_context() {
  12224. auto ctx = new (std::nothrow) httplib::MbedTlsContext();
  12225. if (!ctx) { return nullptr; }
  12226. ctx->is_server = true;
  12227. // Seed the random number generator
  12228. const char *pers = "httplib_server";
  12229. int ret = mbedtls_ctr_drbg_seed(
  12230. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  12231. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  12232. if (ret != 0) {
  12233. mbedtls_last_error() = ret;
  12234. delete ctx;
  12235. return nullptr;
  12236. }
  12237. // Set up SSL config for server
  12238. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  12239. MBEDTLS_SSL_TRANSPORT_STREAM,
  12240. MBEDTLS_SSL_PRESET_DEFAULT);
  12241. if (ret != 0) {
  12242. mbedtls_last_error() = ret;
  12243. delete ctx;
  12244. return nullptr;
  12245. }
  12246. // Set random number generator
  12247. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  12248. // Default: don't verify client
  12249. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  12250. // Set minimum TLS version to 1.2
  12251. #if MBEDTLS_VERSION_MAJOR >= 3
  12252. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  12253. #else
  12254. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  12255. MBEDTLS_SSL_MINOR_VERSION_3);
  12256. #endif
  12257. // Set SNI callback to capture client's SNI hostname
  12258. mbedtls_ssl_conf_sni(&ctx->conf, mbedtls_sni_callback, nullptr);
  12259. return static_cast<tls_ctx_t>(ctx);
  12260. }
  12261. inline void tls_free_context(tls_ctx_t ctx) {
  12262. if (ctx) { delete static_cast<httplib::MbedTlsContext *>(ctx); }
  12263. }
  12264. inline bool tls_set_min_version(tls_ctx_t ctx, int version) {
  12265. if (!ctx) { return false; }
  12266. auto mctx = static_cast<httplib::MbedTlsContext *>(ctx);
  12267. // Map OpenSSL-style version constants to Mbed TLS
  12268. // TLS1_2_VERSION = 0x0303, TLS1_3_VERSION = 0x0304
  12269. #if MBEDTLS_VERSION_MAJOR >= 3
  12270. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  12271. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  12272. if (version >= 0x0304) {
  12273. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  12274. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  12275. #endif
  12276. }
  12277. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  12278. #else
  12279. // Mbed TLS 2.x uses major/minor version numbers
  12280. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  12281. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  12282. if (version >= 0x0304) {
  12283. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  12284. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  12285. #else
  12286. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  12287. #endif
  12288. }
  12289. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  12290. #endif
  12291. return true;
  12292. }
  12293. inline bool tls_load_ca_pem(tls_ctx_t ctx, const char *pem, size_t len) {
  12294. if (!ctx || !pem) { return false; }
  12295. auto mctx = static_cast<httplib::MbedTlsContext *>(ctx);
  12296. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  12297. // Add null terminator if not present
  12298. std::string pem_str(pem, len);
  12299. int ret = mbedtls_x509_crt_parse(
  12300. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  12301. pem_str.size() + 1);
  12302. if (ret != 0) {
  12303. mbedtls_last_error() = ret;
  12304. return false;
  12305. }
  12306. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  12307. return true;
  12308. }
  12309. inline bool tls_load_ca_file(tls_ctx_t ctx, const char *file_path) {
  12310. if (!ctx || !file_path) { return false; }
  12311. auto mctx = static_cast<httplib::MbedTlsContext *>(ctx);
  12312. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  12313. if (ret != 0) {
  12314. mbedtls_last_error() = ret;
  12315. return false;
  12316. }
  12317. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  12318. return true;
  12319. }
  12320. inline bool tls_load_ca_dir(tls_ctx_t ctx, const char *dir_path) {
  12321. if (!ctx || !dir_path) { return false; }
  12322. auto mctx = static_cast<httplib::MbedTlsContext *>(ctx);
  12323. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  12324. if (ret < 0) { // Returns number of certs on success, negative on error
  12325. mbedtls_last_error() = ret;
  12326. return false;
  12327. }
  12328. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  12329. return true;
  12330. }
  12331. inline bool tls_load_system_certs(tls_ctx_t ctx) {
  12332. if (!ctx) { return false; }
  12333. auto mctx = static_cast<httplib::MbedTlsContext *>(ctx);
  12334. bool loaded = false;
  12335. #ifdef _WIN32
  12336. // Load from Windows certificate store
  12337. HCERTSTORE hStore = CertOpenSystemStoreW(0, L"ROOT");
  12338. if (hStore) {
  12339. PCCERT_CONTEXT pContext = nullptr;
  12340. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  12341. nullptr) {
  12342. int ret = mbedtls_x509_crt_parse_der(
  12343. &mctx->ca_chain, pContext->pbCertEncoded, pContext->cbCertEncoded);
  12344. if (ret == 0) { loaded = true; }
  12345. }
  12346. CertCloseStore(hStore, 0);
  12347. }
  12348. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  12349. // Load from macOS Keychain
  12350. CFArrayRef certs = nullptr;
  12351. OSStatus status = SecTrustCopyAnchorCertificates(&certs);
  12352. if (status == errSecSuccess && certs) {
  12353. CFIndex count = CFArrayGetCount(certs);
  12354. for (CFIndex i = 0; i < count; i++) {
  12355. SecCertificateRef cert =
  12356. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  12357. CFDataRef data = SecCertificateCopyData(cert);
  12358. if (data) {
  12359. int ret = mbedtls_x509_crt_parse_der(
  12360. &mctx->ca_chain, CFDataGetBytePtr(data),
  12361. static_cast<size_t>(CFDataGetLength(data)));
  12362. if (ret == 0) { loaded = true; }
  12363. CFRelease(data);
  12364. }
  12365. }
  12366. CFRelease(certs);
  12367. }
  12368. #else
  12369. // Try common CA certificate locations on Linux/Unix
  12370. static const char *ca_paths[] = {
  12371. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  12372. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  12373. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  12374. "/etc/pki/tls/cacert.pem", // OpenELEC
  12375. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  12376. nullptr};
  12377. for (const char **path = ca_paths; *path; ++path) {
  12378. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path);
  12379. if (ret >= 0) {
  12380. loaded = true;
  12381. break;
  12382. }
  12383. }
  12384. // Also try the CA directory
  12385. if (!loaded) {
  12386. static const char *ca_dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  12387. "/etc/pki/tls/certs", // RHEL/CentOS
  12388. "/usr/share/ca-certificates", nullptr};
  12389. for (const char **dir = ca_dirs; *dir; ++dir) {
  12390. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir);
  12391. if (ret >= 0) {
  12392. loaded = true;
  12393. break;
  12394. }
  12395. }
  12396. }
  12397. #endif
  12398. if (loaded) {
  12399. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  12400. }
  12401. return loaded;
  12402. }
  12403. inline bool tls_set_client_cert_pem(tls_ctx_t ctx, const char *cert,
  12404. const char *key, const char *password) {
  12405. if (!ctx || !cert || !key) { return false; }
  12406. auto mctx = static_cast<httplib::MbedTlsContext *>(ctx);
  12407. // Parse certificate
  12408. std::string cert_str(cert);
  12409. int ret = mbedtls_x509_crt_parse(
  12410. &mctx->own_cert,
  12411. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  12412. cert_str.size() + 1);
  12413. if (ret != 0) {
  12414. mbedtls_last_error() = ret;
  12415. return false;
  12416. }
  12417. // Parse private key
  12418. std::string key_str(key);
  12419. const unsigned char *pwd =
  12420. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  12421. size_t pwd_len = password ? strlen(password) : 0;
  12422. #if MBEDTLS_VERSION_MAJOR >= 3
  12423. ret = mbedtls_pk_parse_key(
  12424. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  12425. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  12426. &mctx->ctr_drbg);
  12427. #else
  12428. ret = mbedtls_pk_parse_key(
  12429. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  12430. key_str.size() + 1, pwd, pwd_len);
  12431. #endif
  12432. if (ret != 0) {
  12433. mbedtls_last_error() = ret;
  12434. return false;
  12435. }
  12436. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  12437. if (ret != 0) {
  12438. mbedtls_last_error() = ret;
  12439. return false;
  12440. }
  12441. return true;
  12442. }
  12443. inline bool tls_set_client_cert_file(tls_ctx_t ctx, const char *cert_path,
  12444. const char *key_path,
  12445. const char *password) {
  12446. if (!ctx || !cert_path || !key_path) { return false; }
  12447. auto mctx = static_cast<httplib::MbedTlsContext *>(ctx);
  12448. // Parse certificate file
  12449. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  12450. if (ret != 0) {
  12451. mbedtls_last_error() = ret;
  12452. return false;
  12453. }
  12454. // Parse private key file
  12455. #if MBEDTLS_VERSION_MAJOR >= 3
  12456. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  12457. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  12458. #else
  12459. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  12460. #endif
  12461. if (ret != 0) {
  12462. mbedtls_last_error() = ret;
  12463. return false;
  12464. }
  12465. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  12466. if (ret != 0) {
  12467. mbedtls_last_error() = ret;
  12468. return false;
  12469. }
  12470. return true;
  12471. }
  12472. inline bool tls_set_server_cert_pem(tls_ctx_t ctx, const char *cert,
  12473. const char *key, const char *password) {
  12474. // Same as client cert for Mbed TLS
  12475. return tls_set_client_cert_pem(ctx, cert, key, password);
  12476. }
  12477. inline bool tls_set_server_cert_file(tls_ctx_t ctx, const char *cert_path,
  12478. const char *key_path,
  12479. const char *password) {
  12480. // Same as client cert for Mbed TLS
  12481. return tls_set_client_cert_file(ctx, cert_path, key_path, password);
  12482. }
  12483. inline bool tls_set_client_ca_file(tls_ctx_t ctx, const char *ca_file,
  12484. const char *ca_dir) {
  12485. if (!ctx) { return false; }
  12486. bool success = true;
  12487. if (ca_file && *ca_file) {
  12488. if (!tls_load_ca_file(ctx, ca_file)) { success = false; }
  12489. }
  12490. if (ca_dir && *ca_dir) {
  12491. if (!tls_load_ca_dir(ctx, ca_dir)) { success = false; }
  12492. }
  12493. return success;
  12494. }
  12495. inline void tls_set_verify_client(tls_ctx_t ctx, bool require) {
  12496. if (!ctx) { return; }
  12497. auto mctx = static_cast<httplib::MbedTlsContext *>(ctx);
  12498. mctx->verify_client = require;
  12499. if (require) {
  12500. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  12501. } else {
  12502. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  12503. // is called (matching OpenSSL behavior). Otherwise use NONE.
  12504. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  12505. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  12506. : MBEDTLS_SSL_VERIFY_NONE);
  12507. }
  12508. }
  12509. // Thread-local storage for SNI captured during handshake
  12510. // This is needed because the SNI callback doesn't have a way to pass
  12511. // session-specific data before the session is fully set up
  12512. inline std::string &mbedtls_pending_sni() {
  12513. static thread_local std::string sni;
  12514. return sni;
  12515. }
  12516. // SNI callback for Mbed TLS server to capture client's SNI hostname
  12517. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  12518. const unsigned char *name, size_t name_len) {
  12519. (void)p_ctx;
  12520. (void)ssl;
  12521. // Store SNI name in thread-local storage
  12522. // It will be retrieved and stored in the session after handshake
  12523. if (name && name_len > 0) {
  12524. mbedtls_pending_sni().assign(reinterpret_cast<const char *>(name),
  12525. name_len);
  12526. } else {
  12527. mbedtls_pending_sni().clear();
  12528. }
  12529. return 0; // Accept any SNI
  12530. }
  12531. inline tls_session_t tls_create_session(tls_ctx_t ctx, socket_t sock) {
  12532. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  12533. auto mctx = static_cast<httplib::MbedTlsContext *>(ctx);
  12534. auto session = new (std::nothrow) MbedTlsSession();
  12535. if (!session) { return nullptr; }
  12536. session->sock = sock;
  12537. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  12538. if (ret != 0) {
  12539. mbedtls_last_error() = ret;
  12540. delete session;
  12541. return nullptr;
  12542. }
  12543. // Set BIO callbacks
  12544. mbedtls_ssl_set_bio(&session->ssl, &session->sock, mbedtls_net_send_cb,
  12545. mbedtls_net_recv_cb, nullptr);
  12546. return static_cast<tls_session_t>(session);
  12547. }
  12548. inline void tls_free_session(tls_session_t session) {
  12549. if (session) { delete static_cast<MbedTlsSession *>(session); }
  12550. }
  12551. inline bool tls_set_sni(tls_session_t session, const char *hostname) {
  12552. if (!session || !hostname) { return false; }
  12553. auto msession = static_cast<MbedTlsSession *>(session);
  12554. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  12555. if (ret != 0) {
  12556. mbedtls_last_error() = ret;
  12557. return false;
  12558. }
  12559. msession->hostname = hostname;
  12560. return true;
  12561. }
  12562. inline bool tls_set_hostname(tls_session_t session, const char *hostname) {
  12563. // In Mbed TLS, set_hostname also sets up hostname verification
  12564. return tls_set_sni(session, hostname);
  12565. }
  12566. inline TlsError tls_connect(tls_session_t session) {
  12567. TlsError err;
  12568. if (!session) {
  12569. err.code = ErrorCode::Fatal;
  12570. return err;
  12571. }
  12572. auto msession = static_cast<MbedTlsSession *>(session);
  12573. int ret = mbedtls_ssl_handshake(&msession->ssl);
  12574. if (ret == 0) {
  12575. err.code = ErrorCode::Success;
  12576. } else {
  12577. err.code = map_mbedtls_error(ret, err.sys_errno);
  12578. err.backend_code = static_cast<uint64_t>(-ret);
  12579. mbedtls_last_error() = ret;
  12580. }
  12581. return err;
  12582. }
  12583. inline TlsError tls_accept(tls_session_t session) {
  12584. // Same as connect for Mbed TLS - handshake works for both client and server
  12585. auto result = tls_connect(session);
  12586. // After successful handshake, capture SNI from thread-local storage
  12587. if (result.code == ErrorCode::Success && session) {
  12588. auto msession = static_cast<MbedTlsSession *>(session);
  12589. msession->sni_hostname = std::move(mbedtls_pending_sni());
  12590. mbedtls_pending_sni().clear();
  12591. }
  12592. return result;
  12593. }
  12594. inline bool tls_connect_nonblocking(tls_session_t session, socket_t sock,
  12595. time_t timeout_sec, time_t timeout_usec,
  12596. TlsError *err) {
  12597. if (!session) {
  12598. if (err) { err->code = ErrorCode::Fatal; }
  12599. return false;
  12600. }
  12601. auto msession = static_cast<MbedTlsSession *>(session);
  12602. // Set socket to non-blocking mode
  12603. detail::set_nonblocking(sock, true);
  12604. auto cleanup =
  12605. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  12606. int ret;
  12607. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  12608. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  12609. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  12610. continue;
  12611. }
  12612. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  12613. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  12614. continue;
  12615. }
  12616. }
  12617. // Error or timeout
  12618. if (err) {
  12619. err->code = map_mbedtls_error(ret, err->sys_errno);
  12620. err->backend_code = static_cast<uint64_t>(-ret);
  12621. }
  12622. mbedtls_last_error() = ret;
  12623. return false;
  12624. }
  12625. if (err) { err->code = ErrorCode::Success; }
  12626. return true;
  12627. }
  12628. inline bool tls_accept_nonblocking(tls_session_t session, socket_t sock,
  12629. time_t timeout_sec, time_t timeout_usec,
  12630. TlsError *err) {
  12631. // Same implementation as connect for Mbed TLS
  12632. bool result =
  12633. tls_connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  12634. // After successful handshake, capture SNI from thread-local storage
  12635. if (result && session) {
  12636. auto msession = static_cast<MbedTlsSession *>(session);
  12637. msession->sni_hostname = std::move(mbedtls_pending_sni());
  12638. mbedtls_pending_sni().clear();
  12639. }
  12640. return result;
  12641. }
  12642. inline ssize_t tls_read(tls_session_t session, void *buf, size_t len,
  12643. TlsError &err) {
  12644. if (!session || !buf) {
  12645. err.code = ErrorCode::Fatal;
  12646. return -1;
  12647. }
  12648. auto msession = static_cast<MbedTlsSession *>(session);
  12649. int ret =
  12650. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  12651. if (ret > 0) {
  12652. err.code = ErrorCode::Success;
  12653. return static_cast<ssize_t>(ret);
  12654. }
  12655. if (ret == 0) {
  12656. err.code = ErrorCode::PeerClosed;
  12657. return 0;
  12658. }
  12659. err.code = map_mbedtls_error(ret, err.sys_errno);
  12660. err.backend_code = static_cast<uint64_t>(-ret);
  12661. mbedtls_last_error() = ret;
  12662. return -1;
  12663. }
  12664. inline ssize_t tls_write(tls_session_t session, const void *buf, size_t len,
  12665. TlsError &err) {
  12666. if (!session || !buf) {
  12667. err.code = ErrorCode::Fatal;
  12668. return -1;
  12669. }
  12670. auto msession = static_cast<MbedTlsSession *>(session);
  12671. int ret = mbedtls_ssl_write(&msession->ssl,
  12672. static_cast<const unsigned char *>(buf), len);
  12673. if (ret > 0) {
  12674. err.code = ErrorCode::Success;
  12675. return static_cast<ssize_t>(ret);
  12676. }
  12677. if (ret == 0) {
  12678. err.code = ErrorCode::PeerClosed;
  12679. return 0;
  12680. }
  12681. err.code = map_mbedtls_error(ret, err.sys_errno);
  12682. err.backend_code = static_cast<uint64_t>(-ret);
  12683. mbedtls_last_error() = ret;
  12684. return -1;
  12685. }
  12686. inline int tls_pending(tls_session_t session) {
  12687. if (!session) { return 0; }
  12688. auto msession = static_cast<MbedTlsSession *>(session);
  12689. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  12690. }
  12691. inline void tls_shutdown(tls_session_t session, bool graceful) {
  12692. if (!session) { return; }
  12693. auto msession = static_cast<MbedTlsSession *>(session);
  12694. if (graceful) {
  12695. // Try to send close_notify, but don't block forever
  12696. int ret;
  12697. int attempts = 0;
  12698. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  12699. attempts < 3) {
  12700. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  12701. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  12702. break;
  12703. }
  12704. attempts++;
  12705. }
  12706. }
  12707. }
  12708. inline bool tls_is_peer_closed(tls_session_t session, socket_t sock) {
  12709. if (!session || sock == INVALID_SOCKET) { return true; }
  12710. auto msession = static_cast<MbedTlsSession *>(session);
  12711. // Check if there's already decrypted data available in the TLS buffer
  12712. // If so, the connection is definitely alive
  12713. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  12714. // Set socket to non-blocking to avoid blocking on read
  12715. detail::set_nonblocking(sock, true);
  12716. auto cleanup =
  12717. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  12718. // Try a 1-byte read to check connection status
  12719. // Note: This will consume the byte if data is available, but for the
  12720. // purpose of checking if peer is closed, this should be acceptable
  12721. // since we're only called when we expect the connection might be closing
  12722. unsigned char buf;
  12723. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  12724. // If we got data or WANT_READ (would block), connection is alive
  12725. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  12726. // If we get a peer close notify or a connection reset, the peer is closed
  12727. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  12728. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  12729. }
  12730. inline tls_cert_t tls_get_peer_cert(tls_session_t session) {
  12731. if (!session) { return nullptr; }
  12732. auto msession = static_cast<MbedTlsSession *>(session);
  12733. // Mbed TLS returns a pointer to the peer cert chain, no need to free
  12734. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  12735. return const_cast<mbedtls_x509_crt *>(cert);
  12736. }
  12737. inline void tls_free_cert(tls_cert_t cert) {
  12738. // Mbed TLS: peer certificate is owned by the SSL context, don't free
  12739. (void)cert;
  12740. }
  12741. namespace {
  12742. // Helper function to match hostname with pattern (supports wildcards)
  12743. inline bool match_hostname(const std::string &pattern,
  12744. const std::string &hostname) {
  12745. if (pattern == hostname) { return true; }
  12746. // Wildcard matching: *.example.com matches foo.example.com
  12747. if (pattern.size() > 2 && pattern[0] == '*' && pattern[1] == '.') {
  12748. std::string suffix = pattern.substr(1); // .example.com
  12749. size_t dot_pos = hostname.find('.');
  12750. if (dot_pos != std::string::npos) {
  12751. std::string host_suffix = hostname.substr(dot_pos);
  12752. if (host_suffix == suffix) { return true; }
  12753. }
  12754. }
  12755. return false;
  12756. }
  12757. } // namespace
  12758. // Check if a string is an IPv4 address
  12759. inline bool is_ipv4_address(const std::string &str) {
  12760. int dots = 0;
  12761. for (char c : str) {
  12762. if (c == '.') {
  12763. dots++;
  12764. } else if (!isdigit(static_cast<unsigned char>(c))) {
  12765. return false;
  12766. }
  12767. }
  12768. return dots == 3;
  12769. }
  12770. // Parse IPv4 address string to bytes
  12771. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  12772. int parts[4];
  12773. if (sscanf(str.c_str(), "%d.%d.%d.%d", &parts[0], &parts[1], &parts[2],
  12774. &parts[3]) != 4) {
  12775. return false;
  12776. }
  12777. for (int i = 0; i < 4; i++) {
  12778. if (parts[i] < 0 || parts[i] > 255) return false;
  12779. out[i] = static_cast<unsigned char>(parts[i]);
  12780. }
  12781. return true;
  12782. }
  12783. inline bool tls_verify_hostname(tls_cert_t cert, const char *hostname) {
  12784. if (!cert || !hostname) { return false; }
  12785. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  12786. std::string host_str(hostname);
  12787. // Check if hostname is an IP address
  12788. bool is_ip = is_ipv4_address(host_str);
  12789. unsigned char ip_bytes[4];
  12790. if (is_ip) { parse_ipv4(host_str, ip_bytes); }
  12791. // Check Subject Alternative Names (SAN)
  12792. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  12793. // - DNS names: raw string bytes
  12794. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  12795. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  12796. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  12797. const unsigned char *p = san->buf.p;
  12798. size_t len = san->buf.len;
  12799. if (is_ip) {
  12800. // Check if this SAN is an IPv4 address (4 bytes)
  12801. if (len == 4 && memcmp(p, ip_bytes, 4) == 0) { return true; }
  12802. // Check if this SAN is an IPv6 address (16 bytes) - skip for now
  12803. } else {
  12804. // Check if this SAN is a DNS name (printable ASCII string)
  12805. bool is_dns = len > 0;
  12806. for (size_t i = 0; i < len && is_dns; i++) {
  12807. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  12808. }
  12809. if (is_dns) {
  12810. std::string san_name(reinterpret_cast<const char *>(p), len);
  12811. if (match_hostname(san_name, host_str)) { return true; }
  12812. }
  12813. }
  12814. san = san->next;
  12815. }
  12816. // Fallback: Check Common Name (CN) in subject
  12817. char cn[256];
  12818. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  12819. if (ret > 0) {
  12820. std::string cn_str(cn);
  12821. // Look for "CN=" in the DN string
  12822. size_t cn_pos = cn_str.find("CN=");
  12823. if (cn_pos != std::string::npos) {
  12824. size_t start = cn_pos + 3;
  12825. size_t end = cn_str.find(',', start);
  12826. std::string cn_value =
  12827. cn_str.substr(start, end == std::string::npos ? end : end - start);
  12828. if (match_hostname(cn_value, host_str)) { return true; }
  12829. }
  12830. }
  12831. return false;
  12832. }
  12833. inline long tls_get_verify_result(tls_session_t session) {
  12834. if (!session) { return -1; }
  12835. auto msession = static_cast<MbedTlsSession *>(session);
  12836. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  12837. // Return 0 (X509_V_OK equivalent) if verification passed
  12838. return flags == 0 ? 0 : static_cast<long>(flags);
  12839. }
  12840. inline std::string tls_get_cert_subject_cn(tls_cert_t cert) {
  12841. if (!cert) return "";
  12842. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12843. // Find the CN in the subject
  12844. const mbedtls_x509_name *name = &x509->subject;
  12845. while (name != nullptr) {
  12846. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  12847. return std::string(reinterpret_cast<const char *>(name->val.p),
  12848. name->val.len);
  12849. }
  12850. name = name->next;
  12851. }
  12852. return "";
  12853. }
  12854. inline std::string tls_get_cert_issuer_name(tls_cert_t cert) {
  12855. if (!cert) return "";
  12856. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12857. // Build a human-readable issuer name string
  12858. char buf[512];
  12859. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  12860. if (ret < 0) return "";
  12861. return std::string(buf);
  12862. }
  12863. inline bool tls_get_cert_sans(tls_cert_t cert, std::vector<TlsSanEntry> &sans) {
  12864. sans.clear();
  12865. if (!cert) return false;
  12866. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12867. // Parse the Subject Alternative Name extension
  12868. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  12869. while (cur != nullptr) {
  12870. if (cur->buf.len > 0) {
  12871. // Mbed TLS stores SAN as ASN.1 sequences
  12872. // The tag byte indicates the type
  12873. const unsigned char *p = cur->buf.p;
  12874. size_t len = cur->buf.len;
  12875. // First byte is the tag
  12876. unsigned char tag = *p;
  12877. p++;
  12878. len--;
  12879. // Parse length (simple single-byte length assumed)
  12880. if (len > 0 && *p < 0x80) {
  12881. size_t value_len = *p;
  12882. p++;
  12883. len--;
  12884. if (value_len <= len) {
  12885. TlsSanEntry entry;
  12886. // ASN.1 context tags for GeneralName
  12887. switch (tag & 0x1F) {
  12888. case 2: // dNSName
  12889. entry.type = SanType::DNS;
  12890. entry.value =
  12891. std::string(reinterpret_cast<const char *>(p), value_len);
  12892. break;
  12893. case 7: // iPAddress
  12894. entry.type = SanType::IP;
  12895. if (value_len == 4) {
  12896. // IPv4
  12897. char buf[16];
  12898. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  12899. entry.value = buf;
  12900. } else if (value_len == 16) {
  12901. // IPv6
  12902. char buf[64];
  12903. snprintf(buf, sizeof(buf),
  12904. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  12905. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  12906. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  12907. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  12908. entry.value = buf;
  12909. }
  12910. break;
  12911. case 1: // rfc822Name (email)
  12912. entry.type = SanType::EMAIL;
  12913. entry.value =
  12914. std::string(reinterpret_cast<const char *>(p), value_len);
  12915. break;
  12916. case 6: // uniformResourceIdentifier
  12917. entry.type = SanType::URI;
  12918. entry.value =
  12919. std::string(reinterpret_cast<const char *>(p), value_len);
  12920. break;
  12921. default: entry.type = SanType::OTHER; break;
  12922. }
  12923. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  12924. }
  12925. }
  12926. }
  12927. cur = cur->next;
  12928. }
  12929. return true;
  12930. }
  12931. inline bool tls_get_cert_validity(tls_cert_t cert, time_t &not_before,
  12932. time_t &not_after) {
  12933. if (!cert) return false;
  12934. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12935. // Convert mbedtls_x509_time to time_t
  12936. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  12937. struct tm tm_time = {};
  12938. tm_time.tm_year = t.year - 1900;
  12939. tm_time.tm_mon = t.mon - 1;
  12940. tm_time.tm_mday = t.day;
  12941. tm_time.tm_hour = t.hour;
  12942. tm_time.tm_min = t.min;
  12943. tm_time.tm_sec = t.sec;
  12944. #ifdef _WIN32
  12945. return _mkgmtime(&tm_time);
  12946. #else
  12947. return timegm(&tm_time);
  12948. #endif
  12949. };
  12950. not_before = to_time_t(x509->valid_from);
  12951. not_after = to_time_t(x509->valid_to);
  12952. return true;
  12953. }
  12954. inline std::string tls_get_cert_serial(tls_cert_t cert) {
  12955. if (!cert) return "";
  12956. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  12957. // Convert serial number to hex string
  12958. std::string result;
  12959. result.reserve(x509->serial.len * 2);
  12960. for (size_t i = 0; i < x509->serial.len; i++) {
  12961. char hex[3];
  12962. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  12963. result += hex;
  12964. }
  12965. return result;
  12966. }
  12967. inline const char *tls_get_sni(tls_session_t session) {
  12968. if (!session) return nullptr;
  12969. auto msession = static_cast<MbedTlsSession *>(session);
  12970. // For server: return SNI received from client during handshake
  12971. if (!msession->sni_hostname.empty()) {
  12972. return msession->sni_hostname.c_str();
  12973. }
  12974. // For client: return the hostname set via tls_set_sni
  12975. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  12976. return nullptr;
  12977. }
  12978. inline uint64_t tls_peek_error() {
  12979. // Mbed TLS doesn't have an error queue, return the last error
  12980. return static_cast<uint64_t>(-mbedtls_last_error());
  12981. }
  12982. inline uint64_t tls_get_error() {
  12983. // Mbed TLS doesn't have an error queue, return and clear the last error
  12984. uint64_t err = static_cast<uint64_t>(-mbedtls_last_error());
  12985. mbedtls_last_error() = 0;
  12986. return err;
  12987. }
  12988. inline std::string tls_error_string(uint64_t code) {
  12989. char buf[256];
  12990. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  12991. return std::string(buf);
  12992. }
  12993. inline tls_ca_store_t tls_create_ca_store(const char *pem, size_t len) {
  12994. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  12995. if (!ca_chain) { return nullptr; }
  12996. mbedtls_x509_crt_init(ca_chain);
  12997. // mbedtls_x509_crt_parse expects null-terminated PEM
  12998. int ret = mbedtls_x509_crt_parse(ca_chain,
  12999. reinterpret_cast<const unsigned char *>(pem),
  13000. len + 1); // +1 for null terminator
  13001. if (ret != 0) {
  13002. // Try without +1 in case PEM is already null-terminated
  13003. ret = mbedtls_x509_crt_parse(
  13004. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  13005. if (ret != 0) {
  13006. mbedtls_x509_crt_free(ca_chain);
  13007. delete ca_chain;
  13008. return nullptr;
  13009. }
  13010. }
  13011. return static_cast<tls_ca_store_t>(ca_chain);
  13012. }
  13013. inline void tls_free_ca_store(tls_ca_store_t store) {
  13014. if (store) {
  13015. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  13016. mbedtls_x509_crt_free(ca_chain);
  13017. delete ca_chain;
  13018. }
  13019. }
  13020. inline bool tls_set_ca_store(tls_ctx_t ctx, tls_ca_store_t store) {
  13021. if (!ctx || !store) { return false; }
  13022. auto *mbed_ctx = static_cast<httplib::MbedTlsContext *>(ctx);
  13023. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  13024. // Free existing CA chain
  13025. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  13026. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  13027. // Copy the CA chain (deep copy)
  13028. // Parse from the raw data of the source cert
  13029. mbedtls_x509_crt *src = ca_chain;
  13030. while (src != nullptr) {
  13031. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  13032. src->raw.len);
  13033. if (ret != 0) { return false; }
  13034. src = src->next;
  13035. }
  13036. // Update the SSL config to use the new CA chain
  13037. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  13038. return true;
  13039. }
  13040. inline size_t tls_get_ca_certs(tls_ctx_t ctx, std::vector<tls_cert_t> &certs) {
  13041. certs.clear();
  13042. if (!ctx) { return 0; }
  13043. auto *mbed_ctx = static_cast<httplib::MbedTlsContext *>(ctx);
  13044. // Iterate through the CA chain
  13045. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  13046. while (cert != nullptr && cert->raw.len > 0) {
  13047. // Create a copy of the certificate for the caller
  13048. auto *copy = new mbedtls_x509_crt;
  13049. mbedtls_x509_crt_init(copy);
  13050. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  13051. if (ret == 0) {
  13052. certs.push_back(static_cast<tls_cert_t>(copy));
  13053. } else {
  13054. mbedtls_x509_crt_free(copy);
  13055. delete copy;
  13056. }
  13057. cert = cert->next;
  13058. }
  13059. return certs.size();
  13060. }
  13061. inline std::vector<std::string> tls_get_ca_names(tls_ctx_t ctx) {
  13062. std::vector<std::string> names;
  13063. if (!ctx) { return names; }
  13064. auto *mbed_ctx = static_cast<httplib::MbedTlsContext *>(ctx);
  13065. // Iterate through the CA chain
  13066. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  13067. while (cert != nullptr && cert->raw.len > 0) {
  13068. char buf[512];
  13069. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  13070. if (ret > 0) { names.push_back(buf); }
  13071. cert = cert->next;
  13072. }
  13073. return names;
  13074. }
  13075. inline bool tls_update_server_cert(tls_ctx_t ctx, const char *cert_pem,
  13076. const char *key_pem, const char *password) {
  13077. if (!ctx || !cert_pem || !key_pem) { return false; }
  13078. auto *mbed_ctx = static_cast<httplib::MbedTlsContext *>(ctx);
  13079. // Free existing certificate and key
  13080. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  13081. mbedtls_pk_free(&mbed_ctx->own_key);
  13082. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  13083. mbedtls_pk_init(&mbed_ctx->own_key);
  13084. // Parse certificate PEM
  13085. int ret = mbedtls_x509_crt_parse(
  13086. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  13087. strlen(cert_pem) + 1);
  13088. if (ret != 0) {
  13089. mbedtls_last_error() = ret;
  13090. return false;
  13091. }
  13092. // Parse private key PEM
  13093. #if MBEDTLS_VERSION_MAJOR >= 3
  13094. ret = mbedtls_pk_parse_key(
  13095. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  13096. strlen(key_pem) + 1,
  13097. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  13098. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  13099. &mbed_ctx->ctr_drbg);
  13100. #else
  13101. ret = mbedtls_pk_parse_key(
  13102. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  13103. strlen(key_pem) + 1,
  13104. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  13105. password ? strlen(password) : 0);
  13106. #endif
  13107. if (ret != 0) {
  13108. mbedtls_last_error() = ret;
  13109. return false;
  13110. }
  13111. // Configure SSL to use the new certificate and key
  13112. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  13113. &mbed_ctx->own_key);
  13114. if (ret != 0) {
  13115. mbedtls_last_error() = ret;
  13116. return false;
  13117. }
  13118. return true;
  13119. }
  13120. inline bool tls_update_server_client_ca(tls_ctx_t ctx, const char *ca_pem) {
  13121. if (!ctx || !ca_pem) { return false; }
  13122. auto *mbed_ctx = static_cast<httplib::MbedTlsContext *>(ctx);
  13123. // Free existing CA chain
  13124. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  13125. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  13126. // Parse CA PEM
  13127. int ret = mbedtls_x509_crt_parse(
  13128. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  13129. strlen(ca_pem) + 1);
  13130. if (ret != 0) {
  13131. mbedtls_last_error() = ret;
  13132. return false;
  13133. }
  13134. // Update SSL config to use new CA chain
  13135. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  13136. return true;
  13137. }
  13138. // Thread-local storage for verify callback (MbedTLS)
  13139. inline TlsVerifyCallback &get_mbedtls_verify_callback() {
  13140. static thread_local TlsVerifyCallback callback;
  13141. return callback;
  13142. }
  13143. // MbedTLS verify callback wrapper
  13144. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt, int depth,
  13145. uint32_t *flags) {
  13146. (void)depth;
  13147. auto &callback = get_mbedtls_verify_callback();
  13148. if (!callback) { return 0; } // Continue with default verification
  13149. // data points to the MbedTlsSession
  13150. auto *session = static_cast<MbedTlsSession *>(data);
  13151. // Call user callback
  13152. bool accepted = callback(static_cast<tls_session_t>(session),
  13153. static_cast<tls_cert_t>(crt));
  13154. if (accepted) {
  13155. *flags = 0; // Clear all error flags
  13156. return 0;
  13157. }
  13158. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  13159. }
  13160. inline bool tls_set_verify_callback(tls_ctx_t ctx, TlsVerifyCallback callback) {
  13161. if (!ctx) { return false; }
  13162. auto *mbed_ctx = static_cast<httplib::MbedTlsContext *>(ctx);
  13163. get_mbedtls_verify_callback() = std::move(callback);
  13164. mbed_ctx->has_verify_callback =
  13165. static_cast<bool>(get_mbedtls_verify_callback());
  13166. if (mbed_ctx->has_verify_callback) {
  13167. // Set OPTIONAL mode to ensure callback is called even when verification
  13168. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  13169. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  13170. mbedtls_ssl_conf_verify(&mbed_ctx->conf, mbedtls_verify_callback, nullptr);
  13171. } else {
  13172. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  13173. }
  13174. return true;
  13175. }
  13176. // Thread-local storage for extended verify callback
  13177. inline TlsVerifyCallbackEx &get_mbedtls_verify_callback_ex() {
  13178. static thread_local TlsVerifyCallbackEx callback;
  13179. return callback;
  13180. }
  13181. // Thread-local for depth tracking (Mbed TLS doesn't provide depth directly)
  13182. inline int &get_mbedtls_verify_depth() {
  13183. static thread_local int depth = 0;
  13184. return depth;
  13185. }
  13186. // Mbed TLS extended verify callback wrapper
  13187. inline int mbedtls_verify_callback_ex(void *data, mbedtls_x509_crt *crt,
  13188. int cert_depth, uint32_t *flags) {
  13189. auto &callback = get_mbedtls_verify_callback_ex();
  13190. if (!callback) { return 0; }
  13191. auto *session = static_cast<MbedTlsSession *>(data);
  13192. // Build context
  13193. TlsVerifyContext verify_ctx;
  13194. verify_ctx.session = static_cast<tls_session_t>(session);
  13195. verify_ctx.cert = static_cast<tls_cert_t>(crt);
  13196. verify_ctx.depth = cert_depth;
  13197. verify_ctx.preverify_ok = (*flags == 0);
  13198. verify_ctx.error_code = static_cast<long>(*flags);
  13199. // Convert Mbed TLS flags to error string
  13200. static thread_local char error_buf[256];
  13201. if (*flags != 0) {
  13202. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  13203. verify_ctx.error_string = error_buf;
  13204. } else {
  13205. verify_ctx.error_string = nullptr;
  13206. }
  13207. bool accepted = callback(verify_ctx);
  13208. if (accepted) {
  13209. *flags = 0;
  13210. return 0;
  13211. }
  13212. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  13213. }
  13214. inline bool tls_set_verify_callback_ex(tls_ctx_t ctx,
  13215. TlsVerifyCallbackEx callback) {
  13216. if (!ctx) { return false; }
  13217. auto *mbed_ctx = static_cast<httplib::MbedTlsContext *>(ctx);
  13218. get_mbedtls_verify_callback_ex() = std::move(callback);
  13219. mbed_ctx->has_verify_callback =
  13220. static_cast<bool>(get_mbedtls_verify_callback_ex());
  13221. if (mbed_ctx->has_verify_callback) {
  13222. // Set OPTIONAL mode to ensure callback is called even when verification
  13223. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  13224. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  13225. mbedtls_ssl_conf_verify(&mbed_ctx->conf, mbedtls_verify_callback_ex,
  13226. nullptr);
  13227. } else {
  13228. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  13229. }
  13230. return true;
  13231. }
  13232. inline long tls_get_verify_error(tls_session_t session) {
  13233. if (!session) { return -1; }
  13234. auto *msession = static_cast<MbedTlsSession *>(session);
  13235. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  13236. }
  13237. inline std::string tls_verify_error_string(long error_code) {
  13238. if (error_code == 0) { return ""; }
  13239. char buf[256];
  13240. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  13241. static_cast<uint32_t>(error_code));
  13242. // Remove trailing newline if present
  13243. std::string result(buf);
  13244. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  13245. result.pop_back();
  13246. }
  13247. return result;
  13248. }
  13249. } // namespace tls
  13250. // MbedTlsContext constructor/destructor implementations
  13251. inline MbedTlsContext::MbedTlsContext() {
  13252. mbedtls_ssl_config_init(&conf);
  13253. mbedtls_entropy_init(&entropy);
  13254. mbedtls_ctr_drbg_init(&ctr_drbg);
  13255. mbedtls_x509_crt_init(&ca_chain);
  13256. mbedtls_x509_crt_init(&own_cert);
  13257. mbedtls_pk_init(&own_key);
  13258. }
  13259. inline MbedTlsContext::~MbedTlsContext() {
  13260. mbedtls_pk_free(&own_key);
  13261. mbedtls_x509_crt_free(&own_cert);
  13262. mbedtls_x509_crt_free(&ca_chain);
  13263. mbedtls_ctr_drbg_free(&ctr_drbg);
  13264. mbedtls_entropy_free(&entropy);
  13265. mbedtls_ssl_config_free(&conf);
  13266. }
  13267. inline SSLClient::SSLClient(const std::string &host)
  13268. : SSLClient(host, 443, std::string(), std::string()) {}
  13269. inline SSLClient::SSLClient(const std::string &host, int port)
  13270. : SSLClient(host, port, std::string(), std::string()) {}
  13271. inline SSLClient::SSLClient(const std::string &host, int port,
  13272. const std::string &client_cert_path,
  13273. const std::string &client_key_path,
  13274. const std::string &private_key_password)
  13275. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13276. using namespace tls;
  13277. ctx_ = tls_create_client_context();
  13278. if (!ctx_) { return; }
  13279. // Set minimum TLS version to 1.2
  13280. tls_set_min_version(ctx_, 0x0303); // TLS 1.2
  13281. detail::split(&host_[0], &host_[host_.size()], '.',
  13282. [&](const char *b, const char *e) {
  13283. host_components_.emplace_back(b, e);
  13284. });
  13285. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13286. const char *password =
  13287. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13288. if (!tls_set_client_cert_file(ctx_, client_cert_path.c_str(),
  13289. client_key_path.c_str(), password)) {
  13290. last_backend_error_ = tls_get_error();
  13291. tls_free_context(ctx_);
  13292. ctx_ = nullptr;
  13293. }
  13294. }
  13295. }
  13296. inline SSLClient::SSLClient(const std::string &host, int port,
  13297. const PemMemory &pem)
  13298. : ClientImpl(host, port) {
  13299. using namespace tls;
  13300. ctx_ = tls_create_client_context();
  13301. if (!ctx_) { return; }
  13302. // Set minimum TLS version to 1.2
  13303. tls_set_min_version(ctx_, 0x0303); // TLS 1.2
  13304. detail::split(&host_[0], &host_[host_.size()], '.',
  13305. [&](const char *b, const char *e) {
  13306. host_components_.emplace_back(b, e);
  13307. });
  13308. if (pem.cert_pem && pem.key_pem) {
  13309. if (!tls_set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13310. pem.private_key_password)) {
  13311. last_backend_error_ = tls_get_error();
  13312. tls_free_context(ctx_);
  13313. ctx_ = nullptr;
  13314. }
  13315. }
  13316. }
  13317. inline void SSLClient::set_ca_cert_store(void *ca_cert_store) {
  13318. if (ca_cert_store && ctx_) {
  13319. // tls_set_ca_store takes ownership of ca_cert_store
  13320. tls::tls_set_ca_store(ctx_, ca_cert_store);
  13321. } else if (ca_cert_store) {
  13322. tls::tls_free_ca_store(ca_cert_store);
  13323. }
  13324. }
  13325. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13326. std::size_t size) {
  13327. if (ctx_ && ca_cert && size > 0) {
  13328. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13329. tls::tls_load_ca_pem(ctx_, ca_cert, size);
  13330. }
  13331. }
  13332. inline void
  13333. SSLClient::set_server_certificate_verifier(TlsVerifyCallback verifier) {
  13334. if (!ctx_) { return; }
  13335. tls::tls_set_verify_callback(
  13336. ctx_, [verifier](tls::tls_session_t session, tls::tls_cert_t cert) {
  13337. return verifier(session, cert);
  13338. });
  13339. }
  13340. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13341. using namespace tls;
  13342. // Load system certificates if no CA certs were explicitly set
  13343. if (ca_cert_file_path_.empty() && ca_cert_dir_path_.empty()) {
  13344. tls_load_system_certs(ctx_);
  13345. }
  13346. // Load CA certificates from file/dir if specified
  13347. if (!ca_cert_file_path_.empty()) {
  13348. if (!tls_load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  13349. last_backend_error_ = tls_get_error();
  13350. error = Error::SSLLoadingCerts;
  13351. return false;
  13352. }
  13353. }
  13354. if (!ca_cert_dir_path_.empty()) {
  13355. if (!tls_load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  13356. last_backend_error_ = tls_get_error();
  13357. error = Error::SSLLoadingCerts;
  13358. return false;
  13359. }
  13360. }
  13361. // For IP addresses, we need special handling in mbedTLS:
  13362. // - RFC 6066 prohibits sending IP addresses in SNI
  13363. // - mbedTLS 3.x requires hostname for cert verification (VERIFY_REQUIRED)
  13364. // - Solution: Use VERIFY_OPTIONAL for IP addresses and verify manually
  13365. bool is_ip = detail::is_ip_address(host_);
  13366. if (is_ip && server_certificate_verification_) {
  13367. // Use OPTIONAL mode so mbedTLS doesn't require hostname
  13368. tls_set_verify_client(ctx_, false);
  13369. } else {
  13370. tls_set_verify_client(ctx_, server_certificate_verification_);
  13371. }
  13372. auto session = tls_create_session(ctx_, socket.sock);
  13373. if (!session) {
  13374. last_backend_error_ = tls_get_error();
  13375. error = Error::SSLConnection;
  13376. return false;
  13377. }
  13378. // Use scope_exit to ensure session is freed on error paths
  13379. bool success = false;
  13380. auto session_guard = detail::scope_exit([&] {
  13381. if (!success) { tls_free_session(session); }
  13382. });
  13383. // Set hostname for SNI (only for non-IP addresses per RFC 6066)
  13384. if (!is_ip) {
  13385. if (!tls_set_hostname(session, host_.c_str())) {
  13386. last_backend_error_ = tls_get_error();
  13387. error = Error::SSLConnection;
  13388. return false;
  13389. }
  13390. }
  13391. // Perform TLS handshake
  13392. TlsError tls_err;
  13393. if (!tls_connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13394. connection_timeout_usec_, &tls_err)) {
  13395. last_ssl_error_ = static_cast<int>(tls_err.code);
  13396. last_backend_error_ = tls_err.backend_code;
  13397. // Map TLS error codes to appropriate Error types
  13398. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13399. error = Error::SSLServerVerification;
  13400. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13401. error = Error::SSLServerHostnameVerification;
  13402. } else {
  13403. error = Error::SSLConnection;
  13404. }
  13405. return false;
  13406. }
  13407. // Verify server certificate
  13408. if (server_certificate_verification_) {
  13409. auto verify_result = tls_get_verify_result(session);
  13410. if (verify_result != 0) {
  13411. last_backend_error_ = static_cast<unsigned long>(verify_result);
  13412. error = Error::SSLServerVerification;
  13413. return false;
  13414. }
  13415. auto cert = tls_get_peer_cert(session);
  13416. if (!cert) {
  13417. last_backend_error_ = tls_get_error();
  13418. error = Error::SSLServerVerification;
  13419. return false;
  13420. }
  13421. auto cert_guard = detail::scope_exit([&] { tls_free_cert(cert); });
  13422. if (server_hostname_verification_) {
  13423. if (!tls_verify_hostname(cert, host_.c_str())) {
  13424. // Use a well-known error code for hostname mismatch
  13425. last_backend_error_ = 0x4000A000; // Custom code for hostname mismatch
  13426. error = Error::SSLServerHostnameVerification;
  13427. return false;
  13428. }
  13429. }
  13430. }
  13431. success = true;
  13432. socket.ssl = session;
  13433. return true;
  13434. }
  13435. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  13436. /*
  13437. * SSL/TLS Common Implementation
  13438. */
  13439. inline ClientConnection::~ClientConnection() {
  13440. #ifdef CPPHTTPLIB_SSL_ENABLED
  13441. if (session) {
  13442. tls::tls_shutdown(session, true);
  13443. tls::tls_free_session(session);
  13444. session = nullptr;
  13445. }
  13446. #endif
  13447. if (sock != INVALID_SOCKET) {
  13448. detail::close_socket(sock);
  13449. sock = INVALID_SOCKET;
  13450. }
  13451. }
  13452. #ifdef CPPHTTPLIB_SSL_ENABLED
  13453. namespace detail {
  13454. inline bool is_ip_address(const std::string &host) {
  13455. struct in_addr addr4;
  13456. struct in6_addr addr6;
  13457. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  13458. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  13459. }
  13460. template <typename T>
  13461. inline bool process_server_socket_ssl(
  13462. const std::atomic<socket_t> &svr_sock, tls::tls_session_t session,
  13463. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  13464. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  13465. time_t write_timeout_usec, T callback) {
  13466. return process_server_socket_core(
  13467. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  13468. [&](bool close_connection, bool &connection_closed) {
  13469. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  13470. write_timeout_sec, write_timeout_usec);
  13471. return callback(strm, close_connection, connection_closed);
  13472. });
  13473. }
  13474. template <typename T>
  13475. inline bool process_client_socket_ssl(
  13476. tls::tls_session_t session, socket_t sock, time_t read_timeout_sec,
  13477. time_t read_timeout_usec, time_t write_timeout_sec,
  13478. time_t write_timeout_usec, time_t max_timeout_msec,
  13479. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  13480. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  13481. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  13482. start_time);
  13483. return callback(strm);
  13484. }
  13485. // SSL socket stream implementation
  13486. inline SSLSocketStream::SSLSocketStream(
  13487. socket_t sock, tls::tls_session_t session, time_t read_timeout_sec,
  13488. time_t read_timeout_usec, time_t write_timeout_sec,
  13489. time_t write_timeout_usec, time_t max_timeout_msec,
  13490. std::chrono::time_point<std::chrono::steady_clock> start_time)
  13491. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  13492. read_timeout_usec_(read_timeout_usec),
  13493. write_timeout_sec_(write_timeout_sec),
  13494. write_timeout_usec_(write_timeout_usec),
  13495. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  13496. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13497. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  13498. // Note: tls_create_session() also clears this, but SSLClient currently
  13499. // uses ssl_new() which does not. Until full TLS API migration is complete,
  13500. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  13501. // SSL session was created.
  13502. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  13503. #endif
  13504. }
  13505. inline SSLSocketStream::~SSLSocketStream() = default;
  13506. inline bool SSLSocketStream::is_readable() const {
  13507. return tls::tls_pending(session_) > 0;
  13508. }
  13509. inline bool SSLSocketStream::wait_readable() const {
  13510. if (max_timeout_msec_ <= 0) {
  13511. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  13512. }
  13513. time_t read_timeout_sec;
  13514. time_t read_timeout_usec;
  13515. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  13516. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  13517. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  13518. }
  13519. inline bool SSLSocketStream::wait_writable() const {
  13520. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  13521. is_socket_alive(sock_) && !tls::tls_is_peer_closed(session_, sock_);
  13522. }
  13523. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  13524. if (tls::tls_pending(session_) > 0) {
  13525. tls::TlsError err;
  13526. auto ret = tls::tls_read(session_, ptr, size, err);
  13527. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  13528. error_ = Error::ConnectionClosed;
  13529. }
  13530. return ret;
  13531. } else if (wait_readable()) {
  13532. tls::TlsError err;
  13533. auto ret = tls::tls_read(session_, ptr, size, err);
  13534. if (ret < 0) {
  13535. auto n = 1000;
  13536. #ifdef _WIN32
  13537. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  13538. (err.code == tls::ErrorCode::SyscallError &&
  13539. WSAGetLastError() == WSAETIMEDOUT))) {
  13540. #else
  13541. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  13542. #endif
  13543. if (tls::tls_pending(session_) > 0) {
  13544. return tls::tls_read(session_, ptr, size, err);
  13545. } else if (wait_readable()) {
  13546. std::this_thread::sleep_for(std::chrono::microseconds{10});
  13547. ret = tls::tls_read(session_, ptr, size, err);
  13548. if (ret >= 0) { return ret; }
  13549. } else {
  13550. break;
  13551. }
  13552. }
  13553. assert(ret < 0);
  13554. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  13555. error_ = Error::ConnectionClosed;
  13556. }
  13557. return ret;
  13558. } else {
  13559. error_ = Error::Timeout;
  13560. return -1;
  13561. }
  13562. }
  13563. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  13564. if (wait_writable()) {
  13565. auto handle_size =
  13566. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  13567. tls::TlsError err;
  13568. auto ret = tls::tls_write(session_, ptr, handle_size, err);
  13569. if (ret < 0) {
  13570. auto n = 1000;
  13571. #ifdef _WIN32
  13572. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  13573. (err.code == tls::ErrorCode::SyscallError &&
  13574. WSAGetLastError() == WSAETIMEDOUT))) {
  13575. #else
  13576. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  13577. #endif
  13578. if (wait_writable()) {
  13579. std::this_thread::sleep_for(std::chrono::microseconds{10});
  13580. ret = tls::tls_write(session_, ptr, handle_size, err);
  13581. if (ret >= 0) { return ret; }
  13582. } else {
  13583. break;
  13584. }
  13585. }
  13586. assert(ret < 0);
  13587. }
  13588. return ret;
  13589. }
  13590. return -1;
  13591. }
  13592. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  13593. int &port) const {
  13594. detail::get_remote_ip_and_port(sock_, ip, port);
  13595. }
  13596. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  13597. int &port) const {
  13598. detail::get_local_ip_and_port(sock_, ip, port);
  13599. }
  13600. inline socket_t SSLSocketStream::socket() const { return sock_; }
  13601. inline time_t SSLSocketStream::duration() const {
  13602. return std::chrono::duration_cast<std::chrono::milliseconds>(
  13603. std::chrono::steady_clock::now() - start_time_)
  13604. .count();
  13605. }
  13606. } // namespace detail
  13607. // SSL HTTP server implementation (common for OpenSSL and Mbed TLS)
  13608. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13609. const char *client_ca_cert_file_path,
  13610. const char *client_ca_cert_dir_path,
  13611. const char *private_key_password) {
  13612. using namespace tls;
  13613. ctx_ = tls_create_server_context();
  13614. if (!ctx_) { return; }
  13615. // Load server certificate and private key
  13616. if (!tls_set_server_cert_file(ctx_, cert_path, private_key_path,
  13617. private_key_password)) {
  13618. last_ssl_error_ = static_cast<int>(tls_get_error());
  13619. tls_free_context(ctx_);
  13620. ctx_ = nullptr;
  13621. return;
  13622. }
  13623. // Load client CA certificates for client authentication
  13624. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13625. if (!tls_set_client_ca_file(ctx_, client_ca_cert_file_path,
  13626. client_ca_cert_dir_path)) {
  13627. last_ssl_error_ = static_cast<int>(tls_get_error());
  13628. tls_free_context(ctx_);
  13629. ctx_ = nullptr;
  13630. return;
  13631. }
  13632. // Enable client certificate verification
  13633. tls_set_verify_client(ctx_, true);
  13634. }
  13635. }
  13636. inline SSLServer::SSLServer(const PemMemory &pem) {
  13637. using namespace tls;
  13638. ctx_ = tls_create_server_context();
  13639. if (ctx_) {
  13640. if (!tls_set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13641. pem.private_key_password)) {
  13642. last_ssl_error_ = static_cast<int>(tls_get_error());
  13643. tls_free_context(ctx_);
  13644. ctx_ = nullptr;
  13645. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13646. if (!tls_load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13647. last_ssl_error_ = static_cast<int>(tls_get_error());
  13648. tls_free_context(ctx_);
  13649. ctx_ = nullptr;
  13650. } else {
  13651. tls_set_verify_client(ctx_, true);
  13652. }
  13653. }
  13654. }
  13655. }
  13656. inline SSLServer::SSLServer(
  13657. const std::function<bool(void *ctx)> &setup_callback) {
  13658. using namespace tls;
  13659. ctx_ = tls_create_server_context();
  13660. if (ctx_) {
  13661. if (!setup_callback(ctx_)) {
  13662. tls_free_context(ctx_);
  13663. ctx_ = nullptr;
  13664. }
  13665. }
  13666. }
  13667. inline SSLServer::~SSLServer() {
  13668. if (ctx_) { tls::tls_free_context(ctx_); }
  13669. }
  13670. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13671. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13672. using namespace tls;
  13673. // Create TLS session with mutex protection
  13674. tls_session_t session = nullptr;
  13675. {
  13676. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13677. session = tls_create_session(static_cast<tls_ctx_t>(ctx_), sock);
  13678. }
  13679. if (!session) {
  13680. last_ssl_error_ = static_cast<int>(tls_get_error());
  13681. detail::shutdown_socket(sock);
  13682. detail::close_socket(sock);
  13683. return false;
  13684. }
  13685. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13686. bool handshake_done = false;
  13687. bool ret = false;
  13688. auto cleanup = detail::scope_exit([&] {
  13689. // Shutdown gracefully if handshake succeeded and processing was successful
  13690. if (handshake_done) { tls_shutdown(session, ret); }
  13691. tls_free_session(session);
  13692. detail::shutdown_socket(sock);
  13693. detail::close_socket(sock);
  13694. });
  13695. // Perform TLS accept handshake with timeout
  13696. TlsError tls_err;
  13697. if (!tls_accept_nonblocking(session, sock, read_timeout_sec_,
  13698. read_timeout_usec_, &tls_err)) {
  13699. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13700. // Map TlsError to legacy ssl_error for backward compatibility
  13701. if (tls_err.code == ErrorCode::WantRead) {
  13702. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13703. } else if (tls_err.code == ErrorCode::WantWrite) {
  13704. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13705. } else {
  13706. last_ssl_error_ = SSL_ERROR_SSL;
  13707. }
  13708. #else
  13709. last_ssl_error_ = static_cast<int>(tls_get_error());
  13710. #endif
  13711. return false;
  13712. }
  13713. handshake_done = true;
  13714. std::string remote_addr;
  13715. int remote_port = 0;
  13716. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13717. std::string local_addr;
  13718. int local_port = 0;
  13719. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13720. ret = detail::process_server_socket_ssl(
  13721. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13722. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13723. write_timeout_usec_,
  13724. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13725. return process_request(strm, remote_addr, remote_port, local_addr,
  13726. local_port, close_connection, connection_closed,
  13727. [&](Request &req) { req.ssl = session; });
  13728. });
  13729. return ret;
  13730. }
  13731. inline SSLClient::~SSLClient() {
  13732. if (ctx_) { tls::tls_free_context(ctx_); }
  13733. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13734. // base function rather than the derived function once we get to the
  13735. // base class destructor, and won't free the SSL (causing a leak).
  13736. shutdown_ssl_impl(socket_, true);
  13737. }
  13738. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13739. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13740. shutdown_ssl_impl(socket, shutdown_gracefully);
  13741. }
  13742. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13743. bool shutdown_gracefully) {
  13744. if (socket.sock == INVALID_SOCKET) {
  13745. assert(socket.ssl == nullptr);
  13746. return;
  13747. }
  13748. if (socket.ssl) {
  13749. tls::tls_shutdown(socket.ssl, shutdown_gracefully);
  13750. {
  13751. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13752. tls::tls_free_session(socket.ssl);
  13753. }
  13754. socket.ssl = nullptr;
  13755. }
  13756. assert(socket.ssl == nullptr);
  13757. }
  13758. inline bool SSLClient::process_socket(
  13759. const Socket &socket,
  13760. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13761. std::function<bool(Stream &strm)> callback) {
  13762. assert(socket.ssl);
  13763. return detail::process_client_socket_ssl(
  13764. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13765. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13766. std::move(callback));
  13767. }
  13768. inline bool SSLClient::is_ssl() const { return true; }
  13769. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13770. if (!is_valid()) {
  13771. error = Error::SSLConnection;
  13772. return false;
  13773. }
  13774. return ClientImpl::create_and_connect_socket(socket, error);
  13775. }
  13776. // Assumes that socket_mutex_ is locked and that there are no requests in
  13777. // flight
  13778. inline bool SSLClient::connect_with_proxy(
  13779. Socket &socket,
  13780. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13781. Response &res, bool &success, Error &error) {
  13782. success = true;
  13783. Response proxy_res;
  13784. if (!detail::process_client_socket(
  13785. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13786. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13787. start_time, [&](Stream &strm) {
  13788. Request req2;
  13789. req2.method = "CONNECT";
  13790. req2.path =
  13791. detail::make_host_and_port_string_always_port(host_, port_);
  13792. if (max_timeout_msec_ > 0) {
  13793. req2.start_time_ = std::chrono::steady_clock::now();
  13794. }
  13795. return process_request(strm, req2, proxy_res, false, error);
  13796. })) {
  13797. // Thread-safe to close everything because we are assuming there are no
  13798. // requests in flight
  13799. shutdown_ssl(socket, true);
  13800. shutdown_socket(socket);
  13801. close_socket(socket);
  13802. success = false;
  13803. return false;
  13804. }
  13805. #ifdef CPPHTTPLIB_SSL_ENABLED
  13806. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13807. if (!proxy_digest_auth_username_.empty() &&
  13808. !proxy_digest_auth_password_.empty()) {
  13809. std::map<std::string, std::string> auth;
  13810. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13811. // Close the current socket and create a new one for the authenticated
  13812. // request
  13813. shutdown_ssl(socket, true);
  13814. shutdown_socket(socket);
  13815. close_socket(socket);
  13816. // Create a new socket for the authenticated CONNECT request
  13817. if (!ensure_socket_connection(socket, error)) {
  13818. success = false;
  13819. output_error_log(error, nullptr);
  13820. return false;
  13821. }
  13822. proxy_res = Response();
  13823. if (!detail::process_client_socket(
  13824. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13825. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13826. start_time, [&](Stream &strm) {
  13827. Request req3;
  13828. req3.method = "CONNECT";
  13829. req3.path = detail::make_host_and_port_string_always_port(
  13830. host_, port_);
  13831. req3.headers.insert(detail::make_digest_authentication_header(
  13832. req3, auth, 1, detail::random_string(10),
  13833. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13834. true));
  13835. if (max_timeout_msec_ > 0) {
  13836. req3.start_time_ = std::chrono::steady_clock::now();
  13837. }
  13838. return process_request(strm, req3, proxy_res, false, error);
  13839. })) {
  13840. // Thread-safe to close everything because we are assuming there are
  13841. // no requests in flight
  13842. shutdown_ssl(socket, true);
  13843. shutdown_socket(socket);
  13844. close_socket(socket);
  13845. success = false;
  13846. return false;
  13847. }
  13848. }
  13849. }
  13850. }
  13851. #endif
  13852. // If status code is not 200, proxy request is failed.
  13853. // Set error to ProxyConnection and return proxy response
  13854. // as the response of the request
  13855. if (proxy_res.status != StatusCode::OK_200) {
  13856. error = Error::ProxyConnection;
  13857. output_error_log(error, nullptr);
  13858. res = std::move(proxy_res);
  13859. // Thread-safe to close everything because we are assuming there are
  13860. // no requests in flight
  13861. shutdown_ssl(socket, true);
  13862. shutdown_socket(socket);
  13863. close_socket(socket);
  13864. return false;
  13865. }
  13866. return true;
  13867. }
  13868. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13869. const char *key_pem,
  13870. const char *password) {
  13871. if (!ctx_) { return false; }
  13872. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13873. return tls::tls_update_server_cert(ctx_, cert_pem, key_pem, password);
  13874. }
  13875. inline bool SSLServer::update_client_ca_pem(const char *ca_pem) {
  13876. if (!ctx_) { return false; }
  13877. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13878. return tls::tls_update_server_client_ca(ctx_, ca_pem);
  13879. }
  13880. #endif // CPPHTTPLIB_SSL_ENABLED
  13881. // Universal client implementation
  13882. inline Client::Client(const std::string &scheme_host_port)
  13883. : Client(scheme_host_port, std::string(), std::string()) {}
  13884. inline Client::Client(const std::string &scheme_host_port,
  13885. const std::string &client_cert_path,
  13886. const std::string &client_key_path) {
  13887. const static std::regex re(
  13888. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  13889. std::smatch m;
  13890. if (std::regex_match(scheme_host_port, m, re)) {
  13891. auto scheme = m[1].str();
  13892. #ifdef CPPHTTPLIB_SSL_ENABLED
  13893. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  13894. #else
  13895. if (!scheme.empty() && scheme != "http") {
  13896. #endif
  13897. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13898. std::string msg = "'" + scheme + "' scheme is not supported.";
  13899. throw std::invalid_argument(msg);
  13900. #endif
  13901. return;
  13902. }
  13903. auto is_ssl = scheme == "https";
  13904. auto host = m[2].str();
  13905. if (host.empty()) { host = m[3].str(); }
  13906. auto port_str = m[4].str();
  13907. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  13908. if (is_ssl) {
  13909. #ifdef CPPHTTPLIB_SSL_ENABLED
  13910. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  13911. client_key_path);
  13912. is_ssl_ = is_ssl;
  13913. #endif
  13914. } else {
  13915. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  13916. client_key_path);
  13917. }
  13918. } else {
  13919. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  13920. // if port param below changes.
  13921. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  13922. client_cert_path, client_key_path);
  13923. }
  13924. } // namespace detail
  13925. inline Client::Client(const std::string &host, int port)
  13926. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  13927. inline Client::Client(const std::string &host, int port,
  13928. const std::string &client_cert_path,
  13929. const std::string &client_key_path)
  13930. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  13931. client_key_path)) {}
  13932. inline Client::~Client() = default;
  13933. inline bool Client::is_valid() const {
  13934. return cli_ != nullptr && cli_->is_valid();
  13935. }
  13936. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  13937. return cli_->Get(path, std::move(progress));
  13938. }
  13939. inline Result Client::Get(const std::string &path, const Headers &headers,
  13940. DownloadProgress progress) {
  13941. return cli_->Get(path, headers, std::move(progress));
  13942. }
  13943. inline Result Client::Get(const std::string &path,
  13944. ContentReceiver content_receiver,
  13945. DownloadProgress progress) {
  13946. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  13947. }
  13948. inline Result Client::Get(const std::string &path, const Headers &headers,
  13949. ContentReceiver content_receiver,
  13950. DownloadProgress progress) {
  13951. return cli_->Get(path, headers, std::move(content_receiver),
  13952. std::move(progress));
  13953. }
  13954. inline Result Client::Get(const std::string &path,
  13955. ResponseHandler response_handler,
  13956. ContentReceiver content_receiver,
  13957. DownloadProgress progress) {
  13958. return cli_->Get(path, std::move(response_handler),
  13959. std::move(content_receiver), std::move(progress));
  13960. }
  13961. inline Result Client::Get(const std::string &path, const Headers &headers,
  13962. ResponseHandler response_handler,
  13963. ContentReceiver content_receiver,
  13964. DownloadProgress progress) {
  13965. return cli_->Get(path, headers, std::move(response_handler),
  13966. std::move(content_receiver), std::move(progress));
  13967. }
  13968. inline Result Client::Get(const std::string &path, const Params &params,
  13969. const Headers &headers, DownloadProgress progress) {
  13970. return cli_->Get(path, params, headers, std::move(progress));
  13971. }
  13972. inline Result Client::Get(const std::string &path, const Params &params,
  13973. const Headers &headers,
  13974. ContentReceiver content_receiver,
  13975. DownloadProgress progress) {
  13976. return cli_->Get(path, params, headers, std::move(content_receiver),
  13977. std::move(progress));
  13978. }
  13979. inline Result Client::Get(const std::string &path, const Params &params,
  13980. const Headers &headers,
  13981. ResponseHandler response_handler,
  13982. ContentReceiver content_receiver,
  13983. DownloadProgress progress) {
  13984. return cli_->Get(path, params, headers, std::move(response_handler),
  13985. std::move(content_receiver), std::move(progress));
  13986. }
  13987. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  13988. inline Result Client::Head(const std::string &path, const Headers &headers) {
  13989. return cli_->Head(path, headers);
  13990. }
  13991. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  13992. inline Result Client::Post(const std::string &path, const Headers &headers) {
  13993. return cli_->Post(path, headers);
  13994. }
  13995. inline Result Client::Post(const std::string &path, const char *body,
  13996. size_t content_length,
  13997. const std::string &content_type,
  13998. UploadProgress progress) {
  13999. return cli_->Post(path, body, content_length, content_type, progress);
  14000. }
  14001. inline Result Client::Post(const std::string &path, const Headers &headers,
  14002. const char *body, size_t content_length,
  14003. const std::string &content_type,
  14004. UploadProgress progress) {
  14005. return cli_->Post(path, headers, body, content_length, content_type,
  14006. progress);
  14007. }
  14008. inline Result Client::Post(const std::string &path, const std::string &body,
  14009. const std::string &content_type,
  14010. UploadProgress progress) {
  14011. return cli_->Post(path, body, content_type, progress);
  14012. }
  14013. inline Result Client::Post(const std::string &path, const Headers &headers,
  14014. const std::string &body,
  14015. const std::string &content_type,
  14016. UploadProgress progress) {
  14017. return cli_->Post(path, headers, body, content_type, progress);
  14018. }
  14019. inline Result Client::Post(const std::string &path, size_t content_length,
  14020. ContentProvider content_provider,
  14021. const std::string &content_type,
  14022. UploadProgress progress) {
  14023. return cli_->Post(path, content_length, std::move(content_provider),
  14024. content_type, progress);
  14025. }
  14026. inline Result Client::Post(const std::string &path, size_t content_length,
  14027. ContentProvider content_provider,
  14028. const std::string &content_type,
  14029. ContentReceiver content_receiver,
  14030. UploadProgress progress) {
  14031. return cli_->Post(path, content_length, std::move(content_provider),
  14032. content_type, std::move(content_receiver), progress);
  14033. }
  14034. inline Result Client::Post(const std::string &path,
  14035. ContentProviderWithoutLength content_provider,
  14036. const std::string &content_type,
  14037. UploadProgress progress) {
  14038. return cli_->Post(path, std::move(content_provider), content_type, progress);
  14039. }
  14040. inline Result Client::Post(const std::string &path,
  14041. ContentProviderWithoutLength content_provider,
  14042. const std::string &content_type,
  14043. ContentReceiver content_receiver,
  14044. UploadProgress progress) {
  14045. return cli_->Post(path, std::move(content_provider), content_type,
  14046. std::move(content_receiver), progress);
  14047. }
  14048. inline Result Client::Post(const std::string &path, const Headers &headers,
  14049. size_t content_length,
  14050. ContentProvider content_provider,
  14051. const std::string &content_type,
  14052. UploadProgress progress) {
  14053. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14054. content_type, progress);
  14055. }
  14056. inline Result Client::Post(const std::string &path, const Headers &headers,
  14057. size_t content_length,
  14058. ContentProvider content_provider,
  14059. const std::string &content_type,
  14060. ContentReceiver content_receiver,
  14061. DownloadProgress progress) {
  14062. return cli_->Post(path, headers, content_length, std::move(content_provider),
  14063. content_type, std::move(content_receiver), progress);
  14064. }
  14065. inline Result Client::Post(const std::string &path, const Headers &headers,
  14066. ContentProviderWithoutLength content_provider,
  14067. const std::string &content_type,
  14068. UploadProgress progress) {
  14069. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14070. progress);
  14071. }
  14072. inline Result Client::Post(const std::string &path, const Headers &headers,
  14073. ContentProviderWithoutLength content_provider,
  14074. const std::string &content_type,
  14075. ContentReceiver content_receiver,
  14076. DownloadProgress progress) {
  14077. return cli_->Post(path, headers, std::move(content_provider), content_type,
  14078. std::move(content_receiver), progress);
  14079. }
  14080. inline Result Client::Post(const std::string &path, const Params &params) {
  14081. return cli_->Post(path, params);
  14082. }
  14083. inline Result Client::Post(const std::string &path, const Headers &headers,
  14084. const Params &params) {
  14085. return cli_->Post(path, headers, params);
  14086. }
  14087. inline Result Client::Post(const std::string &path,
  14088. const UploadFormDataItems &items,
  14089. UploadProgress progress) {
  14090. return cli_->Post(path, items, progress);
  14091. }
  14092. inline Result Client::Post(const std::string &path, const Headers &headers,
  14093. const UploadFormDataItems &items,
  14094. UploadProgress progress) {
  14095. return cli_->Post(path, headers, items, progress);
  14096. }
  14097. inline Result Client::Post(const std::string &path, const Headers &headers,
  14098. const UploadFormDataItems &items,
  14099. const std::string &boundary,
  14100. UploadProgress progress) {
  14101. return cli_->Post(path, headers, items, boundary, progress);
  14102. }
  14103. inline Result Client::Post(const std::string &path, const Headers &headers,
  14104. const UploadFormDataItems &items,
  14105. const FormDataProviderItems &provider_items,
  14106. UploadProgress progress) {
  14107. return cli_->Post(path, headers, items, provider_items, progress);
  14108. }
  14109. inline Result Client::Post(const std::string &path, const Headers &headers,
  14110. const std::string &body,
  14111. const std::string &content_type,
  14112. ContentReceiver content_receiver,
  14113. DownloadProgress progress) {
  14114. return cli_->Post(path, headers, body, content_type,
  14115. std::move(content_receiver), progress);
  14116. }
  14117. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  14118. inline Result Client::Put(const std::string &path, const Headers &headers) {
  14119. return cli_->Put(path, headers);
  14120. }
  14121. inline Result Client::Put(const std::string &path, const char *body,
  14122. size_t content_length,
  14123. const std::string &content_type,
  14124. UploadProgress progress) {
  14125. return cli_->Put(path, body, content_length, content_type, progress);
  14126. }
  14127. inline Result Client::Put(const std::string &path, const Headers &headers,
  14128. const char *body, size_t content_length,
  14129. const std::string &content_type,
  14130. UploadProgress progress) {
  14131. return cli_->Put(path, headers, body, content_length, content_type, progress);
  14132. }
  14133. inline Result Client::Put(const std::string &path, const std::string &body,
  14134. const std::string &content_type,
  14135. UploadProgress progress) {
  14136. return cli_->Put(path, body, content_type, progress);
  14137. }
  14138. inline Result Client::Put(const std::string &path, const Headers &headers,
  14139. const std::string &body,
  14140. const std::string &content_type,
  14141. UploadProgress progress) {
  14142. return cli_->Put(path, headers, body, content_type, progress);
  14143. }
  14144. inline Result Client::Put(const std::string &path, size_t content_length,
  14145. ContentProvider content_provider,
  14146. const std::string &content_type,
  14147. UploadProgress progress) {
  14148. return cli_->Put(path, content_length, std::move(content_provider),
  14149. content_type, progress);
  14150. }
  14151. inline Result Client::Put(const std::string &path, size_t content_length,
  14152. ContentProvider content_provider,
  14153. const std::string &content_type,
  14154. ContentReceiver content_receiver,
  14155. UploadProgress progress) {
  14156. return cli_->Put(path, content_length, std::move(content_provider),
  14157. content_type, std::move(content_receiver), progress);
  14158. }
  14159. inline Result Client::Put(const std::string &path,
  14160. ContentProviderWithoutLength content_provider,
  14161. const std::string &content_type,
  14162. UploadProgress progress) {
  14163. return cli_->Put(path, std::move(content_provider), content_type, progress);
  14164. }
  14165. inline Result Client::Put(const std::string &path,
  14166. ContentProviderWithoutLength content_provider,
  14167. const std::string &content_type,
  14168. ContentReceiver content_receiver,
  14169. UploadProgress progress) {
  14170. return cli_->Put(path, std::move(content_provider), content_type,
  14171. std::move(content_receiver), progress);
  14172. }
  14173. inline Result Client::Put(const std::string &path, const Headers &headers,
  14174. size_t content_length,
  14175. ContentProvider content_provider,
  14176. const std::string &content_type,
  14177. UploadProgress progress) {
  14178. return cli_->Put(path, headers, content_length, std::move(content_provider),
  14179. content_type, progress);
  14180. }
  14181. inline Result Client::Put(const std::string &path, const Headers &headers,
  14182. size_t content_length,
  14183. ContentProvider content_provider,
  14184. const std::string &content_type,
  14185. ContentReceiver content_receiver,
  14186. UploadProgress progress) {
  14187. return cli_->Put(path, headers, content_length, std::move(content_provider),
  14188. content_type, std::move(content_receiver), progress);
  14189. }
  14190. inline Result Client::Put(const std::string &path, const Headers &headers,
  14191. ContentProviderWithoutLength content_provider,
  14192. const std::string &content_type,
  14193. UploadProgress progress) {
  14194. return cli_->Put(path, headers, std::move(content_provider), content_type,
  14195. progress);
  14196. }
  14197. inline Result Client::Put(const std::string &path, const Headers &headers,
  14198. ContentProviderWithoutLength content_provider,
  14199. const std::string &content_type,
  14200. ContentReceiver content_receiver,
  14201. UploadProgress progress) {
  14202. return cli_->Put(path, headers, std::move(content_provider), content_type,
  14203. std::move(content_receiver), progress);
  14204. }
  14205. inline Result Client::Put(const std::string &path, const Params &params) {
  14206. return cli_->Put(path, params);
  14207. }
  14208. inline Result Client::Put(const std::string &path, const Headers &headers,
  14209. const Params &params) {
  14210. return cli_->Put(path, headers, params);
  14211. }
  14212. inline Result Client::Put(const std::string &path,
  14213. const UploadFormDataItems &items,
  14214. UploadProgress progress) {
  14215. return cli_->Put(path, items, progress);
  14216. }
  14217. inline Result Client::Put(const std::string &path, const Headers &headers,
  14218. const UploadFormDataItems &items,
  14219. UploadProgress progress) {
  14220. return cli_->Put(path, headers, items, progress);
  14221. }
  14222. inline Result Client::Put(const std::string &path, const Headers &headers,
  14223. const UploadFormDataItems &items,
  14224. const std::string &boundary,
  14225. UploadProgress progress) {
  14226. return cli_->Put(path, headers, items, boundary, progress);
  14227. }
  14228. inline Result Client::Put(const std::string &path, const Headers &headers,
  14229. const UploadFormDataItems &items,
  14230. const FormDataProviderItems &provider_items,
  14231. UploadProgress progress) {
  14232. return cli_->Put(path, headers, items, provider_items, progress);
  14233. }
  14234. inline Result Client::Put(const std::string &path, const Headers &headers,
  14235. const std::string &body,
  14236. const std::string &content_type,
  14237. ContentReceiver content_receiver,
  14238. DownloadProgress progress) {
  14239. return cli_->Put(path, headers, body, content_type, content_receiver,
  14240. progress);
  14241. }
  14242. inline Result Client::Patch(const std::string &path) {
  14243. return cli_->Patch(path);
  14244. }
  14245. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  14246. return cli_->Patch(path, headers);
  14247. }
  14248. inline Result Client::Patch(const std::string &path, const char *body,
  14249. size_t content_length,
  14250. const std::string &content_type,
  14251. UploadProgress progress) {
  14252. return cli_->Patch(path, body, content_length, content_type, progress);
  14253. }
  14254. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14255. const char *body, size_t content_length,
  14256. const std::string &content_type,
  14257. UploadProgress progress) {
  14258. return cli_->Patch(path, headers, body, content_length, content_type,
  14259. progress);
  14260. }
  14261. inline Result Client::Patch(const std::string &path, const std::string &body,
  14262. const std::string &content_type,
  14263. UploadProgress progress) {
  14264. return cli_->Patch(path, body, content_type, progress);
  14265. }
  14266. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14267. const std::string &body,
  14268. const std::string &content_type,
  14269. UploadProgress progress) {
  14270. return cli_->Patch(path, headers, body, content_type, progress);
  14271. }
  14272. inline Result Client::Patch(const std::string &path, size_t content_length,
  14273. ContentProvider content_provider,
  14274. const std::string &content_type,
  14275. UploadProgress progress) {
  14276. return cli_->Patch(path, content_length, std::move(content_provider),
  14277. content_type, progress);
  14278. }
  14279. inline Result Client::Patch(const std::string &path, size_t content_length,
  14280. ContentProvider content_provider,
  14281. const std::string &content_type,
  14282. ContentReceiver content_receiver,
  14283. UploadProgress progress) {
  14284. return cli_->Patch(path, content_length, std::move(content_provider),
  14285. content_type, std::move(content_receiver), progress);
  14286. }
  14287. inline Result Client::Patch(const std::string &path,
  14288. ContentProviderWithoutLength content_provider,
  14289. const std::string &content_type,
  14290. UploadProgress progress) {
  14291. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  14292. }
  14293. inline Result Client::Patch(const std::string &path,
  14294. ContentProviderWithoutLength content_provider,
  14295. const std::string &content_type,
  14296. ContentReceiver content_receiver,
  14297. UploadProgress progress) {
  14298. return cli_->Patch(path, std::move(content_provider), content_type,
  14299. std::move(content_receiver), progress);
  14300. }
  14301. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14302. size_t content_length,
  14303. ContentProvider content_provider,
  14304. const std::string &content_type,
  14305. UploadProgress progress) {
  14306. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  14307. content_type, progress);
  14308. }
  14309. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14310. size_t content_length,
  14311. ContentProvider content_provider,
  14312. const std::string &content_type,
  14313. ContentReceiver content_receiver,
  14314. UploadProgress progress) {
  14315. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  14316. content_type, std::move(content_receiver), progress);
  14317. }
  14318. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14319. ContentProviderWithoutLength content_provider,
  14320. const std::string &content_type,
  14321. UploadProgress progress) {
  14322. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  14323. progress);
  14324. }
  14325. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14326. ContentProviderWithoutLength content_provider,
  14327. const std::string &content_type,
  14328. ContentReceiver content_receiver,
  14329. UploadProgress progress) {
  14330. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  14331. std::move(content_receiver), progress);
  14332. }
  14333. inline Result Client::Patch(const std::string &path, const Params &params) {
  14334. return cli_->Patch(path, params);
  14335. }
  14336. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14337. const Params &params) {
  14338. return cli_->Patch(path, headers, params);
  14339. }
  14340. inline Result Client::Patch(const std::string &path,
  14341. const UploadFormDataItems &items,
  14342. UploadProgress progress) {
  14343. return cli_->Patch(path, items, progress);
  14344. }
  14345. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14346. const UploadFormDataItems &items,
  14347. UploadProgress progress) {
  14348. return cli_->Patch(path, headers, items, progress);
  14349. }
  14350. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14351. const UploadFormDataItems &items,
  14352. const std::string &boundary,
  14353. UploadProgress progress) {
  14354. return cli_->Patch(path, headers, items, boundary, progress);
  14355. }
  14356. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14357. const UploadFormDataItems &items,
  14358. const FormDataProviderItems &provider_items,
  14359. UploadProgress progress) {
  14360. return cli_->Patch(path, headers, items, provider_items, progress);
  14361. }
  14362. inline Result Client::Patch(const std::string &path, const Headers &headers,
  14363. const std::string &body,
  14364. const std::string &content_type,
  14365. ContentReceiver content_receiver,
  14366. DownloadProgress progress) {
  14367. return cli_->Patch(path, headers, body, content_type, content_receiver,
  14368. progress);
  14369. }
  14370. inline Result Client::Delete(const std::string &path,
  14371. DownloadProgress progress) {
  14372. return cli_->Delete(path, progress);
  14373. }
  14374. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14375. DownloadProgress progress) {
  14376. return cli_->Delete(path, headers, progress);
  14377. }
  14378. inline Result Client::Delete(const std::string &path, const char *body,
  14379. size_t content_length,
  14380. const std::string &content_type,
  14381. DownloadProgress progress) {
  14382. return cli_->Delete(path, body, content_length, content_type, progress);
  14383. }
  14384. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14385. const char *body, size_t content_length,
  14386. const std::string &content_type,
  14387. DownloadProgress progress) {
  14388. return cli_->Delete(path, headers, body, content_length, content_type,
  14389. progress);
  14390. }
  14391. inline Result Client::Delete(const std::string &path, const std::string &body,
  14392. const std::string &content_type,
  14393. DownloadProgress progress) {
  14394. return cli_->Delete(path, body, content_type, progress);
  14395. }
  14396. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14397. const std::string &body,
  14398. const std::string &content_type,
  14399. DownloadProgress progress) {
  14400. return cli_->Delete(path, headers, body, content_type, progress);
  14401. }
  14402. inline Result Client::Delete(const std::string &path, const Params &params,
  14403. DownloadProgress progress) {
  14404. return cli_->Delete(path, params, progress);
  14405. }
  14406. inline Result Client::Delete(const std::string &path, const Headers &headers,
  14407. const Params &params, DownloadProgress progress) {
  14408. return cli_->Delete(path, headers, params, progress);
  14409. }
  14410. inline Result Client::Options(const std::string &path) {
  14411. return cli_->Options(path);
  14412. }
  14413. inline Result Client::Options(const std::string &path, const Headers &headers) {
  14414. return cli_->Options(path, headers);
  14415. }
  14416. inline ClientImpl::StreamHandle
  14417. Client::open_stream(const std::string &method, const std::string &path,
  14418. const Params &params, const Headers &headers,
  14419. const std::string &body, const std::string &content_type) {
  14420. return cli_->open_stream(method, path, params, headers, body, content_type);
  14421. }
  14422. inline bool Client::send(Request &req, Response &res, Error &error) {
  14423. return cli_->send(req, res, error);
  14424. }
  14425. inline Result Client::send(const Request &req) { return cli_->send(req); }
  14426. inline void Client::stop() { cli_->stop(); }
  14427. inline std::string Client::host() const { return cli_->host(); }
  14428. inline int Client::port() const { return cli_->port(); }
  14429. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  14430. inline socket_t Client::socket() const { return cli_->socket(); }
  14431. inline void
  14432. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  14433. cli_->set_hostname_addr_map(std::move(addr_map));
  14434. }
  14435. inline void Client::set_default_headers(Headers headers) {
  14436. cli_->set_default_headers(std::move(headers));
  14437. }
  14438. inline void Client::set_header_writer(
  14439. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  14440. cli_->set_header_writer(writer);
  14441. }
  14442. inline void Client::set_address_family(int family) {
  14443. cli_->set_address_family(family);
  14444. }
  14445. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  14446. inline void Client::set_socket_options(SocketOptions socket_options) {
  14447. cli_->set_socket_options(std::move(socket_options));
  14448. }
  14449. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  14450. cli_->set_connection_timeout(sec, usec);
  14451. }
  14452. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  14453. cli_->set_read_timeout(sec, usec);
  14454. }
  14455. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  14456. cli_->set_write_timeout(sec, usec);
  14457. }
  14458. inline void Client::set_basic_auth(const std::string &username,
  14459. const std::string &password) {
  14460. cli_->set_basic_auth(username, password);
  14461. }
  14462. inline void Client::set_bearer_token_auth(const std::string &token) {
  14463. cli_->set_bearer_token_auth(token);
  14464. }
  14465. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  14466. inline void Client::set_follow_location(bool on) {
  14467. cli_->set_follow_location(on);
  14468. }
  14469. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  14470. [[deprecated("Use set_path_encode instead")]]
  14471. inline void Client::set_url_encode(bool on) {
  14472. cli_->set_path_encode(on);
  14473. }
  14474. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  14475. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  14476. inline void Client::set_interface(const std::string &intf) {
  14477. cli_->set_interface(intf);
  14478. }
  14479. inline void Client::set_proxy(const std::string &host, int port) {
  14480. cli_->set_proxy(host, port);
  14481. }
  14482. inline void Client::set_proxy_basic_auth(const std::string &username,
  14483. const std::string &password) {
  14484. cli_->set_proxy_basic_auth(username, password);
  14485. }
  14486. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  14487. cli_->set_proxy_bearer_token_auth(token);
  14488. }
  14489. inline void Client::set_logger(Logger logger) {
  14490. cli_->set_logger(std::move(logger));
  14491. }
  14492. inline void Client::set_error_logger(ErrorLogger error_logger) {
  14493. cli_->set_error_logger(std::move(error_logger));
  14494. }
  14495. #ifdef CPPHTTPLIB_SSL_ENABLED
  14496. inline void Client::set_digest_auth(const std::string &username,
  14497. const std::string &password) {
  14498. cli_->set_digest_auth(username, password);
  14499. }
  14500. inline void Client::set_proxy_digest_auth(const std::string &username,
  14501. const std::string &password) {
  14502. cli_->set_proxy_digest_auth(username, password);
  14503. }
  14504. inline void Client::enable_server_certificate_verification(bool enabled) {
  14505. cli_->enable_server_certificate_verification(enabled);
  14506. }
  14507. inline void Client::enable_server_hostname_verification(bool enabled) {
  14508. cli_->enable_server_hostname_verification(enabled);
  14509. }
  14510. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14511. const std::string &ca_cert_dir_path) {
  14512. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14513. }
  14514. inline void Client::set_ca_cert_store(void *ca_cert_store) {
  14515. if (is_ssl_) {
  14516. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14517. } else if (ca_cert_store) {
  14518. tls::tls_free_ca_store(ca_cert_store);
  14519. }
  14520. }
  14521. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14522. set_ca_cert_store(tls::tls_create_ca_store(ca_cert, size));
  14523. }
  14524. inline void
  14525. Client::set_server_certificate_verifier(TlsVerifyCallback verifier) {
  14526. if (is_ssl_) {
  14527. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14528. std::move(verifier));
  14529. }
  14530. }
  14531. inline void *Client::tls_context() const {
  14532. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14533. return nullptr;
  14534. }
  14535. #endif // CPPHTTPLIB_SSL_ENABLED
  14536. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14537. inline SSL_CTX *Client::ssl_context() const {
  14538. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  14539. return nullptr;
  14540. }
  14541. inline void Client::set_server_certificate_verifier(
  14542. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  14543. cli_->set_server_certificate_verifier(verifier);
  14544. }
  14545. inline long Client::get_openssl_verify_result() const {
  14546. if (is_ssl_) {
  14547. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  14548. }
  14549. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  14550. }
  14551. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  14552. // ----------------------------------------------------------------------------
  14553. } // namespace httplib
  14554. #endif // CPPHTTPLIB_HTTPLIB_H