httplib.h 568 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220
  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.32.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x002000"
  11. /*
  12. * Platform compatibility check
  13. */
  14. #if defined(_WIN32) && !defined(_WIN64)
  15. #if defined(_MSC_VER)
  16. #pragma message( \
  17. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler.")
  18. #else
  19. #warning \
  20. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler."
  21. #endif
  22. #elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ < 8
  23. #warning \
  24. "cpp-httplib doesn't support 32-bit platforms. Please use a 64-bit compiler."
  25. #elif defined(__SIZEOF_SIZE_T__) && __SIZEOF_SIZE_T__ < 8
  26. #warning \
  27. "cpp-httplib doesn't support platforms where size_t is less than 64 bits."
  28. #endif
  29. #ifdef _WIN32
  30. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  31. #error \
  32. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  33. #endif
  34. #endif
  35. /*
  36. * Configuration
  37. */
  38. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  39. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  40. #endif
  41. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  42. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  43. #endif
  44. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  45. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  46. #endif
  47. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  60. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  61. #endif
  62. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  63. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  64. #endif
  65. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  66. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  67. #endif
  68. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  69. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  70. #endif
  71. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  72. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  73. #endif
  74. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  75. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  78. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  79. #endif
  80. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  81. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  82. #endif
  83. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  84. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  85. #endif
  86. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  87. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  88. #endif
  89. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  90. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  91. #endif
  92. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  93. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  94. #endif
  95. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  96. #ifdef _WIN32
  97. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  98. #else
  99. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  100. #endif
  101. #endif
  102. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  103. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  106. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  107. #endif
  108. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  109. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  110. #endif
  111. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  112. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  113. #endif
  114. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  115. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  116. #endif
  117. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  118. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 * 1024 * 1024) // 100MB
  119. #endif
  120. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  121. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  122. #endif
  123. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  124. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  125. #endif
  126. #ifndef CPPHTTPLIB_TCP_NODELAY
  127. #define CPPHTTPLIB_TCP_NODELAY false
  128. #endif
  129. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  130. #define CPPHTTPLIB_IPV6_V6ONLY false
  131. #endif
  132. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  133. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  134. #endif
  135. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  136. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  137. #endif
  138. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  139. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  140. #endif
  141. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  142. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  143. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  144. ? std::thread::hardware_concurrency() - 1 \
  145. : 0))
  146. #endif
  147. #ifndef CPPHTTPLIB_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 <cstdlib>
  247. #include <cstring>
  248. #include <errno.h>
  249. #include <exception>
  250. #include <fcntl.h>
  251. #include <functional>
  252. #include <iomanip>
  253. #include <iostream>
  254. #include <list>
  255. #include <map>
  256. #include <memory>
  257. #include <mutex>
  258. #include <random>
  259. #include <regex>
  260. #include <set>
  261. #include <sstream>
  262. #include <string>
  263. #include <sys/stat.h>
  264. #include <system_error>
  265. #include <thread>
  266. #include <unordered_map>
  267. #include <unordered_set>
  268. #include <utility>
  269. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  270. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  271. #if TARGET_OS_MAC
  272. #include <CFNetwork/CFHost.h>
  273. #include <CoreFoundation/CoreFoundation.h>
  274. #endif
  275. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO or
  276. // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  277. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  278. #ifdef _WIN32
  279. #include <wincrypt.h>
  280. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  281. // used
  282. #undef X509_NAME
  283. #undef X509_CERT_PAIR
  284. #undef X509_EXTENSIONS
  285. #undef PKCS7_SIGNER_INFO
  286. #ifdef _MSC_VER
  287. #pragma comment(lib, "crypt32.lib")
  288. #endif
  289. #endif // _WIN32
  290. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  291. #if TARGET_OS_MAC
  292. #include <Security/Security.h>
  293. #endif
  294. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  295. #include <openssl/err.h>
  296. #include <openssl/evp.h>
  297. #include <openssl/ssl.h>
  298. #include <openssl/x509v3.h>
  299. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  300. #include <openssl/applink.c>
  301. #endif
  302. #include <iostream>
  303. #include <sstream>
  304. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  305. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  306. #error Please use OpenSSL or a current version of BoringSSL
  307. #endif
  308. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  309. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  310. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  311. #endif
  312. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  313. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  314. #include <mbedtls/ctr_drbg.h>
  315. #include <mbedtls/entropy.h>
  316. #include <mbedtls/error.h>
  317. #include <mbedtls/md5.h>
  318. #include <mbedtls/net_sockets.h>
  319. #include <mbedtls/oid.h>
  320. #include <mbedtls/pk.h>
  321. #include <mbedtls/sha1.h>
  322. #include <mbedtls/sha256.h>
  323. #include <mbedtls/sha512.h>
  324. #include <mbedtls/ssl.h>
  325. #include <mbedtls/x509_crt.h>
  326. #ifdef _WIN32
  327. #include <wincrypt.h>
  328. #ifdef _MSC_VER
  329. #pragma comment(lib, "crypt32.lib")
  330. #endif
  331. #endif // _WIN32
  332. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  333. #if TARGET_OS_MAC
  334. #include <Security/Security.h>
  335. #endif
  336. #endif // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  337. // Mbed TLS 3.x API compatibility
  338. #if MBEDTLS_VERSION_MAJOR >= 3
  339. #define CPPHTTPLIB_MBEDTLS_V3
  340. #endif
  341. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  342. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  343. // This simplifies conditional compilation when adding new backends (e.g.,
  344. // wolfSSL)
  345. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  346. #define CPPHTTPLIB_SSL_ENABLED
  347. #endif
  348. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  349. #include <zlib.h>
  350. #endif
  351. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  352. #include <brotli/decode.h>
  353. #include <brotli/encode.h>
  354. #endif
  355. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  356. #include <zstd.h>
  357. #endif
  358. /*
  359. * Declaration
  360. */
  361. namespace httplib {
  362. namespace detail {
  363. /*
  364. * Backport std::make_unique from C++14.
  365. *
  366. * NOTE: This code came up with the following stackoverflow post:
  367. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  368. *
  369. */
  370. template <class T, class... Args>
  371. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  372. make_unique(Args &&...args) {
  373. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  374. }
  375. template <class T>
  376. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  377. make_unique(std::size_t n) {
  378. typedef typename std::remove_extent<T>::type RT;
  379. return std::unique_ptr<T>(new RT[n]);
  380. }
  381. namespace case_ignore {
  382. inline unsigned char to_lower(int c) {
  383. const static unsigned char table[256] = {
  384. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  385. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  386. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  387. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  388. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  389. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  390. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  391. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  392. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  393. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  394. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  395. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  396. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  397. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  398. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  399. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  400. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  401. 255,
  402. };
  403. return table[(unsigned char)(char)c];
  404. }
  405. inline bool equal(const std::string &a, const std::string &b) {
  406. return a.size() == b.size() &&
  407. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  408. return to_lower(ca) == to_lower(cb);
  409. });
  410. }
  411. struct equal_to {
  412. bool operator()(const std::string &a, const std::string &b) const {
  413. return equal(a, b);
  414. }
  415. };
  416. struct hash {
  417. size_t operator()(const std::string &key) const {
  418. return hash_core(key.data(), key.size(), 0);
  419. }
  420. size_t hash_core(const char *s, size_t l, size_t h) const {
  421. return (l == 0) ? h
  422. : hash_core(s + 1, l - 1,
  423. // Unsets the 6 high bits of h, therefore no
  424. // overflow happens
  425. (((std::numeric_limits<size_t>::max)() >> 6) &
  426. h * 33) ^
  427. static_cast<unsigned char>(to_lower(*s)));
  428. }
  429. };
  430. template <typename T>
  431. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  432. detail::case_ignore::equal_to>;
  433. } // namespace case_ignore
  434. // This is based on
  435. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  436. struct scope_exit {
  437. explicit scope_exit(std::function<void(void)> &&f)
  438. : exit_function(std::move(f)), execute_on_destruction{true} {}
  439. scope_exit(scope_exit &&rhs) noexcept
  440. : exit_function(std::move(rhs.exit_function)),
  441. execute_on_destruction{rhs.execute_on_destruction} {
  442. rhs.release();
  443. }
  444. ~scope_exit() {
  445. if (execute_on_destruction) { this->exit_function(); }
  446. }
  447. void release() { this->execute_on_destruction = false; }
  448. private:
  449. scope_exit(const scope_exit &) = delete;
  450. void operator=(const scope_exit &) = delete;
  451. scope_exit &operator=(scope_exit &&) = delete;
  452. std::function<void(void)> exit_function;
  453. bool execute_on_destruction;
  454. };
  455. // Simple from_chars implementation for integer and double types (C++17
  456. // substitute)
  457. template <typename T> struct from_chars_result {
  458. const char *ptr;
  459. std::errc ec;
  460. };
  461. template <typename T>
  462. inline from_chars_result<T> from_chars(const char *first, const char *last,
  463. T &value, int base = 10) {
  464. value = 0;
  465. const char *p = first;
  466. bool negative = false;
  467. if (p != last && *p == '-') {
  468. negative = true;
  469. ++p;
  470. }
  471. if (p == last) { return {first, std::errc::invalid_argument}; }
  472. T result = 0;
  473. for (; p != last; ++p) {
  474. char c = *p;
  475. int digit = -1;
  476. if ('0' <= c && c <= '9') {
  477. digit = c - '0';
  478. } else if ('a' <= c && c <= 'z') {
  479. digit = c - 'a' + 10;
  480. } else if ('A' <= c && c <= 'Z') {
  481. digit = c - 'A' + 10;
  482. } else {
  483. break;
  484. }
  485. if (digit < 0 || digit >= base) { break; }
  486. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  487. return {p, std::errc::result_out_of_range};
  488. }
  489. result = result * base + digit;
  490. }
  491. if (p == first || (negative && p == first + 1)) {
  492. return {first, std::errc::invalid_argument};
  493. }
  494. value = negative ? -result : result;
  495. return {p, std::errc{}};
  496. }
  497. // from_chars for double (simple wrapper for strtod)
  498. inline from_chars_result<double> from_chars(const char *first, const char *last,
  499. double &value) {
  500. std::string s(first, last);
  501. char *endptr = nullptr;
  502. errno = 0;
  503. value = std::strtod(s.c_str(), &endptr);
  504. if (endptr == s.c_str()) { return {first, std::errc::invalid_argument}; }
  505. if (errno == ERANGE) {
  506. return {first + (endptr - s.c_str()), std::errc::result_out_of_range};
  507. }
  508. return {first + (endptr - s.c_str()), std::errc{}};
  509. }
  510. } // namespace detail
  511. enum SSLVerifierResponse {
  512. // no decision has been made, use the built-in certificate verifier
  513. NoDecisionMade,
  514. // connection certificate is verified and accepted
  515. CertificateAccepted,
  516. // connection certificate was processed but is rejected
  517. CertificateRejected
  518. };
  519. enum StatusCode {
  520. // Information responses
  521. Continue_100 = 100,
  522. SwitchingProtocol_101 = 101,
  523. Processing_102 = 102,
  524. EarlyHints_103 = 103,
  525. // Successful responses
  526. OK_200 = 200,
  527. Created_201 = 201,
  528. Accepted_202 = 202,
  529. NonAuthoritativeInformation_203 = 203,
  530. NoContent_204 = 204,
  531. ResetContent_205 = 205,
  532. PartialContent_206 = 206,
  533. MultiStatus_207 = 207,
  534. AlreadyReported_208 = 208,
  535. IMUsed_226 = 226,
  536. // Redirection messages
  537. MultipleChoices_300 = 300,
  538. MovedPermanently_301 = 301,
  539. Found_302 = 302,
  540. SeeOther_303 = 303,
  541. NotModified_304 = 304,
  542. UseProxy_305 = 305,
  543. unused_306 = 306,
  544. TemporaryRedirect_307 = 307,
  545. PermanentRedirect_308 = 308,
  546. // Client error responses
  547. BadRequest_400 = 400,
  548. Unauthorized_401 = 401,
  549. PaymentRequired_402 = 402,
  550. Forbidden_403 = 403,
  551. NotFound_404 = 404,
  552. MethodNotAllowed_405 = 405,
  553. NotAcceptable_406 = 406,
  554. ProxyAuthenticationRequired_407 = 407,
  555. RequestTimeout_408 = 408,
  556. Conflict_409 = 409,
  557. Gone_410 = 410,
  558. LengthRequired_411 = 411,
  559. PreconditionFailed_412 = 412,
  560. PayloadTooLarge_413 = 413,
  561. UriTooLong_414 = 414,
  562. UnsupportedMediaType_415 = 415,
  563. RangeNotSatisfiable_416 = 416,
  564. ExpectationFailed_417 = 417,
  565. ImATeapot_418 = 418,
  566. MisdirectedRequest_421 = 421,
  567. UnprocessableContent_422 = 422,
  568. Locked_423 = 423,
  569. FailedDependency_424 = 424,
  570. TooEarly_425 = 425,
  571. UpgradeRequired_426 = 426,
  572. PreconditionRequired_428 = 428,
  573. TooManyRequests_429 = 429,
  574. RequestHeaderFieldsTooLarge_431 = 431,
  575. UnavailableForLegalReasons_451 = 451,
  576. // Server error responses
  577. InternalServerError_500 = 500,
  578. NotImplemented_501 = 501,
  579. BadGateway_502 = 502,
  580. ServiceUnavailable_503 = 503,
  581. GatewayTimeout_504 = 504,
  582. HttpVersionNotSupported_505 = 505,
  583. VariantAlsoNegotiates_506 = 506,
  584. InsufficientStorage_507 = 507,
  585. LoopDetected_508 = 508,
  586. NotExtended_510 = 510,
  587. NetworkAuthenticationRequired_511 = 511,
  588. };
  589. using Headers =
  590. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  591. detail::case_ignore::equal_to>;
  592. using Params = std::multimap<std::string, std::string>;
  593. using Match = std::smatch;
  594. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  595. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  596. struct Response;
  597. using ResponseHandler = std::function<bool(const Response &response)>;
  598. struct FormData {
  599. std::string name;
  600. std::string content;
  601. std::string filename;
  602. std::string content_type;
  603. Headers headers;
  604. };
  605. struct FormField {
  606. std::string name;
  607. std::string content;
  608. Headers headers;
  609. };
  610. using FormFields = std::multimap<std::string, FormField>;
  611. using FormFiles = std::multimap<std::string, FormData>;
  612. struct MultipartFormData {
  613. FormFields fields; // Text fields from multipart
  614. FormFiles files; // Files from multipart
  615. // Text field access
  616. std::string get_field(const std::string &key, size_t id = 0) const;
  617. std::vector<std::string> get_fields(const std::string &key) const;
  618. bool has_field(const std::string &key) const;
  619. size_t get_field_count(const std::string &key) const;
  620. // File access
  621. FormData get_file(const std::string &key, size_t id = 0) const;
  622. std::vector<FormData> get_files(const std::string &key) const;
  623. bool has_file(const std::string &key) const;
  624. size_t get_file_count(const std::string &key) const;
  625. };
  626. struct UploadFormData {
  627. std::string name;
  628. std::string content;
  629. std::string filename;
  630. std::string content_type;
  631. };
  632. using UploadFormDataItems = std::vector<UploadFormData>;
  633. class DataSink {
  634. public:
  635. DataSink() : os(&sb_), sb_(*this) {}
  636. DataSink(const DataSink &) = delete;
  637. DataSink &operator=(const DataSink &) = delete;
  638. DataSink(DataSink &&) = delete;
  639. DataSink &operator=(DataSink &&) = delete;
  640. std::function<bool(const char *data, size_t data_len)> write;
  641. std::function<bool()> is_writable;
  642. std::function<void()> done;
  643. std::function<void(const Headers &trailer)> done_with_trailer;
  644. std::ostream os;
  645. private:
  646. class data_sink_streambuf final : public std::streambuf {
  647. public:
  648. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  649. protected:
  650. std::streamsize xsputn(const char *s, std::streamsize n) override {
  651. sink_.write(s, static_cast<size_t>(n));
  652. return n;
  653. }
  654. private:
  655. DataSink &sink_;
  656. };
  657. data_sink_streambuf sb_;
  658. };
  659. using ContentProvider =
  660. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  661. using ContentProviderWithoutLength =
  662. std::function<bool(size_t offset, DataSink &sink)>;
  663. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  664. struct FormDataProvider {
  665. std::string name;
  666. ContentProviderWithoutLength provider;
  667. std::string filename;
  668. std::string content_type;
  669. };
  670. using FormDataProviderItems = std::vector<FormDataProvider>;
  671. using ContentReceiverWithProgress = std::function<bool(
  672. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  673. using ContentReceiver =
  674. std::function<bool(const char *data, size_t data_length)>;
  675. using FormDataHeader = std::function<bool(const FormData &file)>;
  676. class ContentReader {
  677. public:
  678. using Reader = std::function<bool(ContentReceiver receiver)>;
  679. using FormDataReader =
  680. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  681. ContentReader(Reader reader, FormDataReader multipart_reader)
  682. : reader_(std::move(reader)),
  683. formdata_reader_(std::move(multipart_reader)) {}
  684. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  685. return formdata_reader_(std::move(header), std::move(receiver));
  686. }
  687. bool operator()(ContentReceiver receiver) const {
  688. return reader_(std::move(receiver));
  689. }
  690. Reader reader_;
  691. FormDataReader formdata_reader_;
  692. };
  693. using Range = std::pair<ssize_t, ssize_t>;
  694. using Ranges = std::vector<Range>;
  695. #ifdef CPPHTTPLIB_SSL_ENABLED
  696. // TLS abstraction layer - public type definitions and API
  697. namespace tls {
  698. // Opaque handles (defined as void* for abstraction)
  699. using ctx_t = void *;
  700. using session_t = void *;
  701. using const_session_t = const void *; // For read-only session access
  702. using cert_t = void *;
  703. using ca_store_t = void *;
  704. // TLS versions
  705. enum class Version {
  706. TLS1_2 = 0x0303,
  707. TLS1_3 = 0x0304,
  708. };
  709. // Subject Alternative Names (SAN) entry types
  710. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  711. // SAN entry structure
  712. struct SanEntry {
  713. SanType type;
  714. std::string value;
  715. };
  716. // Verification context for certificate verification callback
  717. struct VerifyContext {
  718. session_t session; // TLS session handle
  719. cert_t cert; // Current certificate being verified
  720. int depth; // Certificate chain depth (0 = leaf)
  721. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  722. long error_code; // Backend-specific error code (0 = no error)
  723. const char *error_string; // Human-readable error description
  724. // Certificate introspection methods
  725. std::string subject_cn() const;
  726. std::string issuer_name() const;
  727. bool check_hostname(const char *hostname) const;
  728. std::vector<SanEntry> sans() const;
  729. bool validity(time_t &not_before, time_t &not_after) const;
  730. std::string serial() const;
  731. };
  732. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  733. // TlsError codes for TLS operations (backend-independent)
  734. enum class ErrorCode : int {
  735. Success = 0,
  736. WantRead, // Non-blocking: need to wait for read
  737. WantWrite, // Non-blocking: need to wait for write
  738. PeerClosed, // Peer closed the connection
  739. Fatal, // Unrecoverable error
  740. SyscallError, // System call error (check sys_errno)
  741. CertVerifyFailed, // Certificate verification failed
  742. HostnameMismatch, // Hostname verification failed
  743. };
  744. // TLS error information
  745. struct TlsError {
  746. ErrorCode code = ErrorCode::Fatal;
  747. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  748. int sys_errno = 0; // errno when SyscallError
  749. // Convert verification error code to human-readable string
  750. static std::string verify_error_to_string(long error_code);
  751. };
  752. // RAII wrapper for peer certificate
  753. class PeerCert {
  754. public:
  755. PeerCert();
  756. PeerCert(PeerCert &&other) noexcept;
  757. PeerCert &operator=(PeerCert &&other) noexcept;
  758. ~PeerCert();
  759. PeerCert(const PeerCert &) = delete;
  760. PeerCert &operator=(const PeerCert &) = delete;
  761. explicit operator bool() const;
  762. std::string subject_cn() const;
  763. std::string issuer_name() const;
  764. bool check_hostname(const char *hostname) const;
  765. std::vector<SanEntry> sans() const;
  766. bool validity(time_t &not_before, time_t &not_after) const;
  767. std::string serial() const;
  768. private:
  769. explicit PeerCert(cert_t cert);
  770. cert_t cert_ = nullptr;
  771. friend PeerCert get_peer_cert_from_session(const_session_t session);
  772. };
  773. // Callback for TLS context setup (used by SSLServer constructor)
  774. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  775. } // namespace tls
  776. #endif
  777. struct Request {
  778. std::string method;
  779. std::string path;
  780. std::string matched_route;
  781. Params params;
  782. Headers headers;
  783. Headers trailers;
  784. std::string body;
  785. std::string remote_addr;
  786. int remote_port = -1;
  787. std::string local_addr;
  788. int local_port = -1;
  789. // for server
  790. std::string version;
  791. std::string target;
  792. MultipartFormData form;
  793. Ranges ranges;
  794. Match matches;
  795. std::unordered_map<std::string, std::string> path_params;
  796. std::function<bool()> is_connection_closed = []() { return true; };
  797. // for client
  798. std::vector<std::string> accept_content_types;
  799. ResponseHandler response_handler;
  800. ContentReceiverWithProgress content_receiver;
  801. DownloadProgress download_progress;
  802. UploadProgress upload_progress;
  803. bool has_header(const std::string &key) const;
  804. std::string get_header_value(const std::string &key, const char *def = "",
  805. size_t id = 0) const;
  806. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  807. size_t id = 0) const;
  808. size_t get_header_value_count(const std::string &key) const;
  809. void set_header(const std::string &key, const std::string &val);
  810. bool has_trailer(const std::string &key) const;
  811. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  812. size_t get_trailer_value_count(const std::string &key) const;
  813. bool has_param(const std::string &key) const;
  814. std::string get_param_value(const std::string &key, size_t id = 0) const;
  815. size_t get_param_value_count(const std::string &key) const;
  816. bool is_multipart_form_data() const;
  817. // private members...
  818. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  819. size_t content_length_ = 0;
  820. ContentProvider content_provider_;
  821. bool is_chunked_content_provider_ = false;
  822. size_t authorization_count_ = 0;
  823. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  824. (std::chrono::steady_clock::time_point::min)();
  825. #ifdef CPPHTTPLIB_SSL_ENABLED
  826. tls::const_session_t ssl = nullptr;
  827. tls::PeerCert peer_cert() const;
  828. std::string sni() const;
  829. #endif
  830. };
  831. struct Response {
  832. std::string version;
  833. int status = -1;
  834. std::string reason;
  835. Headers headers;
  836. Headers trailers;
  837. std::string body;
  838. std::string location; // Redirect location
  839. bool has_header(const std::string &key) const;
  840. std::string get_header_value(const std::string &key, const char *def = "",
  841. size_t id = 0) const;
  842. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  843. size_t id = 0) const;
  844. size_t get_header_value_count(const std::string &key) const;
  845. void set_header(const std::string &key, const std::string &val);
  846. bool has_trailer(const std::string &key) const;
  847. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  848. size_t get_trailer_value_count(const std::string &key) const;
  849. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  850. void set_content(const char *s, size_t n, const std::string &content_type);
  851. void set_content(const std::string &s, const std::string &content_type);
  852. void set_content(std::string &&s, const std::string &content_type);
  853. void set_content_provider(
  854. size_t length, const std::string &content_type, ContentProvider provider,
  855. ContentProviderResourceReleaser resource_releaser = nullptr);
  856. void set_content_provider(
  857. const std::string &content_type, ContentProviderWithoutLength provider,
  858. ContentProviderResourceReleaser resource_releaser = nullptr);
  859. void set_chunked_content_provider(
  860. const std::string &content_type, ContentProviderWithoutLength provider,
  861. ContentProviderResourceReleaser resource_releaser = nullptr);
  862. void set_file_content(const std::string &path,
  863. const std::string &content_type);
  864. void set_file_content(const std::string &path);
  865. Response() = default;
  866. Response(const Response &) = default;
  867. Response &operator=(const Response &) = default;
  868. Response(Response &&) = default;
  869. Response &operator=(Response &&) = default;
  870. ~Response() {
  871. if (content_provider_resource_releaser_) {
  872. content_provider_resource_releaser_(content_provider_success_);
  873. }
  874. }
  875. // private members...
  876. size_t content_length_ = 0;
  877. ContentProvider content_provider_;
  878. ContentProviderResourceReleaser content_provider_resource_releaser_;
  879. bool is_chunked_content_provider_ = false;
  880. bool content_provider_success_ = false;
  881. std::string file_content_path_;
  882. std::string file_content_content_type_;
  883. };
  884. enum class Error {
  885. Success = 0,
  886. Unknown,
  887. Connection,
  888. BindIPAddress,
  889. Read,
  890. Write,
  891. ExceedRedirectCount,
  892. Canceled,
  893. SSLConnection,
  894. SSLLoadingCerts,
  895. SSLServerVerification,
  896. SSLServerHostnameVerification,
  897. UnsupportedMultipartBoundaryChars,
  898. Compression,
  899. ConnectionTimeout,
  900. ProxyConnection,
  901. ConnectionClosed,
  902. Timeout,
  903. ResourceExhaustion,
  904. TooManyFormDataFiles,
  905. ExceedMaxPayloadSize,
  906. ExceedUriMaxLength,
  907. ExceedMaxSocketDescriptorCount,
  908. InvalidRequestLine,
  909. InvalidHTTPMethod,
  910. InvalidHTTPVersion,
  911. InvalidHeaders,
  912. MultipartParsing,
  913. OpenFile,
  914. Listen,
  915. GetSockName,
  916. UnsupportedAddressFamily,
  917. HTTPParsing,
  918. InvalidRangeHeader,
  919. // For internal use only
  920. SSLPeerCouldBeClosed_,
  921. };
  922. std::string to_string(Error error);
  923. std::ostream &operator<<(std::ostream &os, const Error &obj);
  924. class Stream {
  925. public:
  926. virtual ~Stream() = default;
  927. virtual bool is_readable() const = 0;
  928. virtual bool wait_readable() const = 0;
  929. virtual bool wait_writable() const = 0;
  930. virtual ssize_t read(char *ptr, size_t size) = 0;
  931. virtual ssize_t write(const char *ptr, size_t size) = 0;
  932. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  933. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  934. virtual socket_t socket() const = 0;
  935. virtual time_t duration() const = 0;
  936. ssize_t write(const char *ptr);
  937. ssize_t write(const std::string &s);
  938. Error get_error() const { return error_; }
  939. protected:
  940. Error error_ = Error::Success;
  941. };
  942. class TaskQueue {
  943. public:
  944. TaskQueue() = default;
  945. virtual ~TaskQueue() = default;
  946. virtual bool enqueue(std::function<void()> fn) = 0;
  947. virtual void shutdown() = 0;
  948. virtual void on_idle() {}
  949. };
  950. class ThreadPool final : public TaskQueue {
  951. public:
  952. explicit ThreadPool(size_t n, size_t mqr = 0);
  953. ThreadPool(const ThreadPool &) = delete;
  954. ~ThreadPool() override = default;
  955. bool enqueue(std::function<void()> fn) override;
  956. void shutdown() override;
  957. private:
  958. struct worker {
  959. explicit worker(ThreadPool &pool);
  960. void operator()();
  961. ThreadPool &pool_;
  962. };
  963. friend struct worker;
  964. std::vector<std::thread> threads_;
  965. std::list<std::function<void()>> jobs_;
  966. bool shutdown_;
  967. size_t max_queued_requests_ = 0;
  968. std::condition_variable cond_;
  969. std::mutex mutex_;
  970. };
  971. using Logger = std::function<void(const Request &, const Response &)>;
  972. // Forward declaration for Error type
  973. enum class Error;
  974. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  975. using SocketOptions = std::function<void(socket_t sock)>;
  976. void default_socket_options(socket_t sock);
  977. const char *status_message(int status);
  978. std::string to_string(Error error);
  979. std::ostream &operator<<(std::ostream &os, const Error &obj);
  980. std::string get_bearer_token_auth(const Request &req);
  981. namespace detail {
  982. class MatcherBase {
  983. public:
  984. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  985. virtual ~MatcherBase() = default;
  986. const std::string &pattern() const { return pattern_; }
  987. // Match request path and populate its matches and
  988. virtual bool match(Request &request) const = 0;
  989. private:
  990. std::string pattern_;
  991. };
  992. /**
  993. * Captures parameters in request path and stores them in Request::path_params
  994. *
  995. * Capture name is a substring of a pattern from : to /.
  996. * The rest of the pattern is matched against the request path directly
  997. * Parameters are captured starting from the next character after
  998. * the end of the last matched static pattern fragment until the next /.
  999. *
  1000. * Example pattern:
  1001. * "/path/fragments/:capture/more/fragments/:second_capture"
  1002. * Static fragments:
  1003. * "/path/fragments/", "more/fragments/"
  1004. *
  1005. * Given the following request path:
  1006. * "/path/fragments/:1/more/fragments/:2"
  1007. * the resulting capture will be
  1008. * {{"capture", "1"}, {"second_capture", "2"}}
  1009. */
  1010. class PathParamsMatcher final : public MatcherBase {
  1011. public:
  1012. PathParamsMatcher(const std::string &pattern);
  1013. bool match(Request &request) const override;
  1014. private:
  1015. // Treat segment separators as the end of path parameter capture
  1016. // Does not need to handle query parameters as they are parsed before path
  1017. // matching
  1018. static constexpr char separator = '/';
  1019. // Contains static path fragments to match against, excluding the '/' after
  1020. // path params
  1021. // Fragments are separated by path params
  1022. std::vector<std::string> static_fragments_;
  1023. // Stores the names of the path parameters to be used as keys in the
  1024. // Request::path_params map
  1025. std::vector<std::string> param_names_;
  1026. };
  1027. /**
  1028. * Performs std::regex_match on request path
  1029. * and stores the result in Request::matches
  1030. *
  1031. * Note that regex match is performed directly on the whole request.
  1032. * This means that wildcard patterns may match multiple path segments with /:
  1033. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1034. */
  1035. class RegexMatcher final : public MatcherBase {
  1036. public:
  1037. RegexMatcher(const std::string &pattern)
  1038. : MatcherBase(pattern), regex_(pattern) {}
  1039. bool match(Request &request) const override;
  1040. private:
  1041. std::regex regex_;
  1042. };
  1043. int close_socket(socket_t sock);
  1044. ssize_t write_headers(Stream &strm, const Headers &headers);
  1045. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1046. time_t usec);
  1047. } // namespace detail
  1048. class Server {
  1049. public:
  1050. using Handler = std::function<void(const Request &, Response &)>;
  1051. using ExceptionHandler =
  1052. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1053. enum class HandlerResponse {
  1054. Handled,
  1055. Unhandled,
  1056. };
  1057. using HandlerWithResponse =
  1058. std::function<HandlerResponse(const Request &, Response &)>;
  1059. using HandlerWithContentReader = std::function<void(
  1060. const Request &, Response &, const ContentReader &content_reader)>;
  1061. using Expect100ContinueHandler =
  1062. std::function<int(const Request &, Response &)>;
  1063. Server();
  1064. virtual ~Server();
  1065. virtual bool is_valid() const;
  1066. Server &Get(const std::string &pattern, Handler handler);
  1067. Server &Post(const std::string &pattern, Handler handler);
  1068. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1069. Server &Put(const std::string &pattern, Handler handler);
  1070. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1071. Server &Patch(const std::string &pattern, Handler handler);
  1072. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1073. Server &Delete(const std::string &pattern, Handler handler);
  1074. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1075. Server &Options(const std::string &pattern, Handler handler);
  1076. bool set_base_dir(const std::string &dir,
  1077. const std::string &mount_point = std::string());
  1078. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1079. Headers headers = Headers());
  1080. bool remove_mount_point(const std::string &mount_point);
  1081. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1082. const std::string &mime);
  1083. Server &set_default_file_mimetype(const std::string &mime);
  1084. Server &set_file_request_handler(Handler handler);
  1085. template <class ErrorHandlerFunc>
  1086. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1087. return set_error_handler_core(
  1088. std::forward<ErrorHandlerFunc>(handler),
  1089. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1090. }
  1091. Server &set_exception_handler(ExceptionHandler handler);
  1092. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1093. Server &set_post_routing_handler(Handler handler);
  1094. Server &set_pre_request_handler(HandlerWithResponse handler);
  1095. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1096. Server &set_logger(Logger logger);
  1097. Server &set_pre_compression_logger(Logger logger);
  1098. Server &set_error_logger(ErrorLogger error_logger);
  1099. Server &set_address_family(int family);
  1100. Server &set_tcp_nodelay(bool on);
  1101. Server &set_ipv6_v6only(bool on);
  1102. Server &set_socket_options(SocketOptions socket_options);
  1103. Server &set_default_headers(Headers headers);
  1104. Server &
  1105. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1106. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1107. Server &set_keep_alive_max_count(size_t count);
  1108. Server &set_keep_alive_timeout(time_t sec);
  1109. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1110. template <class Rep, class Period>
  1111. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1112. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1113. template <class Rep, class Period>
  1114. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1115. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1116. template <class Rep, class Period>
  1117. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1118. Server &set_payload_max_length(size_t length);
  1119. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1120. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1121. bool listen_after_bind();
  1122. bool listen(const std::string &host, int port, int socket_flags = 0);
  1123. bool is_running() const;
  1124. void wait_until_ready() const;
  1125. void stop();
  1126. void decommission();
  1127. std::function<TaskQueue *(void)> new_task_queue;
  1128. protected:
  1129. bool process_request(Stream &strm, const std::string &remote_addr,
  1130. int remote_port, const std::string &local_addr,
  1131. int local_port, bool close_connection,
  1132. bool &connection_closed,
  1133. const std::function<void(Request &)> &setup_request);
  1134. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1135. std::vector<std::string> trusted_proxies_;
  1136. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1137. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1138. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1139. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1140. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1141. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1142. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1143. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1144. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1145. private:
  1146. using Handlers =
  1147. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1148. using HandlersForContentReader =
  1149. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1150. HandlerWithContentReader>>;
  1151. static std::unique_ptr<detail::MatcherBase>
  1152. make_matcher(const std::string &pattern);
  1153. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1154. Server &set_error_handler_core(Handler handler, std::false_type);
  1155. socket_t create_server_socket(const std::string &host, int port,
  1156. int socket_flags,
  1157. SocketOptions socket_options) const;
  1158. int bind_internal(const std::string &host, int port, int socket_flags);
  1159. bool listen_internal();
  1160. bool routing(Request &req, Response &res, Stream &strm);
  1161. bool handle_file_request(Request &req, Response &res);
  1162. bool check_if_not_modified(const Request &req, Response &res,
  1163. const std::string &etag, time_t mtime) const;
  1164. bool check_if_range(Request &req, const std::string &etag,
  1165. time_t mtime) const;
  1166. bool dispatch_request(Request &req, Response &res,
  1167. const Handlers &handlers) const;
  1168. bool dispatch_request_for_content_reader(
  1169. Request &req, Response &res, ContentReader content_reader,
  1170. const HandlersForContentReader &handlers) const;
  1171. bool parse_request_line(const char *s, Request &req) const;
  1172. void apply_ranges(const Request &req, Response &res,
  1173. std::string &content_type, std::string &boundary) const;
  1174. bool write_response(Stream &strm, bool close_connection, Request &req,
  1175. Response &res);
  1176. bool write_response_with_content(Stream &strm, bool close_connection,
  1177. const Request &req, Response &res);
  1178. bool write_response_core(Stream &strm, bool close_connection,
  1179. const Request &req, Response &res,
  1180. bool need_apply_ranges);
  1181. bool write_content_with_provider(Stream &strm, const Request &req,
  1182. Response &res, const std::string &boundary,
  1183. const std::string &content_type);
  1184. bool read_content(Stream &strm, Request &req, Response &res);
  1185. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1186. Response &res,
  1187. ContentReceiver receiver,
  1188. FormDataHeader multipart_header,
  1189. ContentReceiver multipart_receiver);
  1190. bool read_content_core(Stream &strm, Request &req, Response &res,
  1191. ContentReceiver receiver,
  1192. FormDataHeader multipart_header,
  1193. ContentReceiver multipart_receiver) const;
  1194. virtual bool process_and_close_socket(socket_t sock);
  1195. void output_log(const Request &req, const Response &res) const;
  1196. void output_pre_compression_log(const Request &req,
  1197. const Response &res) const;
  1198. void output_error_log(const Error &err, const Request *req) const;
  1199. std::atomic<bool> is_running_{false};
  1200. std::atomic<bool> is_decommissioned{false};
  1201. struct MountPointEntry {
  1202. std::string mount_point;
  1203. std::string base_dir;
  1204. Headers headers;
  1205. };
  1206. std::vector<MountPointEntry> base_dirs_;
  1207. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1208. std::string default_file_mimetype_ = "application/octet-stream";
  1209. Handler file_request_handler_;
  1210. Handlers get_handlers_;
  1211. Handlers post_handlers_;
  1212. HandlersForContentReader post_handlers_for_content_reader_;
  1213. Handlers put_handlers_;
  1214. HandlersForContentReader put_handlers_for_content_reader_;
  1215. Handlers patch_handlers_;
  1216. HandlersForContentReader patch_handlers_for_content_reader_;
  1217. Handlers delete_handlers_;
  1218. HandlersForContentReader delete_handlers_for_content_reader_;
  1219. Handlers options_handlers_;
  1220. HandlerWithResponse error_handler_;
  1221. ExceptionHandler exception_handler_;
  1222. HandlerWithResponse pre_routing_handler_;
  1223. Handler post_routing_handler_;
  1224. HandlerWithResponse pre_request_handler_;
  1225. Expect100ContinueHandler expect_100_continue_handler_;
  1226. mutable std::mutex logger_mutex_;
  1227. Logger logger_;
  1228. Logger pre_compression_logger_;
  1229. ErrorLogger error_logger_;
  1230. int address_family_ = AF_UNSPEC;
  1231. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1232. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1233. SocketOptions socket_options_ = default_socket_options;
  1234. Headers default_headers_;
  1235. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1236. detail::write_headers;
  1237. };
  1238. class Result {
  1239. public:
  1240. Result() = default;
  1241. Result(std::unique_ptr<Response> &&res, Error err,
  1242. Headers &&request_headers = Headers{})
  1243. : res_(std::move(res)), err_(err),
  1244. request_headers_(std::move(request_headers)) {}
  1245. // Response
  1246. operator bool() const { return res_ != nullptr; }
  1247. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1248. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1249. const Response &value() const { return *res_; }
  1250. Response &value() { return *res_; }
  1251. const Response &operator*() const { return *res_; }
  1252. Response &operator*() { return *res_; }
  1253. const Response *operator->() const { return res_.get(); }
  1254. Response *operator->() { return res_.get(); }
  1255. // Error
  1256. Error error() const { return err_; }
  1257. // Request Headers
  1258. bool has_request_header(const std::string &key) const;
  1259. std::string get_request_header_value(const std::string &key,
  1260. const char *def = "",
  1261. size_t id = 0) const;
  1262. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1263. size_t id = 0) const;
  1264. size_t get_request_header_value_count(const std::string &key) const;
  1265. private:
  1266. std::unique_ptr<Response> res_;
  1267. Error err_ = Error::Unknown;
  1268. Headers request_headers_;
  1269. #ifdef CPPHTTPLIB_SSL_ENABLED
  1270. public:
  1271. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1272. int ssl_error)
  1273. : res_(std::move(res)), err_(err),
  1274. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1275. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1276. int ssl_error, unsigned long ssl_backend_error)
  1277. : res_(std::move(res)), err_(err),
  1278. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1279. ssl_backend_error_(ssl_backend_error) {}
  1280. int ssl_error() const { return ssl_error_; }
  1281. unsigned long ssl_backend_error() const { return ssl_backend_error_; }
  1282. private:
  1283. int ssl_error_ = 0;
  1284. unsigned long ssl_backend_error_ = 0;
  1285. #endif
  1286. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1287. public:
  1288. [[deprecated("Use ssl_backend_error() instead")]]
  1289. unsigned long ssl_openssl_error() const {
  1290. return ssl_backend_error_;
  1291. }
  1292. #endif
  1293. };
  1294. struct ClientConnection {
  1295. socket_t sock = INVALID_SOCKET;
  1296. bool is_open() const { return sock != INVALID_SOCKET; }
  1297. ClientConnection() = default;
  1298. ~ClientConnection();
  1299. ClientConnection(const ClientConnection &) = delete;
  1300. ClientConnection &operator=(const ClientConnection &) = delete;
  1301. ClientConnection(ClientConnection &&other) noexcept
  1302. : sock(other.sock)
  1303. #ifdef CPPHTTPLIB_SSL_ENABLED
  1304. ,
  1305. session(other.session)
  1306. #endif
  1307. {
  1308. other.sock = INVALID_SOCKET;
  1309. #ifdef CPPHTTPLIB_SSL_ENABLED
  1310. other.session = nullptr;
  1311. #endif
  1312. }
  1313. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1314. if (this != &other) {
  1315. sock = other.sock;
  1316. other.sock = INVALID_SOCKET;
  1317. #ifdef CPPHTTPLIB_SSL_ENABLED
  1318. session = other.session;
  1319. other.session = nullptr;
  1320. #endif
  1321. }
  1322. return *this;
  1323. }
  1324. #ifdef CPPHTTPLIB_SSL_ENABLED
  1325. tls::session_t session = nullptr;
  1326. #endif
  1327. };
  1328. namespace detail {
  1329. struct ChunkedDecoder;
  1330. struct BodyReader {
  1331. Stream *stream = nullptr;
  1332. bool has_content_length = false;
  1333. size_t content_length = 0;
  1334. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1335. size_t bytes_read = 0;
  1336. bool chunked = false;
  1337. bool eof = false;
  1338. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1339. Error last_error = Error::Success;
  1340. ssize_t read(char *buf, size_t len);
  1341. bool has_error() const { return last_error != Error::Success; }
  1342. };
  1343. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1344. size_t len) {
  1345. (void)stream;
  1346. return br.read(buf, len);
  1347. }
  1348. class decompressor;
  1349. } // namespace detail
  1350. class ClientImpl {
  1351. public:
  1352. explicit ClientImpl(const std::string &host);
  1353. explicit ClientImpl(const std::string &host, int port);
  1354. explicit ClientImpl(const std::string &host, int port,
  1355. const std::string &client_cert_path,
  1356. const std::string &client_key_path);
  1357. virtual ~ClientImpl();
  1358. virtual bool is_valid() const;
  1359. struct StreamHandle {
  1360. std::unique_ptr<Response> response;
  1361. Error error = Error::Success;
  1362. StreamHandle() = default;
  1363. StreamHandle(const StreamHandle &) = delete;
  1364. StreamHandle &operator=(const StreamHandle &) = delete;
  1365. StreamHandle(StreamHandle &&) = default;
  1366. StreamHandle &operator=(StreamHandle &&) = default;
  1367. ~StreamHandle() = default;
  1368. bool is_valid() const {
  1369. return response != nullptr && error == Error::Success;
  1370. }
  1371. ssize_t read(char *buf, size_t len);
  1372. void parse_trailers_if_needed();
  1373. Error get_read_error() const { return body_reader_.last_error; }
  1374. bool has_read_error() const { return body_reader_.has_error(); }
  1375. bool trailers_parsed_ = false;
  1376. private:
  1377. friend class ClientImpl;
  1378. ssize_t read_with_decompression(char *buf, size_t len);
  1379. std::unique_ptr<ClientConnection> connection_;
  1380. std::unique_ptr<Stream> socket_stream_;
  1381. Stream *stream_ = nullptr;
  1382. detail::BodyReader body_reader_;
  1383. std::unique_ptr<detail::decompressor> decompressor_;
  1384. std::string decompress_buffer_;
  1385. size_t decompress_offset_ = 0;
  1386. size_t decompressed_bytes_read_ = 0;
  1387. };
  1388. // clang-format off
  1389. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1390. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1391. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1392. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1393. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1394. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1395. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1396. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1397. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1398. Result Head(const std::string &path);
  1399. Result Head(const std::string &path, const Headers &headers);
  1400. Result Post(const std::string &path);
  1401. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1402. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1403. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1404. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1405. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1406. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1407. Result Post(const std::string &path, const Params &params);
  1408. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1409. Result Post(const std::string &path, const Headers &headers);
  1410. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1411. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1412. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1413. 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);
  1414. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1415. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1416. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1417. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1418. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1419. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1420. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1421. Result Put(const std::string &path);
  1422. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1423. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1424. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1425. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1426. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1427. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1428. Result Put(const std::string &path, const Params &params);
  1429. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1430. Result Put(const std::string &path, const Headers &headers);
  1431. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1432. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1433. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1434. 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);
  1435. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1436. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1437. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1438. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1439. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1440. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1441. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1442. Result Patch(const std::string &path);
  1443. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1444. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1445. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1446. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1447. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1448. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1449. Result Patch(const std::string &path, const Params &params);
  1450. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1451. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1452. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1453. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1454. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1455. 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);
  1456. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1457. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1458. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1459. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1460. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1461. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1462. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1463. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1464. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1465. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1466. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1467. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1468. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1469. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1470. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1471. Result Options(const std::string &path);
  1472. Result Options(const std::string &path, const Headers &headers);
  1473. // clang-format on
  1474. // Streaming API: Open a stream for reading response body incrementally
  1475. // Socket ownership is transferred to StreamHandle for true streaming
  1476. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1477. StreamHandle open_stream(const std::string &method, const std::string &path,
  1478. const Params &params = {},
  1479. const Headers &headers = {},
  1480. const std::string &body = {},
  1481. const std::string &content_type = {});
  1482. bool send(Request &req, Response &res, Error &error);
  1483. Result send(const Request &req);
  1484. void stop();
  1485. std::string host() const;
  1486. int port() const;
  1487. size_t is_socket_open() const;
  1488. socket_t socket() const;
  1489. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1490. void set_default_headers(Headers headers);
  1491. void
  1492. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1493. void set_address_family(int family);
  1494. void set_tcp_nodelay(bool on);
  1495. void set_ipv6_v6only(bool on);
  1496. void set_socket_options(SocketOptions socket_options);
  1497. void set_connection_timeout(time_t sec, time_t usec = 0);
  1498. template <class Rep, class Period>
  1499. void
  1500. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1501. void set_read_timeout(time_t sec, time_t usec = 0);
  1502. template <class Rep, class Period>
  1503. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1504. void set_write_timeout(time_t sec, time_t usec = 0);
  1505. template <class Rep, class Period>
  1506. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1507. void set_max_timeout(time_t msec);
  1508. template <class Rep, class Period>
  1509. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1510. void set_basic_auth(const std::string &username, const std::string &password);
  1511. void set_bearer_token_auth(const std::string &token);
  1512. void set_keep_alive(bool on);
  1513. void set_follow_location(bool on);
  1514. void set_path_encode(bool on);
  1515. void set_compress(bool on);
  1516. void set_decompress(bool on);
  1517. void set_payload_max_length(size_t length);
  1518. void set_interface(const std::string &intf);
  1519. void set_proxy(const std::string &host, int port);
  1520. void set_proxy_basic_auth(const std::string &username,
  1521. const std::string &password);
  1522. void set_proxy_bearer_token_auth(const std::string &token);
  1523. void set_logger(Logger logger);
  1524. void set_error_logger(ErrorLogger error_logger);
  1525. protected:
  1526. struct Socket {
  1527. socket_t sock = INVALID_SOCKET;
  1528. // For Mbed TLS compatibility: start_time for request timeout tracking
  1529. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1530. bool is_open() const { return sock != INVALID_SOCKET; }
  1531. #ifdef CPPHTTPLIB_SSL_ENABLED
  1532. tls::session_t ssl = nullptr;
  1533. #endif
  1534. };
  1535. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1536. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1537. // All of:
  1538. // shutdown_ssl
  1539. // shutdown_socket
  1540. // close_socket
  1541. // should ONLY be called when socket_mutex_ is locked.
  1542. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1543. // with a DIFFERENT thread sending requests using that socket.
  1544. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1545. void shutdown_socket(Socket &socket) const;
  1546. void close_socket(Socket &socket);
  1547. bool process_request(Stream &strm, Request &req, Response &res,
  1548. bool close_connection, Error &error);
  1549. bool write_content_with_provider(Stream &strm, const Request &req,
  1550. Error &error) const;
  1551. void copy_settings(const ClientImpl &rhs);
  1552. void output_log(const Request &req, const Response &res) const;
  1553. void output_error_log(const Error &err, const Request *req) const;
  1554. // Socket endpoint information
  1555. const std::string host_;
  1556. const int port_;
  1557. // Current open socket
  1558. Socket socket_;
  1559. mutable std::mutex socket_mutex_;
  1560. std::recursive_mutex request_mutex_;
  1561. // These are all protected under socket_mutex
  1562. size_t socket_requests_in_flight_ = 0;
  1563. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1564. bool socket_should_be_closed_when_request_is_done_ = false;
  1565. // Hostname-IP map
  1566. std::map<std::string, std::string> addr_map_;
  1567. // Default headers
  1568. Headers default_headers_;
  1569. // Header writer
  1570. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1571. detail::write_headers;
  1572. // Settings
  1573. std::string client_cert_path_;
  1574. std::string client_key_path_;
  1575. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1576. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1577. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1578. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1579. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1580. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1581. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1582. std::string basic_auth_username_;
  1583. std::string basic_auth_password_;
  1584. std::string bearer_token_auth_token_;
  1585. bool keep_alive_ = false;
  1586. bool follow_location_ = false;
  1587. bool path_encode_ = true;
  1588. int address_family_ = AF_UNSPEC;
  1589. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1590. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1591. SocketOptions socket_options_ = nullptr;
  1592. bool compress_ = false;
  1593. bool decompress_ = true;
  1594. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1595. bool has_payload_max_length_ = false;
  1596. std::string interface_;
  1597. std::string proxy_host_;
  1598. int proxy_port_ = -1;
  1599. std::string proxy_basic_auth_username_;
  1600. std::string proxy_basic_auth_password_;
  1601. std::string proxy_bearer_token_auth_token_;
  1602. mutable std::mutex logger_mutex_;
  1603. Logger logger_;
  1604. ErrorLogger error_logger_;
  1605. private:
  1606. bool send_(Request &req, Response &res, Error &error);
  1607. Result send_(Request &&req);
  1608. socket_t create_client_socket(Error &error) const;
  1609. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1610. bool skip_100_continue = true) const;
  1611. bool write_request(Stream &strm, Request &req, bool close_connection,
  1612. Error &error, bool skip_body = false);
  1613. bool write_request_body(Stream &strm, Request &req, Error &error);
  1614. void prepare_default_headers(Request &r, bool for_stream,
  1615. const std::string &ct);
  1616. bool redirect(Request &req, Response &res, Error &error);
  1617. bool create_redirect_client(const std::string &scheme,
  1618. const std::string &host, int port, Request &req,
  1619. Response &res, const std::string &path,
  1620. const std::string &location, Error &error);
  1621. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1622. bool handle_request(Stream &strm, Request &req, Response &res,
  1623. bool close_connection, Error &error);
  1624. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1625. Request &req, const char *body, size_t content_length,
  1626. ContentProvider content_provider,
  1627. ContentProviderWithoutLength content_provider_without_length,
  1628. const std::string &content_type, ContentReceiver content_receiver,
  1629. Error &error);
  1630. Result send_with_content_provider_and_receiver(
  1631. const std::string &method, const std::string &path,
  1632. const Headers &headers, const char *body, size_t content_length,
  1633. ContentProvider content_provider,
  1634. ContentProviderWithoutLength content_provider_without_length,
  1635. const std::string &content_type, ContentReceiver content_receiver,
  1636. UploadProgress progress);
  1637. ContentProviderWithoutLength get_multipart_content_provider(
  1638. const std::string &boundary, const UploadFormDataItems &items,
  1639. const FormDataProviderItems &provider_items) const;
  1640. virtual bool
  1641. process_socket(const Socket &socket,
  1642. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1643. std::function<bool(Stream &strm)> callback);
  1644. virtual bool is_ssl() const;
  1645. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1646. #ifdef CPPHTTPLIB_SSL_ENABLED
  1647. public:
  1648. void set_digest_auth(const std::string &username,
  1649. const std::string &password);
  1650. void set_proxy_digest_auth(const std::string &username,
  1651. const std::string &password);
  1652. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1653. const std::string &ca_cert_dir_path = std::string());
  1654. void enable_server_certificate_verification(bool enabled);
  1655. void enable_server_hostname_verification(bool enabled);
  1656. protected:
  1657. std::string digest_auth_username_;
  1658. std::string digest_auth_password_;
  1659. std::string proxy_digest_auth_username_;
  1660. std::string proxy_digest_auth_password_;
  1661. std::string ca_cert_file_path_;
  1662. std::string ca_cert_dir_path_;
  1663. bool server_certificate_verification_ = true;
  1664. bool server_hostname_verification_ = true;
  1665. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  1666. int last_ssl_error_ = 0;
  1667. unsigned long last_backend_error_ = 0;
  1668. #endif
  1669. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1670. public:
  1671. [[deprecated("Use load_ca_cert_store() instead")]]
  1672. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1673. [[deprecated("Use tls::create_ca_store() instead")]]
  1674. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1675. [[deprecated("Use set_server_certificate_verifier(VerifyCallback) instead")]]
  1676. virtual void set_server_certificate_verifier(
  1677. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1678. #endif
  1679. };
  1680. class Client {
  1681. public:
  1682. // Universal interface
  1683. explicit Client(const std::string &scheme_host_port);
  1684. explicit Client(const std::string &scheme_host_port,
  1685. const std::string &client_cert_path,
  1686. const std::string &client_key_path);
  1687. // HTTP only interface
  1688. explicit Client(const std::string &host, int port);
  1689. explicit Client(const std::string &host, int port,
  1690. const std::string &client_cert_path,
  1691. const std::string &client_key_path);
  1692. Client(Client &&) = default;
  1693. Client &operator=(Client &&) = default;
  1694. ~Client();
  1695. bool is_valid() const;
  1696. // clang-format off
  1697. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1698. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1699. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1700. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1701. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1702. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1703. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1704. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1705. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1706. Result Head(const std::string &path);
  1707. Result Head(const std::string &path, const Headers &headers);
  1708. Result Post(const std::string &path);
  1709. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1710. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1711. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1712. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1713. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1714. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1715. Result Post(const std::string &path, const Params &params);
  1716. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1717. Result Post(const std::string &path, const Headers &headers);
  1718. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1719. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1720. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1721. 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);
  1722. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1723. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1724. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1725. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1726. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1727. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1728. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1729. Result Put(const std::string &path);
  1730. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1731. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1732. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1733. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1734. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1735. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1736. Result Put(const std::string &path, const Params &params);
  1737. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1738. Result Put(const std::string &path, const Headers &headers);
  1739. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1740. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1741. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1742. 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);
  1743. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1744. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1745. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1746. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1747. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1748. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1749. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1750. Result Patch(const std::string &path);
  1751. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1752. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1753. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1754. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1755. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1756. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1757. Result Patch(const std::string &path, const Params &params);
  1758. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1759. Result Patch(const std::string &path, const Headers &headers);
  1760. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1761. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1762. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1763. 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);
  1764. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1765. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1766. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1767. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1768. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1769. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1770. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1771. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1772. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1773. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1774. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1775. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1776. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1777. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1778. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1779. Result Options(const std::string &path);
  1780. Result Options(const std::string &path, const Headers &headers);
  1781. // clang-format on
  1782. // Streaming API: Open a stream for reading response body incrementally
  1783. // Socket ownership is transferred to StreamHandle for true streaming
  1784. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1785. ClientImpl::StreamHandle open_stream(const std::string &method,
  1786. const std::string &path,
  1787. const Params &params = {},
  1788. const Headers &headers = {},
  1789. const std::string &body = {},
  1790. const std::string &content_type = {});
  1791. bool send(Request &req, Response &res, Error &error);
  1792. Result send(const Request &req);
  1793. void stop();
  1794. std::string host() const;
  1795. int port() const;
  1796. size_t is_socket_open() const;
  1797. socket_t socket() const;
  1798. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1799. void set_default_headers(Headers headers);
  1800. void
  1801. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1802. void set_address_family(int family);
  1803. void set_tcp_nodelay(bool on);
  1804. void set_socket_options(SocketOptions socket_options);
  1805. void set_connection_timeout(time_t sec, time_t usec = 0);
  1806. template <class Rep, class Period>
  1807. void
  1808. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1809. void set_read_timeout(time_t sec, time_t usec = 0);
  1810. template <class Rep, class Period>
  1811. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1812. void set_write_timeout(time_t sec, time_t usec = 0);
  1813. template <class Rep, class Period>
  1814. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1815. void set_max_timeout(time_t msec);
  1816. template <class Rep, class Period>
  1817. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1818. void set_basic_auth(const std::string &username, const std::string &password);
  1819. void set_bearer_token_auth(const std::string &token);
  1820. void set_keep_alive(bool on);
  1821. void set_follow_location(bool on);
  1822. void set_path_encode(bool on);
  1823. void set_url_encode(bool on);
  1824. void set_compress(bool on);
  1825. void set_decompress(bool on);
  1826. void set_payload_max_length(size_t length);
  1827. void set_interface(const std::string &intf);
  1828. void set_proxy(const std::string &host, int port);
  1829. void set_proxy_basic_auth(const std::string &username,
  1830. const std::string &password);
  1831. void set_proxy_bearer_token_auth(const std::string &token);
  1832. void set_logger(Logger logger);
  1833. void set_error_logger(ErrorLogger error_logger);
  1834. private:
  1835. std::unique_ptr<ClientImpl> cli_;
  1836. #ifdef CPPHTTPLIB_SSL_ENABLED
  1837. public:
  1838. void set_digest_auth(const std::string &username,
  1839. const std::string &password);
  1840. void set_proxy_digest_auth(const std::string &username,
  1841. const std::string &password);
  1842. void enable_server_certificate_verification(bool enabled);
  1843. void enable_server_hostname_verification(bool enabled);
  1844. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1845. const std::string &ca_cert_dir_path = std::string());
  1846. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  1847. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1848. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  1849. void set_session_verifier(
  1850. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  1851. tls::ctx_t tls_context() const;
  1852. #if defined(_WIN32) && \
  1853. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  1854. void enable_windows_certificate_verification(bool enabled);
  1855. #endif
  1856. private:
  1857. bool is_ssl_ = false;
  1858. #endif
  1859. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1860. public:
  1861. [[deprecated("Use tls_context() instead")]]
  1862. SSL_CTX *ssl_context() const;
  1863. [[deprecated("Use set_session_verifier(session_t) instead")]]
  1864. void set_server_certificate_verifier(
  1865. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1866. [[deprecated("Use Result::ssl_backend_error() instead")]]
  1867. long get_verify_result() const;
  1868. #endif
  1869. };
  1870. #ifdef CPPHTTPLIB_SSL_ENABLED
  1871. class SSLServer : public Server {
  1872. public:
  1873. SSLServer(const char *cert_path, const char *private_key_path,
  1874. const char *client_ca_cert_file_path = nullptr,
  1875. const char *client_ca_cert_dir_path = nullptr,
  1876. const char *private_key_password = nullptr);
  1877. struct PemMemory {
  1878. const char *cert_pem;
  1879. size_t cert_pem_len;
  1880. const char *key_pem;
  1881. size_t key_pem_len;
  1882. const char *client_ca_pem;
  1883. size_t client_ca_pem_len;
  1884. const char *private_key_password;
  1885. };
  1886. explicit SSLServer(const PemMemory &pem);
  1887. // The callback receives the ctx_t handle which can be cast to the
  1888. // appropriate backend type (SSL_CTX* for OpenSSL,
  1889. // tls::impl::MbedTlsContext* for Mbed TLS)
  1890. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  1891. ~SSLServer() override;
  1892. bool is_valid() const override;
  1893. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  1894. const char *client_ca_pem = nullptr,
  1895. const char *password = nullptr);
  1896. tls::ctx_t tls_context() const { return ctx_; }
  1897. int ssl_last_error() const { return last_ssl_error_; }
  1898. private:
  1899. bool process_and_close_socket(socket_t sock) override;
  1900. tls::ctx_t ctx_ = nullptr;
  1901. std::mutex ctx_mutex_;
  1902. int last_ssl_error_ = 0;
  1903. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1904. public:
  1905. [[deprecated("Use SSLServer(PemMemory) or "
  1906. "SSLServer(ContextSetupCallback) instead")]]
  1907. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1908. X509_STORE *client_ca_cert_store = nullptr);
  1909. [[deprecated("Use SSLServer(ContextSetupCallback) instead")]]
  1910. SSLServer(
  1911. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1912. [[deprecated("Use tls_context() instead")]]
  1913. SSL_CTX *ssl_context() const;
  1914. [[deprecated("Use update_certs_pem() instead")]]
  1915. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1916. X509_STORE *client_ca_cert_store = nullptr);
  1917. #endif
  1918. };
  1919. class SSLClient final : public ClientImpl {
  1920. public:
  1921. explicit SSLClient(const std::string &host);
  1922. explicit SSLClient(const std::string &host, int port);
  1923. explicit SSLClient(const std::string &host, int port,
  1924. const std::string &client_cert_path,
  1925. const std::string &client_key_path,
  1926. const std::string &private_key_password = std::string());
  1927. struct PemMemory {
  1928. const char *cert_pem;
  1929. size_t cert_pem_len;
  1930. const char *key_pem;
  1931. size_t key_pem_len;
  1932. const char *private_key_password;
  1933. };
  1934. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  1935. ~SSLClient() override;
  1936. bool is_valid() const override;
  1937. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  1938. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1939. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  1940. // Post-handshake session verifier (backend-independent)
  1941. void set_session_verifier(
  1942. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  1943. tls::ctx_t tls_context() const { return ctx_; }
  1944. #if defined(_WIN32) && \
  1945. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  1946. void enable_windows_certificate_verification(bool enabled);
  1947. #endif
  1948. private:
  1949. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1950. bool ensure_socket_connection(Socket &socket, Error &error) override;
  1951. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1952. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1953. bool
  1954. process_socket(const Socket &socket,
  1955. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1956. std::function<bool(Stream &strm)> callback) override;
  1957. bool is_ssl() const override;
  1958. bool connect_with_proxy(
  1959. Socket &sock,
  1960. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1961. Response &res, bool &success, Error &error);
  1962. bool initialize_ssl(Socket &socket, Error &error);
  1963. bool load_certs();
  1964. tls::ctx_t ctx_ = nullptr;
  1965. std::mutex ctx_mutex_;
  1966. std::once_flag initialize_cert_;
  1967. long verify_result_ = 0;
  1968. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  1969. #if defined(_WIN32) && \
  1970. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  1971. bool enable_windows_cert_verification_ = true;
  1972. #endif
  1973. friend class ClientImpl;
  1974. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1975. public:
  1976. [[deprecated("Use SSLClient(host, port, PemMemory) instead")]]
  1977. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1978. EVP_PKEY *client_key,
  1979. const std::string &private_key_password = std::string());
  1980. [[deprecated("Use Result::ssl_backend_error() instead")]]
  1981. long get_verify_result() const;
  1982. [[deprecated("Use tls_context() instead")]]
  1983. SSL_CTX *ssl_context() const;
  1984. [[deprecated("Use set_session_verifier(session_t) instead")]]
  1985. void set_server_certificate_verifier(
  1986. std::function<SSLVerifierResponse(SSL *ssl)> verifier) override;
  1987. private:
  1988. bool verify_host(X509 *server_cert) const;
  1989. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1990. bool verify_host_with_common_name(X509 *server_cert) const;
  1991. #endif
  1992. };
  1993. #endif // CPPHTTPLIB_SSL_ENABLED
  1994. namespace detail {
  1995. template <typename T, typename U>
  1996. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1997. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1998. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1999. duration - std::chrono::seconds(sec))
  2000. .count();
  2001. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2002. }
  2003. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2004. return N - 1;
  2005. }
  2006. inline bool is_numeric(const std::string &str) {
  2007. return !str.empty() &&
  2008. std::all_of(str.cbegin(), str.cend(),
  2009. [](unsigned char c) { return std::isdigit(c); });
  2010. }
  2011. inline size_t get_header_value_u64(const Headers &headers,
  2012. const std::string &key, size_t def,
  2013. size_t id, bool &is_invalid_value) {
  2014. is_invalid_value = false;
  2015. auto rng = headers.equal_range(key);
  2016. auto it = rng.first;
  2017. std::advance(it, static_cast<ssize_t>(id));
  2018. if (it != rng.second) {
  2019. if (is_numeric(it->second)) {
  2020. return std::strtoull(it->second.data(), nullptr, 10);
  2021. } else {
  2022. is_invalid_value = true;
  2023. }
  2024. }
  2025. return def;
  2026. }
  2027. inline size_t get_header_value_u64(const Headers &headers,
  2028. const std::string &key, size_t def,
  2029. size_t id) {
  2030. auto dummy = false;
  2031. return get_header_value_u64(headers, key, def, id, dummy);
  2032. }
  2033. } // namespace detail
  2034. template <class Rep, class Period>
  2035. inline Server &
  2036. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2037. detail::duration_to_sec_and_usec(
  2038. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2039. return *this;
  2040. }
  2041. template <class Rep, class Period>
  2042. inline Server &
  2043. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2044. detail::duration_to_sec_and_usec(
  2045. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2046. return *this;
  2047. }
  2048. template <class Rep, class Period>
  2049. inline Server &
  2050. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2051. detail::duration_to_sec_and_usec(
  2052. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2053. return *this;
  2054. }
  2055. template <class Rep, class Period>
  2056. inline void ClientImpl::set_connection_timeout(
  2057. const std::chrono::duration<Rep, Period> &duration) {
  2058. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2059. set_connection_timeout(sec, usec);
  2060. });
  2061. }
  2062. template <class Rep, class Period>
  2063. inline void ClientImpl::set_read_timeout(
  2064. const std::chrono::duration<Rep, Period> &duration) {
  2065. detail::duration_to_sec_and_usec(
  2066. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2067. }
  2068. template <class Rep, class Period>
  2069. inline void ClientImpl::set_write_timeout(
  2070. const std::chrono::duration<Rep, Period> &duration) {
  2071. detail::duration_to_sec_and_usec(
  2072. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2073. }
  2074. template <class Rep, class Period>
  2075. inline void ClientImpl::set_max_timeout(
  2076. const std::chrono::duration<Rep, Period> &duration) {
  2077. auto msec =
  2078. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2079. set_max_timeout(msec);
  2080. }
  2081. template <class Rep, class Period>
  2082. inline void Client::set_connection_timeout(
  2083. const std::chrono::duration<Rep, Period> &duration) {
  2084. cli_->set_connection_timeout(duration);
  2085. }
  2086. template <class Rep, class Period>
  2087. inline void
  2088. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2089. cli_->set_read_timeout(duration);
  2090. }
  2091. template <class Rep, class Period>
  2092. inline void
  2093. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2094. cli_->set_write_timeout(duration);
  2095. }
  2096. inline void Client::set_max_timeout(time_t msec) {
  2097. cli_->set_max_timeout(msec);
  2098. }
  2099. template <class Rep, class Period>
  2100. inline void
  2101. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2102. cli_->set_max_timeout(duration);
  2103. }
  2104. /*
  2105. * Forward declarations and types that will be part of the .h file if split into
  2106. * .h + .cc.
  2107. */
  2108. std::string hosted_at(const std::string &hostname);
  2109. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2110. // JavaScript-style URL encoding/decoding functions
  2111. std::string encode_uri_component(const std::string &value);
  2112. std::string encode_uri(const std::string &value);
  2113. std::string decode_uri_component(const std::string &value);
  2114. std::string decode_uri(const std::string &value);
  2115. // RFC 3986 compliant URL component encoding/decoding functions
  2116. std::string encode_path_component(const std::string &component);
  2117. std::string decode_path_component(const std::string &component);
  2118. std::string encode_query_component(const std::string &component,
  2119. bool space_as_plus = true);
  2120. std::string decode_query_component(const std::string &component,
  2121. bool plus_as_space = true);
  2122. std::string append_query_params(const std::string &path, const Params &params);
  2123. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2124. std::pair<std::string, std::string>
  2125. make_basic_authentication_header(const std::string &username,
  2126. const std::string &password,
  2127. bool is_proxy = false);
  2128. namespace detail {
  2129. #if defined(_WIN32)
  2130. inline std::wstring u8string_to_wstring(const char *s) {
  2131. if (!s) { return std::wstring(); }
  2132. auto len = static_cast<int>(strlen(s));
  2133. if (!len) { return std::wstring(); }
  2134. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2135. if (!wlen) { return std::wstring(); }
  2136. std::wstring ws;
  2137. ws.resize(wlen);
  2138. wlen = ::MultiByteToWideChar(
  2139. CP_UTF8, 0, s, len,
  2140. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2141. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2142. return ws;
  2143. }
  2144. #endif
  2145. struct FileStat {
  2146. FileStat(const std::string &path);
  2147. bool is_file() const;
  2148. bool is_dir() const;
  2149. time_t mtime() const;
  2150. size_t size() const;
  2151. private:
  2152. #if defined(_WIN32)
  2153. struct _stat st_;
  2154. #else
  2155. struct stat st_;
  2156. #endif
  2157. int ret_ = -1;
  2158. };
  2159. std::string make_host_and_port_string(const std::string &host, int port,
  2160. bool is_ssl);
  2161. std::string trim_copy(const std::string &s);
  2162. void divide(
  2163. const char *data, std::size_t size, char d,
  2164. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2165. fn);
  2166. void divide(
  2167. const std::string &str, char d,
  2168. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2169. fn);
  2170. void split(const char *b, const char *e, char d,
  2171. std::function<void(const char *, const char *)> fn);
  2172. void split(const char *b, const char *e, char d, size_t m,
  2173. std::function<void(const char *, const char *)> fn);
  2174. bool process_client_socket(
  2175. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2176. time_t write_timeout_sec, time_t write_timeout_usec,
  2177. time_t max_timeout_msec,
  2178. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2179. std::function<bool(Stream &)> callback);
  2180. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2181. int port, int address_family, bool tcp_nodelay,
  2182. bool ipv6_v6only, SocketOptions socket_options,
  2183. time_t connection_timeout_sec,
  2184. time_t connection_timeout_usec,
  2185. time_t read_timeout_sec, time_t read_timeout_usec,
  2186. time_t write_timeout_sec,
  2187. time_t write_timeout_usec,
  2188. const std::string &intf, Error &error);
  2189. const char *get_header_value(const Headers &headers, const std::string &key,
  2190. const char *def, size_t id);
  2191. std::string params_to_query_str(const Params &params);
  2192. void parse_query_text(const char *data, std::size_t size, Params &params);
  2193. void parse_query_text(const std::string &s, Params &params);
  2194. bool parse_multipart_boundary(const std::string &content_type,
  2195. std::string &boundary);
  2196. bool parse_range_header(const std::string &s, Ranges &ranges);
  2197. bool parse_accept_header(const std::string &s,
  2198. std::vector<std::string> &content_types);
  2199. int close_socket(socket_t sock);
  2200. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2201. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2202. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2203. EncodingType encoding_type(const Request &req, const Response &res);
  2204. class BufferStream final : public Stream {
  2205. public:
  2206. BufferStream() = default;
  2207. ~BufferStream() override = default;
  2208. bool is_readable() const override;
  2209. bool wait_readable() const override;
  2210. bool wait_writable() const override;
  2211. ssize_t read(char *ptr, size_t size) override;
  2212. ssize_t write(const char *ptr, size_t size) override;
  2213. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2214. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2215. socket_t socket() const override;
  2216. time_t duration() const override;
  2217. const std::string &get_buffer() const;
  2218. private:
  2219. std::string buffer;
  2220. size_t position = 0;
  2221. };
  2222. class compressor {
  2223. public:
  2224. virtual ~compressor() = default;
  2225. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2226. virtual bool compress(const char *data, size_t data_length, bool last,
  2227. Callback callback) = 0;
  2228. };
  2229. class decompressor {
  2230. public:
  2231. virtual ~decompressor() = default;
  2232. virtual bool is_valid() const = 0;
  2233. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2234. virtual bool decompress(const char *data, size_t data_length,
  2235. Callback callback) = 0;
  2236. };
  2237. class nocompressor final : public compressor {
  2238. public:
  2239. ~nocompressor() override = default;
  2240. bool compress(const char *data, size_t data_length, bool /*last*/,
  2241. Callback callback) override;
  2242. };
  2243. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2244. class gzip_compressor final : public compressor {
  2245. public:
  2246. gzip_compressor();
  2247. ~gzip_compressor() override;
  2248. bool compress(const char *data, size_t data_length, bool last,
  2249. Callback callback) override;
  2250. private:
  2251. bool is_valid_ = false;
  2252. z_stream strm_;
  2253. };
  2254. class gzip_decompressor final : public decompressor {
  2255. public:
  2256. gzip_decompressor();
  2257. ~gzip_decompressor() override;
  2258. bool is_valid() const override;
  2259. bool decompress(const char *data, size_t data_length,
  2260. Callback callback) override;
  2261. private:
  2262. bool is_valid_ = false;
  2263. z_stream strm_;
  2264. };
  2265. #endif
  2266. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2267. class brotli_compressor final : public compressor {
  2268. public:
  2269. brotli_compressor();
  2270. ~brotli_compressor();
  2271. bool compress(const char *data, size_t data_length, bool last,
  2272. Callback callback) override;
  2273. private:
  2274. BrotliEncoderState *state_ = nullptr;
  2275. };
  2276. class brotli_decompressor final : public decompressor {
  2277. public:
  2278. brotli_decompressor();
  2279. ~brotli_decompressor();
  2280. bool is_valid() const override;
  2281. bool decompress(const char *data, size_t data_length,
  2282. Callback callback) override;
  2283. private:
  2284. BrotliDecoderResult decoder_r;
  2285. BrotliDecoderState *decoder_s = nullptr;
  2286. };
  2287. #endif
  2288. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2289. class zstd_compressor : public compressor {
  2290. public:
  2291. zstd_compressor();
  2292. ~zstd_compressor();
  2293. bool compress(const char *data, size_t data_length, bool last,
  2294. Callback callback) override;
  2295. private:
  2296. ZSTD_CCtx *ctx_ = nullptr;
  2297. };
  2298. class zstd_decompressor : public decompressor {
  2299. public:
  2300. zstd_decompressor();
  2301. ~zstd_decompressor();
  2302. bool is_valid() const override;
  2303. bool decompress(const char *data, size_t data_length,
  2304. Callback callback) override;
  2305. private:
  2306. ZSTD_DCtx *ctx_ = nullptr;
  2307. };
  2308. #endif
  2309. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2310. // to store data. The call can set memory on stack for performance.
  2311. class stream_line_reader {
  2312. public:
  2313. stream_line_reader(Stream &strm, char *fixed_buffer,
  2314. size_t fixed_buffer_size);
  2315. const char *ptr() const;
  2316. size_t size() const;
  2317. bool end_with_crlf() const;
  2318. bool getline();
  2319. private:
  2320. void append(char c);
  2321. Stream &strm_;
  2322. char *fixed_buffer_;
  2323. const size_t fixed_buffer_size_;
  2324. size_t fixed_buffer_used_size_ = 0;
  2325. std::string growable_buffer_;
  2326. };
  2327. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2328. const Headers &src_headers);
  2329. struct ChunkedDecoder {
  2330. Stream &strm;
  2331. size_t chunk_remaining = 0;
  2332. bool finished = false;
  2333. char line_buf[64];
  2334. size_t last_chunk_total = 0;
  2335. size_t last_chunk_offset = 0;
  2336. explicit ChunkedDecoder(Stream &s);
  2337. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2338. size_t &out_chunk_total);
  2339. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2340. };
  2341. class mmap {
  2342. public:
  2343. mmap(const char *path);
  2344. ~mmap();
  2345. bool open(const char *path);
  2346. void close();
  2347. bool is_open() const;
  2348. size_t size() const;
  2349. const char *data() const;
  2350. private:
  2351. #if defined(_WIN32)
  2352. HANDLE hFile_ = NULL;
  2353. HANDLE hMapping_ = NULL;
  2354. #else
  2355. int fd_ = -1;
  2356. #endif
  2357. size_t size_ = 0;
  2358. void *addr_ = nullptr;
  2359. bool is_open_empty_file = false;
  2360. };
  2361. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2362. namespace fields {
  2363. bool is_token_char(char c);
  2364. bool is_token(const std::string &s);
  2365. bool is_field_name(const std::string &s);
  2366. bool is_vchar(char c);
  2367. bool is_obs_text(char c);
  2368. bool is_field_vchar(char c);
  2369. bool is_field_content(const std::string &s);
  2370. bool is_field_value(const std::string &s);
  2371. } // namespace fields
  2372. } // namespace detail
  2373. /*
  2374. * TLS Abstraction Layer Declarations
  2375. */
  2376. #ifdef CPPHTTPLIB_SSL_ENABLED
  2377. // TLS abstraction layer - backend-specific type declarations
  2378. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2379. namespace tls {
  2380. namespace impl {
  2381. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2382. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2383. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2384. struct MbedTlsContext {
  2385. mbedtls_ssl_config conf;
  2386. mbedtls_entropy_context entropy;
  2387. mbedtls_ctr_drbg_context ctr_drbg;
  2388. mbedtls_x509_crt ca_chain;
  2389. mbedtls_x509_crt own_cert;
  2390. mbedtls_pk_context own_key;
  2391. bool is_server = false;
  2392. bool verify_client = false;
  2393. bool has_verify_callback = false;
  2394. MbedTlsContext();
  2395. ~MbedTlsContext();
  2396. MbedTlsContext(const MbedTlsContext &) = delete;
  2397. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2398. };
  2399. } // namespace impl
  2400. } // namespace tls
  2401. #endif
  2402. #endif // CPPHTTPLIB_SSL_ENABLED
  2403. namespace stream {
  2404. class Result {
  2405. public:
  2406. Result();
  2407. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2408. Result(Result &&other) noexcept;
  2409. Result &operator=(Result &&other) noexcept;
  2410. Result(const Result &) = delete;
  2411. Result &operator=(const Result &) = delete;
  2412. // Response info
  2413. bool is_valid() const;
  2414. explicit operator bool() const;
  2415. int status() const;
  2416. const Headers &headers() const;
  2417. std::string get_header_value(const std::string &key,
  2418. const char *def = "") const;
  2419. bool has_header(const std::string &key) const;
  2420. Error error() const;
  2421. Error read_error() const;
  2422. bool has_read_error() const;
  2423. // Stream reading
  2424. bool next();
  2425. const char *data() const;
  2426. size_t size() const;
  2427. std::string read_all();
  2428. private:
  2429. ClientImpl::StreamHandle handle_;
  2430. std::string buffer_;
  2431. size_t current_size_ = 0;
  2432. size_t chunk_size_;
  2433. bool finished_ = false;
  2434. };
  2435. // GET
  2436. template <typename ClientType>
  2437. inline Result Get(ClientType &cli, const std::string &path,
  2438. size_t chunk_size = 8192) {
  2439. return Result{cli.open_stream("GET", path), chunk_size};
  2440. }
  2441. template <typename ClientType>
  2442. inline Result Get(ClientType &cli, const std::string &path,
  2443. const Headers &headers, size_t chunk_size = 8192) {
  2444. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2445. }
  2446. template <typename ClientType>
  2447. inline Result Get(ClientType &cli, const std::string &path,
  2448. const Params &params, size_t chunk_size = 8192) {
  2449. return Result{cli.open_stream("GET", path, params), chunk_size};
  2450. }
  2451. template <typename ClientType>
  2452. inline Result Get(ClientType &cli, const std::string &path,
  2453. const Params &params, const Headers &headers,
  2454. size_t chunk_size = 8192) {
  2455. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2456. }
  2457. // POST
  2458. template <typename ClientType>
  2459. inline Result Post(ClientType &cli, const std::string &path,
  2460. const std::string &body, const std::string &content_type,
  2461. size_t chunk_size = 8192) {
  2462. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2463. chunk_size};
  2464. }
  2465. template <typename ClientType>
  2466. inline Result Post(ClientType &cli, const std::string &path,
  2467. const Headers &headers, const std::string &body,
  2468. const std::string &content_type, size_t chunk_size = 8192) {
  2469. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2470. chunk_size};
  2471. }
  2472. template <typename ClientType>
  2473. inline Result Post(ClientType &cli, const std::string &path,
  2474. const Params &params, const std::string &body,
  2475. const std::string &content_type, size_t chunk_size = 8192) {
  2476. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2477. chunk_size};
  2478. }
  2479. template <typename ClientType>
  2480. inline Result Post(ClientType &cli, const std::string &path,
  2481. const Params &params, const Headers &headers,
  2482. const std::string &body, const std::string &content_type,
  2483. size_t chunk_size = 8192) {
  2484. return Result{
  2485. cli.open_stream("POST", path, params, headers, body, content_type),
  2486. chunk_size};
  2487. }
  2488. // PUT
  2489. template <typename ClientType>
  2490. inline Result Put(ClientType &cli, const std::string &path,
  2491. const std::string &body, const std::string &content_type,
  2492. size_t chunk_size = 8192) {
  2493. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2494. chunk_size};
  2495. }
  2496. template <typename ClientType>
  2497. inline Result Put(ClientType &cli, const std::string &path,
  2498. const Headers &headers, const std::string &body,
  2499. const std::string &content_type, size_t chunk_size = 8192) {
  2500. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2501. chunk_size};
  2502. }
  2503. template <typename ClientType>
  2504. inline Result Put(ClientType &cli, const std::string &path,
  2505. const Params &params, const std::string &body,
  2506. const std::string &content_type, size_t chunk_size = 8192) {
  2507. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2508. chunk_size};
  2509. }
  2510. template <typename ClientType>
  2511. inline Result Put(ClientType &cli, const std::string &path,
  2512. const Params &params, const Headers &headers,
  2513. const std::string &body, const std::string &content_type,
  2514. size_t chunk_size = 8192) {
  2515. return Result{
  2516. cli.open_stream("PUT", path, params, headers, body, content_type),
  2517. chunk_size};
  2518. }
  2519. // PATCH
  2520. template <typename ClientType>
  2521. inline Result Patch(ClientType &cli, const std::string &path,
  2522. const std::string &body, const std::string &content_type,
  2523. size_t chunk_size = 8192) {
  2524. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2525. chunk_size};
  2526. }
  2527. template <typename ClientType>
  2528. inline Result Patch(ClientType &cli, const std::string &path,
  2529. const Headers &headers, const std::string &body,
  2530. const std::string &content_type, size_t chunk_size = 8192) {
  2531. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2532. chunk_size};
  2533. }
  2534. template <typename ClientType>
  2535. inline Result Patch(ClientType &cli, const std::string &path,
  2536. const Params &params, const std::string &body,
  2537. const std::string &content_type, size_t chunk_size = 8192) {
  2538. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2539. chunk_size};
  2540. }
  2541. template <typename ClientType>
  2542. inline Result Patch(ClientType &cli, const std::string &path,
  2543. const Params &params, const Headers &headers,
  2544. const std::string &body, const std::string &content_type,
  2545. size_t chunk_size = 8192) {
  2546. return Result{
  2547. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2548. chunk_size};
  2549. }
  2550. // DELETE
  2551. template <typename ClientType>
  2552. inline Result Delete(ClientType &cli, const std::string &path,
  2553. size_t chunk_size = 8192) {
  2554. return Result{cli.open_stream("DELETE", path), chunk_size};
  2555. }
  2556. template <typename ClientType>
  2557. inline Result Delete(ClientType &cli, const std::string &path,
  2558. const Headers &headers, size_t chunk_size = 8192) {
  2559. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2560. }
  2561. template <typename ClientType>
  2562. inline Result Delete(ClientType &cli, const std::string &path,
  2563. const std::string &body, const std::string &content_type,
  2564. size_t chunk_size = 8192) {
  2565. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2566. chunk_size};
  2567. }
  2568. template <typename ClientType>
  2569. inline Result Delete(ClientType &cli, const std::string &path,
  2570. const Headers &headers, const std::string &body,
  2571. const std::string &content_type,
  2572. size_t chunk_size = 8192) {
  2573. return Result{
  2574. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2575. chunk_size};
  2576. }
  2577. template <typename ClientType>
  2578. inline Result Delete(ClientType &cli, const std::string &path,
  2579. const Params &params, size_t chunk_size = 8192) {
  2580. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2581. }
  2582. template <typename ClientType>
  2583. inline Result Delete(ClientType &cli, const std::string &path,
  2584. const Params &params, const Headers &headers,
  2585. size_t chunk_size = 8192) {
  2586. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2587. }
  2588. template <typename ClientType>
  2589. inline Result Delete(ClientType &cli, const std::string &path,
  2590. const Params &params, const std::string &body,
  2591. const std::string &content_type,
  2592. size_t chunk_size = 8192) {
  2593. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2594. chunk_size};
  2595. }
  2596. template <typename ClientType>
  2597. inline Result Delete(ClientType &cli, const std::string &path,
  2598. const Params &params, const Headers &headers,
  2599. const std::string &body, const std::string &content_type,
  2600. size_t chunk_size = 8192) {
  2601. return Result{
  2602. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2603. chunk_size};
  2604. }
  2605. // HEAD
  2606. template <typename ClientType>
  2607. inline Result Head(ClientType &cli, const std::string &path,
  2608. size_t chunk_size = 8192) {
  2609. return Result{cli.open_stream("HEAD", path), chunk_size};
  2610. }
  2611. template <typename ClientType>
  2612. inline Result Head(ClientType &cli, const std::string &path,
  2613. const Headers &headers, size_t chunk_size = 8192) {
  2614. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2615. }
  2616. template <typename ClientType>
  2617. inline Result Head(ClientType &cli, const std::string &path,
  2618. const Params &params, size_t chunk_size = 8192) {
  2619. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2620. }
  2621. template <typename ClientType>
  2622. inline Result Head(ClientType &cli, const std::string &path,
  2623. const Params &params, const Headers &headers,
  2624. size_t chunk_size = 8192) {
  2625. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2626. }
  2627. // OPTIONS
  2628. template <typename ClientType>
  2629. inline Result Options(ClientType &cli, const std::string &path,
  2630. size_t chunk_size = 8192) {
  2631. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2632. }
  2633. template <typename ClientType>
  2634. inline Result Options(ClientType &cli, const std::string &path,
  2635. const Headers &headers, size_t chunk_size = 8192) {
  2636. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2637. }
  2638. template <typename ClientType>
  2639. inline Result Options(ClientType &cli, const std::string &path,
  2640. const Params &params, size_t chunk_size = 8192) {
  2641. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2642. }
  2643. template <typename ClientType>
  2644. inline Result Options(ClientType &cli, const std::string &path,
  2645. const Params &params, const Headers &headers,
  2646. size_t chunk_size = 8192) {
  2647. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2648. }
  2649. } // namespace stream
  2650. namespace sse {
  2651. struct SSEMessage {
  2652. std::string event; // Event type (default: "message")
  2653. std::string data; // Event payload
  2654. std::string id; // Event ID for Last-Event-ID header
  2655. SSEMessage();
  2656. void clear();
  2657. };
  2658. class SSEClient {
  2659. public:
  2660. using MessageHandler = std::function<void(const SSEMessage &)>;
  2661. using ErrorHandler = std::function<void(Error)>;
  2662. using OpenHandler = std::function<void()>;
  2663. SSEClient(Client &client, const std::string &path);
  2664. SSEClient(Client &client, const std::string &path, const Headers &headers);
  2665. ~SSEClient();
  2666. SSEClient(const SSEClient &) = delete;
  2667. SSEClient &operator=(const SSEClient &) = delete;
  2668. // Event handlers
  2669. SSEClient &on_message(MessageHandler handler);
  2670. SSEClient &on_event(const std::string &type, MessageHandler handler);
  2671. SSEClient &on_open(OpenHandler handler);
  2672. SSEClient &on_error(ErrorHandler handler);
  2673. SSEClient &set_reconnect_interval(int ms);
  2674. SSEClient &set_max_reconnect_attempts(int n);
  2675. // State accessors
  2676. bool is_connected() const;
  2677. const std::string &last_event_id() const;
  2678. // Blocking start - runs event loop with auto-reconnect
  2679. void start();
  2680. // Non-blocking start - runs in background thread
  2681. void start_async();
  2682. // Stop the client (thread-safe)
  2683. void stop();
  2684. private:
  2685. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  2686. void run_event_loop();
  2687. void dispatch_event(const SSEMessage &msg);
  2688. bool should_reconnect(int count) const;
  2689. void wait_for_reconnect();
  2690. // Client and path
  2691. Client &client_;
  2692. std::string path_;
  2693. Headers headers_;
  2694. // Callbacks
  2695. MessageHandler on_message_;
  2696. std::map<std::string, MessageHandler> event_handlers_;
  2697. OpenHandler on_open_;
  2698. ErrorHandler on_error_;
  2699. // Configuration
  2700. int reconnect_interval_ms_ = 3000;
  2701. int max_reconnect_attempts_ = 0; // 0 = unlimited
  2702. // State
  2703. std::atomic<bool> running_{false};
  2704. std::atomic<bool> connected_{false};
  2705. std::string last_event_id_;
  2706. // Async support
  2707. std::thread async_thread_;
  2708. };
  2709. } // namespace sse
  2710. // ----------------------------------------------------------------------------
  2711. /*
  2712. * Implementation that will be part of the .cc file if split into .h + .cc.
  2713. */
  2714. namespace stream {
  2715. // stream::Result implementations
  2716. inline Result::Result() : chunk_size_(8192) {}
  2717. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  2718. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  2719. inline Result::Result(Result &&other) noexcept
  2720. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  2721. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  2722. finished_(other.finished_) {
  2723. other.current_size_ = 0;
  2724. other.finished_ = true;
  2725. }
  2726. inline Result &Result::operator=(Result &&other) noexcept {
  2727. if (this != &other) {
  2728. handle_ = std::move(other.handle_);
  2729. buffer_ = std::move(other.buffer_);
  2730. current_size_ = other.current_size_;
  2731. chunk_size_ = other.chunk_size_;
  2732. finished_ = other.finished_;
  2733. other.current_size_ = 0;
  2734. other.finished_ = true;
  2735. }
  2736. return *this;
  2737. }
  2738. inline bool Result::is_valid() const { return handle_.is_valid(); }
  2739. inline Result::operator bool() const { return is_valid(); }
  2740. inline int Result::status() const {
  2741. return handle_.response ? handle_.response->status : -1;
  2742. }
  2743. inline const Headers &Result::headers() const {
  2744. static const Headers empty_headers;
  2745. return handle_.response ? handle_.response->headers : empty_headers;
  2746. }
  2747. inline std::string Result::get_header_value(const std::string &key,
  2748. const char *def) const {
  2749. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  2750. }
  2751. inline bool Result::has_header(const std::string &key) const {
  2752. return handle_.response ? handle_.response->has_header(key) : false;
  2753. }
  2754. inline Error Result::error() const { return handle_.error; }
  2755. inline Error Result::read_error() const { return handle_.get_read_error(); }
  2756. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  2757. inline bool Result::next() {
  2758. if (!handle_.is_valid() || finished_) { return false; }
  2759. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  2760. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  2761. if (n > 0) {
  2762. current_size_ = static_cast<size_t>(n);
  2763. return true;
  2764. }
  2765. current_size_ = 0;
  2766. finished_ = true;
  2767. return false;
  2768. }
  2769. inline const char *Result::data() const { return buffer_.data(); }
  2770. inline size_t Result::size() const { return current_size_; }
  2771. inline std::string Result::read_all() {
  2772. std::string result;
  2773. while (next()) {
  2774. result.append(data(), size());
  2775. }
  2776. return result;
  2777. }
  2778. } // namespace stream
  2779. namespace sse {
  2780. // SSEMessage implementations
  2781. inline SSEMessage::SSEMessage() : event("message") {}
  2782. inline void SSEMessage::clear() {
  2783. event = "message";
  2784. data.clear();
  2785. id.clear();
  2786. }
  2787. // SSEClient implementations
  2788. inline SSEClient::SSEClient(Client &client, const std::string &path)
  2789. : client_(client), path_(path) {}
  2790. inline SSEClient::SSEClient(Client &client, const std::string &path,
  2791. const Headers &headers)
  2792. : client_(client), path_(path), headers_(headers) {}
  2793. inline SSEClient::~SSEClient() { stop(); }
  2794. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  2795. on_message_ = std::move(handler);
  2796. return *this;
  2797. }
  2798. inline SSEClient &SSEClient::on_event(const std::string &type,
  2799. MessageHandler handler) {
  2800. event_handlers_[type] = std::move(handler);
  2801. return *this;
  2802. }
  2803. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  2804. on_open_ = std::move(handler);
  2805. return *this;
  2806. }
  2807. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  2808. on_error_ = std::move(handler);
  2809. return *this;
  2810. }
  2811. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  2812. reconnect_interval_ms_ = ms;
  2813. return *this;
  2814. }
  2815. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  2816. max_reconnect_attempts_ = n;
  2817. return *this;
  2818. }
  2819. inline bool SSEClient::is_connected() const { return connected_.load(); }
  2820. inline const std::string &SSEClient::last_event_id() const {
  2821. return last_event_id_;
  2822. }
  2823. inline void SSEClient::start() {
  2824. running_.store(true);
  2825. run_event_loop();
  2826. }
  2827. inline void SSEClient::start_async() {
  2828. running_.store(true);
  2829. async_thread_ = std::thread([this]() { run_event_loop(); });
  2830. }
  2831. inline void SSEClient::stop() {
  2832. running_.store(false);
  2833. client_.stop(); // Cancel any pending operations
  2834. if (async_thread_.joinable()) { async_thread_.join(); }
  2835. }
  2836. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  2837. int &retry_ms) {
  2838. // Blank line signals end of event
  2839. if (line.empty() || line == "\r") { return true; }
  2840. // Lines starting with ':' are comments (ignored)
  2841. if (!line.empty() && line[0] == ':') { return false; }
  2842. // Find the colon separator
  2843. auto colon_pos = line.find(':');
  2844. if (colon_pos == std::string::npos) {
  2845. // Line with no colon is treated as field name with empty value
  2846. return false;
  2847. }
  2848. auto field = line.substr(0, colon_pos);
  2849. std::string value;
  2850. // Value starts after colon, skip optional single space
  2851. if (colon_pos + 1 < line.size()) {
  2852. auto value_start = colon_pos + 1;
  2853. if (line[value_start] == ' ') { value_start++; }
  2854. value = line.substr(value_start);
  2855. // Remove trailing \r if present
  2856. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  2857. }
  2858. // Handle known fields
  2859. if (field == "event") {
  2860. msg.event = value;
  2861. } else if (field == "data") {
  2862. // Multiple data lines are concatenated with newlines
  2863. if (!msg.data.empty()) { msg.data += "\n"; }
  2864. msg.data += value;
  2865. } else if (field == "id") {
  2866. // Empty id is valid (clears the last event ID)
  2867. msg.id = value;
  2868. } else if (field == "retry") {
  2869. // Parse retry interval in milliseconds
  2870. {
  2871. int v = 0;
  2872. auto res =
  2873. detail::from_chars(value.data(), value.data() + value.size(), v);
  2874. if (res.ec == std::errc{}) { retry_ms = v; }
  2875. }
  2876. }
  2877. // Unknown fields are ignored per SSE spec
  2878. return false;
  2879. }
  2880. inline void SSEClient::run_event_loop() {
  2881. auto reconnect_count = 0;
  2882. while (running_.load()) {
  2883. // Build headers, including Last-Event-ID if we have one
  2884. auto request_headers = headers_;
  2885. if (!last_event_id_.empty()) {
  2886. request_headers.emplace("Last-Event-ID", last_event_id_);
  2887. }
  2888. // Open streaming connection
  2889. auto result = stream::Get(client_, path_, request_headers);
  2890. // Connection error handling
  2891. if (!result) {
  2892. connected_.store(false);
  2893. if (on_error_) { on_error_(result.error()); }
  2894. if (!should_reconnect(reconnect_count)) { break; }
  2895. wait_for_reconnect();
  2896. reconnect_count++;
  2897. continue;
  2898. }
  2899. if (result.status() != 200) {
  2900. connected_.store(false);
  2901. // For certain errors, don't reconnect
  2902. if (result.status() == 204 || // No Content - server wants us to stop
  2903. result.status() == 404 || // Not Found
  2904. result.status() == 401 || // Unauthorized
  2905. result.status() == 403) { // Forbidden
  2906. if (on_error_) { on_error_(Error::Connection); }
  2907. break;
  2908. }
  2909. if (on_error_) { on_error_(Error::Connection); }
  2910. if (!should_reconnect(reconnect_count)) { break; }
  2911. wait_for_reconnect();
  2912. reconnect_count++;
  2913. continue;
  2914. }
  2915. // Connection successful
  2916. connected_.store(true);
  2917. reconnect_count = 0;
  2918. if (on_open_) { on_open_(); }
  2919. // Event receiving loop
  2920. std::string buffer;
  2921. SSEMessage current_msg;
  2922. while (running_.load() && result.next()) {
  2923. buffer.append(result.data(), result.size());
  2924. // Process complete lines in the buffer
  2925. size_t line_start = 0;
  2926. size_t newline_pos;
  2927. while ((newline_pos = buffer.find('\n', line_start)) !=
  2928. std::string::npos) {
  2929. auto line = buffer.substr(line_start, newline_pos - line_start);
  2930. line_start = newline_pos + 1;
  2931. // Parse the line and check if event is complete
  2932. auto event_complete =
  2933. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  2934. if (event_complete && !current_msg.data.empty()) {
  2935. // Update last_event_id for reconnection
  2936. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  2937. // Dispatch event to appropriate handler
  2938. dispatch_event(current_msg);
  2939. current_msg.clear();
  2940. }
  2941. }
  2942. // Keep unprocessed data in buffer
  2943. buffer.erase(0, line_start);
  2944. }
  2945. // Connection ended
  2946. connected_.store(false);
  2947. if (!running_.load()) { break; }
  2948. // Check for read errors
  2949. if (result.has_read_error()) {
  2950. if (on_error_) { on_error_(result.read_error()); }
  2951. }
  2952. if (!should_reconnect(reconnect_count)) { break; }
  2953. wait_for_reconnect();
  2954. reconnect_count++;
  2955. }
  2956. connected_.store(false);
  2957. }
  2958. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  2959. // Check for specific event type handler first
  2960. auto it = event_handlers_.find(msg.event);
  2961. if (it != event_handlers_.end()) {
  2962. it->second(msg);
  2963. return;
  2964. }
  2965. // Fall back to generic message handler
  2966. if (on_message_) { on_message_(msg); }
  2967. }
  2968. inline bool SSEClient::should_reconnect(int count) const {
  2969. if (!running_.load()) { return false; }
  2970. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  2971. return count < max_reconnect_attempts_;
  2972. }
  2973. inline void SSEClient::wait_for_reconnect() {
  2974. // Use small increments to check running_ flag frequently
  2975. auto waited = 0;
  2976. while (running_.load() && waited < reconnect_interval_ms_) {
  2977. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2978. waited += 100;
  2979. }
  2980. }
  2981. } // namespace sse
  2982. #ifdef CPPHTTPLIB_SSL_ENABLED
  2983. /*
  2984. * TLS abstraction layer - internal function declarations
  2985. * These are implementation details and not part of the public API.
  2986. */
  2987. namespace tls {
  2988. // Client context
  2989. ctx_t create_client_context();
  2990. void free_context(ctx_t ctx);
  2991. bool set_min_version(ctx_t ctx, Version version);
  2992. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  2993. bool load_ca_file(ctx_t ctx, const char *file_path);
  2994. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  2995. bool load_system_certs(ctx_t ctx);
  2996. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  2997. const char *password);
  2998. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  2999. const char *key_path, const char *password);
  3000. // Server context
  3001. ctx_t create_server_context();
  3002. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3003. const char *password);
  3004. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3005. const char *key_path, const char *password);
  3006. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3007. void set_verify_client(ctx_t ctx, bool require);
  3008. // Session management
  3009. session_t create_session(ctx_t ctx, socket_t sock);
  3010. void free_session(session_t session);
  3011. bool set_sni(session_t session, const char *hostname);
  3012. bool set_hostname(session_t session, const char *hostname);
  3013. // Handshake (non-blocking capable)
  3014. TlsError connect(session_t session);
  3015. TlsError accept(session_t session);
  3016. // Handshake with timeout (blocking until timeout)
  3017. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3018. time_t timeout_usec, TlsError *err);
  3019. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3020. time_t timeout_usec, TlsError *err);
  3021. // I/O (non-blocking capable)
  3022. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3023. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3024. int pending(const_session_t session);
  3025. void shutdown(session_t session, bool graceful);
  3026. // Connection state
  3027. bool is_peer_closed(session_t session, socket_t sock);
  3028. // Certificate verification
  3029. cert_t get_peer_cert(const_session_t session);
  3030. void free_cert(cert_t cert);
  3031. bool verify_hostname(cert_t cert, const char *hostname);
  3032. uint64_t hostname_mismatch_code();
  3033. long get_verify_result(const_session_t session);
  3034. // Certificate introspection
  3035. std::string get_cert_subject_cn(cert_t cert);
  3036. std::string get_cert_issuer_name(cert_t cert);
  3037. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3038. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3039. std::string get_cert_serial(cert_t cert);
  3040. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3041. const char *get_sni(const_session_t session);
  3042. // CA store management
  3043. ca_store_t create_ca_store(const char *pem, size_t len);
  3044. void free_ca_store(ca_store_t store);
  3045. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3046. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3047. std::vector<std::string> get_ca_names(ctx_t ctx);
  3048. // Dynamic certificate update (for servers)
  3049. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3050. const char *password);
  3051. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3052. // Certificate verification callback
  3053. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3054. long get_verify_error(const_session_t session);
  3055. std::string verify_error_string(long error_code);
  3056. // TlsError information
  3057. uint64_t peek_error();
  3058. uint64_t get_error();
  3059. std::string error_string(uint64_t code);
  3060. } // namespace tls
  3061. #endif // CPPHTTPLIB_SSL_ENABLED
  3062. /*
  3063. * Group 1: detail namespace - Non-SSL utilities
  3064. */
  3065. namespace detail {
  3066. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3067. const void *optval, socklen_t optlen) {
  3068. return setsockopt(sock, level, optname,
  3069. #ifdef _WIN32
  3070. reinterpret_cast<const char *>(optval),
  3071. #else
  3072. optval,
  3073. #endif
  3074. optlen) == 0;
  3075. }
  3076. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  3077. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  3078. }
  3079. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3080. time_t sec, time_t usec) {
  3081. #ifdef _WIN32
  3082. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3083. #else
  3084. timeval timeout;
  3085. timeout.tv_sec = static_cast<long>(sec);
  3086. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3087. #endif
  3088. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3089. }
  3090. inline bool is_hex(char c, int &v) {
  3091. if (isdigit(c)) {
  3092. v = c - '0';
  3093. return true;
  3094. } else if ('A' <= c && c <= 'F') {
  3095. v = c - 'A' + 10;
  3096. return true;
  3097. } else if ('a' <= c && c <= 'f') {
  3098. v = c - 'a' + 10;
  3099. return true;
  3100. }
  3101. return false;
  3102. }
  3103. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3104. int &val) {
  3105. if (i >= s.size()) { return false; }
  3106. val = 0;
  3107. for (; cnt; i++, cnt--) {
  3108. if (!s[i]) { return false; }
  3109. auto v = 0;
  3110. if (is_hex(s[i], v)) {
  3111. val = val * 16 + v;
  3112. } else {
  3113. return false;
  3114. }
  3115. }
  3116. return true;
  3117. }
  3118. inline std::string from_i_to_hex(size_t n) {
  3119. static const auto charset = "0123456789abcdef";
  3120. std::string ret;
  3121. do {
  3122. ret = charset[n & 15] + ret;
  3123. n >>= 4;
  3124. } while (n > 0);
  3125. return ret;
  3126. }
  3127. inline std::string compute_etag(const FileStat &fs) {
  3128. if (!fs.is_file()) { return std::string(); }
  3129. // If mtime cannot be determined (negative value indicates an error
  3130. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3131. // value like 0 could collide with a real file that legitimately has
  3132. // mtime == 0 (epoch) and lead to misleading validators.
  3133. auto mtime_raw = fs.mtime();
  3134. if (mtime_raw < 0) { return std::string(); }
  3135. auto mtime = static_cast<size_t>(mtime_raw);
  3136. auto size = fs.size();
  3137. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3138. from_i_to_hex(size) + "\"";
  3139. }
  3140. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3141. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3142. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3143. inline std::string file_mtime_to_http_date(time_t mtime) {
  3144. if (mtime < 0) { return std::string(); }
  3145. struct tm tm_buf;
  3146. #ifdef _WIN32
  3147. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3148. #else
  3149. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3150. #endif
  3151. char buf[64];
  3152. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3153. return std::string();
  3154. }
  3155. return std::string(buf);
  3156. }
  3157. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3158. inline time_t parse_http_date(const std::string &date_str) {
  3159. struct tm tm_buf;
  3160. // Create a classic locale object once for all parsing attempts
  3161. const std::locale classic_locale = std::locale::classic();
  3162. // Try to parse using std::get_time (C++11, cross-platform)
  3163. auto try_parse = [&](const char *fmt) -> bool {
  3164. std::istringstream ss(date_str);
  3165. ss.imbue(classic_locale);
  3166. memset(&tm_buf, 0, sizeof(tm_buf));
  3167. ss >> std::get_time(&tm_buf, fmt);
  3168. return !ss.fail();
  3169. };
  3170. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3171. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3172. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3173. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3174. // asctime format: "Sun Nov 6 08:49:37 1994"
  3175. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3176. return static_cast<time_t>(-1);
  3177. }
  3178. }
  3179. }
  3180. #ifdef _WIN32
  3181. return _mkgmtime(&tm_buf);
  3182. #elif defined _AIX
  3183. return mktime(&tm_buf);
  3184. #else
  3185. return timegm(&tm_buf);
  3186. #endif
  3187. }
  3188. inline bool is_weak_etag(const std::string &s) {
  3189. // Check if the string is a weak ETag (starts with 'W/"')
  3190. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3191. }
  3192. inline bool is_strong_etag(const std::string &s) {
  3193. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3194. // chars)
  3195. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3196. }
  3197. inline size_t to_utf8(int code, char *buff) {
  3198. if (code < 0x0080) {
  3199. buff[0] = static_cast<char>(code & 0x7F);
  3200. return 1;
  3201. } else if (code < 0x0800) {
  3202. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3203. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3204. return 2;
  3205. } else if (code < 0xD800) {
  3206. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3207. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3208. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3209. return 3;
  3210. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3211. return 0;
  3212. } else if (code < 0x10000) {
  3213. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3214. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3215. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3216. return 3;
  3217. } else if (code < 0x110000) {
  3218. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3219. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3220. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3221. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3222. return 4;
  3223. }
  3224. // NOTREACHED
  3225. return 0;
  3226. }
  3227. // NOTE: This code came up with the following stackoverflow post:
  3228. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3229. inline std::string base64_encode(const std::string &in) {
  3230. static const auto lookup =
  3231. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3232. std::string out;
  3233. out.reserve(in.size());
  3234. auto val = 0;
  3235. auto valb = -6;
  3236. for (auto c : in) {
  3237. val = (val << 8) + static_cast<uint8_t>(c);
  3238. valb += 8;
  3239. while (valb >= 0) {
  3240. out.push_back(lookup[(val >> valb) & 0x3F]);
  3241. valb -= 6;
  3242. }
  3243. }
  3244. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3245. while (out.size() % 4) {
  3246. out.push_back('=');
  3247. }
  3248. return out;
  3249. }
  3250. inline bool is_valid_path(const std::string &path) {
  3251. size_t level = 0;
  3252. size_t i = 0;
  3253. // Skip slash
  3254. while (i < path.size() && path[i] == '/') {
  3255. i++;
  3256. }
  3257. while (i < path.size()) {
  3258. // Read component
  3259. auto beg = i;
  3260. while (i < path.size() && path[i] != '/') {
  3261. if (path[i] == '\0') {
  3262. return false;
  3263. } else if (path[i] == '\\') {
  3264. return false;
  3265. }
  3266. i++;
  3267. }
  3268. auto len = i - beg;
  3269. assert(len > 0);
  3270. if (!path.compare(beg, len, ".")) {
  3271. ;
  3272. } else if (!path.compare(beg, len, "..")) {
  3273. if (level == 0) { return false; }
  3274. level--;
  3275. } else {
  3276. level++;
  3277. }
  3278. // Skip slash
  3279. while (i < path.size() && path[i] == '/') {
  3280. i++;
  3281. }
  3282. }
  3283. return true;
  3284. }
  3285. inline FileStat::FileStat(const std::string &path) {
  3286. #if defined(_WIN32)
  3287. auto wpath = u8string_to_wstring(path.c_str());
  3288. ret_ = _wstat(wpath.c_str(), &st_);
  3289. #else
  3290. ret_ = stat(path.c_str(), &st_);
  3291. #endif
  3292. }
  3293. inline bool FileStat::is_file() const {
  3294. return ret_ >= 0 && S_ISREG(st_.st_mode);
  3295. }
  3296. inline bool FileStat::is_dir() const {
  3297. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  3298. }
  3299. inline time_t FileStat::mtime() const {
  3300. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  3301. : static_cast<time_t>(-1);
  3302. }
  3303. inline size_t FileStat::size() const {
  3304. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  3305. }
  3306. inline std::string encode_path(const std::string &s) {
  3307. std::string result;
  3308. result.reserve(s.size());
  3309. for (size_t i = 0; s[i]; i++) {
  3310. switch (s[i]) {
  3311. case ' ': result += "%20"; break;
  3312. case '+': result += "%2B"; break;
  3313. case '\r': result += "%0D"; break;
  3314. case '\n': result += "%0A"; break;
  3315. case '\'': result += "%27"; break;
  3316. case ',': result += "%2C"; break;
  3317. // case ':': result += "%3A"; break; // ok? probably...
  3318. case ';': result += "%3B"; break;
  3319. default:
  3320. auto c = static_cast<uint8_t>(s[i]);
  3321. if (c >= 0x80) {
  3322. result += '%';
  3323. char hex[4];
  3324. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  3325. assert(len == 2);
  3326. result.append(hex, static_cast<size_t>(len));
  3327. } else {
  3328. result += s[i];
  3329. }
  3330. break;
  3331. }
  3332. }
  3333. return result;
  3334. }
  3335. inline std::string file_extension(const std::string &path) {
  3336. std::smatch m;
  3337. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  3338. if (std::regex_search(path, m, re)) { return m[1].str(); }
  3339. return std::string();
  3340. }
  3341. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  3342. template <typename T>
  3343. inline bool parse_header(const char *beg, const char *end, T fn);
  3344. template <typename T>
  3345. inline bool parse_header(const char *beg, const char *end, T fn) {
  3346. // Skip trailing spaces and tabs.
  3347. while (beg < end && is_space_or_tab(end[-1])) {
  3348. end--;
  3349. }
  3350. auto p = beg;
  3351. while (p < end && *p != ':') {
  3352. p++;
  3353. }
  3354. auto name = std::string(beg, p);
  3355. if (!detail::fields::is_field_name(name)) { return false; }
  3356. if (p == end) { return false; }
  3357. auto key_end = p;
  3358. if (*p++ != ':') { return false; }
  3359. while (p < end && is_space_or_tab(*p)) {
  3360. p++;
  3361. }
  3362. if (p <= end) {
  3363. auto key_len = key_end - beg;
  3364. if (!key_len) { return false; }
  3365. auto key = std::string(beg, key_end);
  3366. auto val = std::string(p, end);
  3367. if (!detail::fields::is_field_value(val)) { return false; }
  3368. if (case_ignore::equal(key, "Location") ||
  3369. case_ignore::equal(key, "Referer")) {
  3370. fn(key, val);
  3371. } else {
  3372. fn(key, decode_path_component(val));
  3373. }
  3374. return true;
  3375. }
  3376. return false;
  3377. }
  3378. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3379. const Headers &src_headers) {
  3380. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3381. // transfer coding is complete when a chunk with a chunk-size of zero is
  3382. // received, possibly followed by a trailer section, and finally terminated by
  3383. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3384. //
  3385. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3386. // doesn't care for the existence of the final CRLF. In other words, it seems
  3387. // to be ok whether the final CRLF exists or not in the chunked data.
  3388. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3389. //
  3390. // According to the reference code in RFC 9112, cpp-httplib now allows
  3391. // chunked transfer coding data without the final CRLF.
  3392. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3393. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3394. "transfer-encoding",
  3395. "content-length",
  3396. "host",
  3397. "authorization",
  3398. "www-authenticate",
  3399. "proxy-authenticate",
  3400. "proxy-authorization",
  3401. "cookie",
  3402. "set-cookie",
  3403. "cache-control",
  3404. "expect",
  3405. "max-forwards",
  3406. "pragma",
  3407. "range",
  3408. "te",
  3409. "age",
  3410. "expires",
  3411. "date",
  3412. "location",
  3413. "retry-after",
  3414. "vary",
  3415. "warning",
  3416. "content-encoding",
  3417. "content-type",
  3418. "content-range",
  3419. "trailer"};
  3420. case_ignore::unordered_set<std::string> declared_trailers;
  3421. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  3422. if (trailer_header && std::strlen(trailer_header)) {
  3423. auto len = std::strlen(trailer_header);
  3424. split(trailer_header, trailer_header + len, ',',
  3425. [&](const char *b, const char *e) {
  3426. const char *kbeg = b;
  3427. const char *kend = e;
  3428. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  3429. ++kbeg;
  3430. }
  3431. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  3432. --kend;
  3433. }
  3434. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  3435. if (!key.empty() &&
  3436. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  3437. declared_trailers.insert(key);
  3438. }
  3439. });
  3440. }
  3441. size_t trailer_header_count = 0;
  3442. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3443. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3444. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3445. constexpr auto line_terminator_len = 2;
  3446. auto line_beg = line_reader.ptr();
  3447. auto line_end =
  3448. line_reader.ptr() + line_reader.size() - line_terminator_len;
  3449. if (!parse_header(line_beg, line_end,
  3450. [&](const std::string &key, const std::string &val) {
  3451. if (declared_trailers.find(key) !=
  3452. declared_trailers.end()) {
  3453. dest.emplace(key, val);
  3454. trailer_header_count++;
  3455. }
  3456. })) {
  3457. return false;
  3458. }
  3459. if (!line_reader.getline()) { return false; }
  3460. }
  3461. return true;
  3462. }
  3463. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  3464. size_t right) {
  3465. while (b + left < e && is_space_or_tab(b[left])) {
  3466. left++;
  3467. }
  3468. while (right > 0 && is_space_or_tab(b[right - 1])) {
  3469. right--;
  3470. }
  3471. return std::make_pair(left, right);
  3472. }
  3473. inline std::string trim_copy(const std::string &s) {
  3474. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  3475. return s.substr(r.first, r.second - r.first);
  3476. }
  3477. inline std::string trim_double_quotes_copy(const std::string &s) {
  3478. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  3479. return s.substr(1, s.size() - 2);
  3480. }
  3481. return s;
  3482. }
  3483. inline void
  3484. divide(const char *data, std::size_t size, char d,
  3485. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3486. fn) {
  3487. const auto it = std::find(data, data + size, d);
  3488. const auto found = static_cast<std::size_t>(it != data + size);
  3489. const auto lhs_data = data;
  3490. const auto lhs_size = static_cast<std::size_t>(it - data);
  3491. const auto rhs_data = it + found;
  3492. const auto rhs_size = size - lhs_size - found;
  3493. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  3494. }
  3495. inline void
  3496. divide(const std::string &str, char d,
  3497. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3498. fn) {
  3499. divide(str.data(), str.size(), d, std::move(fn));
  3500. }
  3501. inline void split(const char *b, const char *e, char d,
  3502. std::function<void(const char *, const char *)> fn) {
  3503. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  3504. }
  3505. inline void split(const char *b, const char *e, char d, size_t m,
  3506. std::function<void(const char *, const char *)> fn) {
  3507. size_t i = 0;
  3508. size_t beg = 0;
  3509. size_t count = 1;
  3510. while (e ? (b + i < e) : (b[i] != '\0')) {
  3511. if (b[i] == d && count < m) {
  3512. auto r = trim(b, e, beg, i);
  3513. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3514. beg = i + 1;
  3515. count++;
  3516. }
  3517. i++;
  3518. }
  3519. if (i) {
  3520. auto r = trim(b, e, beg, i);
  3521. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3522. }
  3523. }
  3524. inline bool split_find(const char *b, const char *e, char d, size_t m,
  3525. std::function<bool(const char *, const char *)> fn) {
  3526. size_t i = 0;
  3527. size_t beg = 0;
  3528. size_t count = 1;
  3529. while (e ? (b + i < e) : (b[i] != '\0')) {
  3530. if (b[i] == d && count < m) {
  3531. auto r = trim(b, e, beg, i);
  3532. if (r.first < r.second) {
  3533. auto found = fn(&b[r.first], &b[r.second]);
  3534. if (found) { return true; }
  3535. }
  3536. beg = i + 1;
  3537. count++;
  3538. }
  3539. i++;
  3540. }
  3541. if (i) {
  3542. auto r = trim(b, e, beg, i);
  3543. if (r.first < r.second) {
  3544. auto found = fn(&b[r.first], &b[r.second]);
  3545. if (found) { return true; }
  3546. }
  3547. }
  3548. return false;
  3549. }
  3550. inline bool split_find(const char *b, const char *e, char d,
  3551. std::function<bool(const char *, const char *)> fn) {
  3552. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  3553. std::move(fn));
  3554. }
  3555. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  3556. size_t fixed_buffer_size)
  3557. : strm_(strm), fixed_buffer_(fixed_buffer),
  3558. fixed_buffer_size_(fixed_buffer_size) {}
  3559. inline const char *stream_line_reader::ptr() const {
  3560. if (growable_buffer_.empty()) {
  3561. return fixed_buffer_;
  3562. } else {
  3563. return growable_buffer_.data();
  3564. }
  3565. }
  3566. inline size_t stream_line_reader::size() const {
  3567. if (growable_buffer_.empty()) {
  3568. return fixed_buffer_used_size_;
  3569. } else {
  3570. return growable_buffer_.size();
  3571. }
  3572. }
  3573. inline bool stream_line_reader::end_with_crlf() const {
  3574. auto end = ptr() + size();
  3575. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  3576. }
  3577. inline bool stream_line_reader::getline() {
  3578. fixed_buffer_used_size_ = 0;
  3579. growable_buffer_.clear();
  3580. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3581. char prev_byte = 0;
  3582. #endif
  3583. for (size_t i = 0;; i++) {
  3584. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  3585. // Treat exceptionally long lines as an error to
  3586. // prevent infinite loops/memory exhaustion
  3587. return false;
  3588. }
  3589. char byte;
  3590. auto n = strm_.read(&byte, 1);
  3591. if (n < 0) {
  3592. return false;
  3593. } else if (n == 0) {
  3594. if (i == 0) {
  3595. return false;
  3596. } else {
  3597. break;
  3598. }
  3599. }
  3600. append(byte);
  3601. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3602. if (byte == '\n') { break; }
  3603. #else
  3604. if (prev_byte == '\r' && byte == '\n') { break; }
  3605. prev_byte = byte;
  3606. #endif
  3607. }
  3608. return true;
  3609. }
  3610. inline void stream_line_reader::append(char c) {
  3611. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  3612. fixed_buffer_[fixed_buffer_used_size_++] = c;
  3613. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  3614. } else {
  3615. if (growable_buffer_.empty()) {
  3616. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  3617. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  3618. }
  3619. growable_buffer_ += c;
  3620. }
  3621. }
  3622. inline mmap::mmap(const char *path) { open(path); }
  3623. inline mmap::~mmap() { close(); }
  3624. inline bool mmap::open(const char *path) {
  3625. close();
  3626. #if defined(_WIN32)
  3627. auto wpath = u8string_to_wstring(path);
  3628. if (wpath.empty()) { return false; }
  3629. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  3630. OPEN_EXISTING, NULL);
  3631. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  3632. LARGE_INTEGER size{};
  3633. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  3634. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  3635. // See:
  3636. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  3637. if (static_cast<ULONGLONG>(size.QuadPart) >
  3638. (std::numeric_limits<decltype(size_)>::max)()) {
  3639. // `size_t` might be 32-bits, on 32-bits Windows.
  3640. return false;
  3641. }
  3642. size_ = static_cast<size_t>(size.QuadPart);
  3643. hMapping_ =
  3644. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  3645. // Special treatment for an empty file...
  3646. if (hMapping_ == NULL && size_ == 0) {
  3647. close();
  3648. is_open_empty_file = true;
  3649. return true;
  3650. }
  3651. if (hMapping_ == NULL) {
  3652. close();
  3653. return false;
  3654. }
  3655. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  3656. if (addr_ == nullptr) {
  3657. close();
  3658. return false;
  3659. }
  3660. #else
  3661. fd_ = ::open(path, O_RDONLY);
  3662. if (fd_ == -1) { return false; }
  3663. struct stat sb;
  3664. if (fstat(fd_, &sb) == -1) {
  3665. close();
  3666. return false;
  3667. }
  3668. size_ = static_cast<size_t>(sb.st_size);
  3669. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  3670. // Special treatment for an empty file...
  3671. if (addr_ == MAP_FAILED && size_ == 0) {
  3672. close();
  3673. is_open_empty_file = true;
  3674. return false;
  3675. }
  3676. #endif
  3677. return true;
  3678. }
  3679. inline bool mmap::is_open() const {
  3680. return is_open_empty_file ? true : addr_ != nullptr;
  3681. }
  3682. inline size_t mmap::size() const { return size_; }
  3683. inline const char *mmap::data() const {
  3684. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  3685. }
  3686. inline void mmap::close() {
  3687. #if defined(_WIN32)
  3688. if (addr_) {
  3689. ::UnmapViewOfFile(addr_);
  3690. addr_ = nullptr;
  3691. }
  3692. if (hMapping_) {
  3693. ::CloseHandle(hMapping_);
  3694. hMapping_ = NULL;
  3695. }
  3696. if (hFile_ != INVALID_HANDLE_VALUE) {
  3697. ::CloseHandle(hFile_);
  3698. hFile_ = INVALID_HANDLE_VALUE;
  3699. }
  3700. is_open_empty_file = false;
  3701. #else
  3702. if (addr_ != nullptr) {
  3703. munmap(addr_, size_);
  3704. addr_ = nullptr;
  3705. }
  3706. if (fd_ != -1) {
  3707. ::close(fd_);
  3708. fd_ = -1;
  3709. }
  3710. #endif
  3711. size_ = 0;
  3712. }
  3713. inline int close_socket(socket_t sock) {
  3714. #ifdef _WIN32
  3715. return closesocket(sock);
  3716. #else
  3717. return close(sock);
  3718. #endif
  3719. }
  3720. template <typename T> inline ssize_t handle_EINTR(T fn) {
  3721. ssize_t res = 0;
  3722. while (true) {
  3723. res = fn();
  3724. if (res < 0 && errno == EINTR) {
  3725. std::this_thread::sleep_for(std::chrono::microseconds{1});
  3726. continue;
  3727. }
  3728. break;
  3729. }
  3730. return res;
  3731. }
  3732. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  3733. return handle_EINTR([&]() {
  3734. return recv(sock,
  3735. #ifdef _WIN32
  3736. static_cast<char *>(ptr), static_cast<int>(size),
  3737. #else
  3738. ptr, size,
  3739. #endif
  3740. flags);
  3741. });
  3742. }
  3743. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  3744. int flags) {
  3745. return handle_EINTR([&]() {
  3746. return send(sock,
  3747. #ifdef _WIN32
  3748. static_cast<const char *>(ptr), static_cast<int>(size),
  3749. #else
  3750. ptr, size,
  3751. #endif
  3752. flags);
  3753. });
  3754. }
  3755. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  3756. #ifdef _WIN32
  3757. return ::WSAPoll(fds, nfds, timeout);
  3758. #else
  3759. return ::poll(fds, nfds, timeout);
  3760. #endif
  3761. }
  3762. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  3763. time_t usec) {
  3764. struct pollfd pfd;
  3765. pfd.fd = sock;
  3766. pfd.events = events;
  3767. pfd.revents = 0;
  3768. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3769. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  3770. }
  3771. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  3772. return select_impl(sock, POLLIN, sec, usec);
  3773. }
  3774. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  3775. return select_impl(sock, POLLOUT, sec, usec);
  3776. }
  3777. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  3778. time_t usec) {
  3779. struct pollfd pfd_read;
  3780. pfd_read.fd = sock;
  3781. pfd_read.events = POLLIN | POLLOUT;
  3782. pfd_read.revents = 0;
  3783. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3784. auto poll_res =
  3785. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  3786. if (poll_res == 0) { return Error::ConnectionTimeout; }
  3787. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  3788. auto error = 0;
  3789. socklen_t len = sizeof(error);
  3790. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3791. reinterpret_cast<char *>(&error), &len);
  3792. auto successful = res >= 0 && !error;
  3793. return successful ? Error::Success : Error::Connection;
  3794. }
  3795. return Error::Connection;
  3796. }
  3797. inline bool is_socket_alive(socket_t sock) {
  3798. const auto val = detail::select_read(sock, 0, 0);
  3799. if (val == 0) {
  3800. return true;
  3801. } else if (val < 0 && errno == EBADF) {
  3802. return false;
  3803. }
  3804. char buf[1];
  3805. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  3806. }
  3807. class SocketStream final : public Stream {
  3808. public:
  3809. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3810. time_t write_timeout_sec, time_t write_timeout_usec,
  3811. time_t max_timeout_msec = 0,
  3812. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3813. (std::chrono::steady_clock::time_point::min)());
  3814. ~SocketStream() override;
  3815. bool is_readable() const override;
  3816. bool wait_readable() const override;
  3817. bool wait_writable() const override;
  3818. ssize_t read(char *ptr, size_t size) override;
  3819. ssize_t write(const char *ptr, size_t size) override;
  3820. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3821. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3822. socket_t socket() const override;
  3823. time_t duration() const override;
  3824. private:
  3825. socket_t sock_;
  3826. time_t read_timeout_sec_;
  3827. time_t read_timeout_usec_;
  3828. time_t write_timeout_sec_;
  3829. time_t write_timeout_usec_;
  3830. time_t max_timeout_msec_;
  3831. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3832. std::vector<char> read_buff_;
  3833. size_t read_buff_off_ = 0;
  3834. size_t read_buff_content_size_ = 0;
  3835. static const size_t read_buff_size_ = 1024l * 4;
  3836. };
  3837. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3838. time_t keep_alive_timeout_sec) {
  3839. using namespace std::chrono;
  3840. const auto interval_usec =
  3841. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  3842. // Avoid expensive `steady_clock::now()` call for the first time
  3843. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  3844. const auto start = steady_clock::now() - microseconds{interval_usec};
  3845. const auto timeout = seconds{keep_alive_timeout_sec};
  3846. while (true) {
  3847. if (svr_sock == INVALID_SOCKET) {
  3848. break; // Server socket is closed
  3849. }
  3850. auto val = select_read(sock, 0, interval_usec);
  3851. if (val < 0) {
  3852. break; // Ssocket error
  3853. } else if (val == 0) {
  3854. if (steady_clock::now() - start > timeout) {
  3855. break; // Timeout
  3856. }
  3857. } else {
  3858. return true; // Ready for read
  3859. }
  3860. }
  3861. return false;
  3862. }
  3863. template <typename T>
  3864. inline bool
  3865. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3866. size_t keep_alive_max_count,
  3867. time_t keep_alive_timeout_sec, T callback) {
  3868. assert(keep_alive_max_count > 0);
  3869. auto ret = false;
  3870. auto count = keep_alive_max_count;
  3871. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  3872. auto close_connection = count == 1;
  3873. auto connection_closed = false;
  3874. ret = callback(close_connection, connection_closed);
  3875. if (!ret || connection_closed) { break; }
  3876. count--;
  3877. }
  3878. return ret;
  3879. }
  3880. template <typename T>
  3881. inline bool
  3882. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3883. size_t keep_alive_max_count,
  3884. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  3885. time_t read_timeout_usec, time_t write_timeout_sec,
  3886. time_t write_timeout_usec, T callback) {
  3887. return process_server_socket_core(
  3888. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  3889. [&](bool close_connection, bool &connection_closed) {
  3890. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3891. write_timeout_sec, write_timeout_usec);
  3892. return callback(strm, close_connection, connection_closed);
  3893. });
  3894. }
  3895. inline bool process_client_socket(
  3896. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3897. time_t write_timeout_sec, time_t write_timeout_usec,
  3898. time_t max_timeout_msec,
  3899. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3900. std::function<bool(Stream &)> callback) {
  3901. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3902. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  3903. start_time);
  3904. return callback(strm);
  3905. }
  3906. inline int shutdown_socket(socket_t sock) {
  3907. #ifdef _WIN32
  3908. return shutdown(sock, SD_BOTH);
  3909. #else
  3910. return shutdown(sock, SHUT_RDWR);
  3911. #endif
  3912. }
  3913. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  3914. if (s.size() > 1 && s[0] == '\0') {
  3915. auto ret = s;
  3916. ret[0] = '@';
  3917. return ret;
  3918. }
  3919. return s;
  3920. }
  3921. inline std::string
  3922. unescape_abstract_namespace_unix_domain(const std::string &s) {
  3923. if (s.size() > 1 && s[0] == '@') {
  3924. auto ret = s;
  3925. ret[0] = '\0';
  3926. return ret;
  3927. }
  3928. return s;
  3929. }
  3930. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  3931. const struct addrinfo *hints,
  3932. struct addrinfo **res, time_t timeout_sec) {
  3933. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  3934. if (timeout_sec <= 0) {
  3935. // No timeout specified, use standard getaddrinfo
  3936. return getaddrinfo(node, service, hints, res);
  3937. }
  3938. #ifdef _WIN32
  3939. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  3940. OVERLAPPED overlapped = {0};
  3941. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  3942. if (!event) { return EAI_FAIL; }
  3943. overlapped.hEvent = event;
  3944. PADDRINFOEXW result_addrinfo = nullptr;
  3945. HANDLE cancel_handle = nullptr;
  3946. ADDRINFOEXW hints_ex = {0};
  3947. if (hints) {
  3948. hints_ex.ai_flags = hints->ai_flags;
  3949. hints_ex.ai_family = hints->ai_family;
  3950. hints_ex.ai_socktype = hints->ai_socktype;
  3951. hints_ex.ai_protocol = hints->ai_protocol;
  3952. }
  3953. auto wnode = u8string_to_wstring(node);
  3954. auto wservice = u8string_to_wstring(service);
  3955. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  3956. hints ? &hints_ex : nullptr, &result_addrinfo,
  3957. nullptr, &overlapped, nullptr, &cancel_handle);
  3958. if (ret == WSA_IO_PENDING) {
  3959. auto wait_result =
  3960. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  3961. if (wait_result == WAIT_TIMEOUT) {
  3962. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  3963. ::CloseHandle(event);
  3964. return EAI_AGAIN;
  3965. }
  3966. DWORD bytes_returned;
  3967. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  3968. &bytes_returned, FALSE)) {
  3969. ::CloseHandle(event);
  3970. return ::WSAGetLastError();
  3971. }
  3972. }
  3973. ::CloseHandle(event);
  3974. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  3975. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  3976. return 0;
  3977. }
  3978. return ret;
  3979. #elif TARGET_OS_MAC
  3980. if (!node) { return EAI_NONAME; }
  3981. // macOS implementation using CFHost API for asynchronous DNS resolution
  3982. CFStringRef hostname_ref = CFStringCreateWithCString(
  3983. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  3984. if (!hostname_ref) { return EAI_MEMORY; }
  3985. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  3986. CFRelease(hostname_ref);
  3987. if (!host_ref) { return EAI_MEMORY; }
  3988. // Set up context for callback
  3989. struct CFHostContext {
  3990. bool completed = false;
  3991. bool success = false;
  3992. CFArrayRef addresses = nullptr;
  3993. std::mutex mutex;
  3994. std::condition_variable cv;
  3995. } context;
  3996. CFHostClientContext client_context;
  3997. memset(&client_context, 0, sizeof(client_context));
  3998. client_context.info = &context;
  3999. // Set callback
  4000. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4001. const CFStreamError *error, void *info) {
  4002. auto ctx = static_cast<CFHostContext *>(info);
  4003. std::lock_guard<std::mutex> lock(ctx->mutex);
  4004. if (error && error->error != 0) {
  4005. ctx->success = false;
  4006. } else {
  4007. Boolean hasBeenResolved;
  4008. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4009. if (ctx->addresses && hasBeenResolved) {
  4010. CFRetain(ctx->addresses);
  4011. ctx->success = true;
  4012. } else {
  4013. ctx->success = false;
  4014. }
  4015. }
  4016. ctx->completed = true;
  4017. ctx->cv.notify_one();
  4018. };
  4019. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4020. CFRelease(host_ref);
  4021. return EAI_SYSTEM;
  4022. }
  4023. // Schedule on run loop
  4024. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4025. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4026. // Start resolution
  4027. CFStreamError stream_error;
  4028. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4029. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4030. CFRelease(host_ref);
  4031. return EAI_FAIL;
  4032. }
  4033. // Wait for completion with timeout
  4034. auto timeout_time =
  4035. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4036. bool timed_out = false;
  4037. {
  4038. std::unique_lock<std::mutex> lock(context.mutex);
  4039. while (!context.completed) {
  4040. auto now = std::chrono::steady_clock::now();
  4041. if (now >= timeout_time) {
  4042. timed_out = true;
  4043. break;
  4044. }
  4045. // Run the runloop for a short time
  4046. lock.unlock();
  4047. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4048. lock.lock();
  4049. }
  4050. }
  4051. // Clean up
  4052. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4053. CFHostSetClient(host_ref, nullptr, nullptr);
  4054. if (timed_out || !context.completed) {
  4055. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4056. CFRelease(host_ref);
  4057. return EAI_AGAIN;
  4058. }
  4059. if (!context.success || !context.addresses) {
  4060. CFRelease(host_ref);
  4061. return EAI_NODATA;
  4062. }
  4063. // Convert CFArray to addrinfo
  4064. CFIndex count = CFArrayGetCount(context.addresses);
  4065. if (count == 0) {
  4066. CFRelease(context.addresses);
  4067. CFRelease(host_ref);
  4068. return EAI_NODATA;
  4069. }
  4070. struct addrinfo *result_addrinfo = nullptr;
  4071. struct addrinfo **current = &result_addrinfo;
  4072. for (CFIndex i = 0; i < count; i++) {
  4073. CFDataRef addr_data =
  4074. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4075. if (!addr_data) continue;
  4076. const struct sockaddr *sockaddr_ptr =
  4077. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4078. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4079. // Allocate addrinfo structure
  4080. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4081. if (!*current) {
  4082. freeaddrinfo(result_addrinfo);
  4083. CFRelease(context.addresses);
  4084. CFRelease(host_ref);
  4085. return EAI_MEMORY;
  4086. }
  4087. memset(*current, 0, sizeof(struct addrinfo));
  4088. // Set up addrinfo fields
  4089. (*current)->ai_family = sockaddr_ptr->sa_family;
  4090. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4091. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4092. (*current)->ai_addrlen = sockaddr_len;
  4093. // Copy sockaddr
  4094. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4095. if (!(*current)->ai_addr) {
  4096. freeaddrinfo(result_addrinfo);
  4097. CFRelease(context.addresses);
  4098. CFRelease(host_ref);
  4099. return EAI_MEMORY;
  4100. }
  4101. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4102. // Set port if service is specified
  4103. if (service && strlen(service) > 0) {
  4104. int port = atoi(service);
  4105. if (port > 0) {
  4106. if (sockaddr_ptr->sa_family == AF_INET) {
  4107. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4108. ->sin_port = htons(static_cast<uint16_t>(port));
  4109. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4110. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4111. ->sin6_port = htons(static_cast<uint16_t>(port));
  4112. }
  4113. }
  4114. }
  4115. current = &((*current)->ai_next);
  4116. }
  4117. CFRelease(context.addresses);
  4118. CFRelease(host_ref);
  4119. *res = result_addrinfo;
  4120. return 0;
  4121. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  4122. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  4123. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  4124. struct gaicb request;
  4125. struct gaicb *requests[1] = {&request};
  4126. struct sigevent sevp;
  4127. struct timespec timeout;
  4128. // Initialize the request structure
  4129. memset(&request, 0, sizeof(request));
  4130. request.ar_name = node;
  4131. request.ar_service = service;
  4132. request.ar_request = hints;
  4133. // Set up timeout
  4134. timeout.tv_sec = timeout_sec;
  4135. timeout.tv_nsec = 0;
  4136. // Initialize sigevent structure (not used, but required)
  4137. memset(&sevp, 0, sizeof(sevp));
  4138. sevp.sigev_notify = SIGEV_NONE;
  4139. // Start asynchronous resolution
  4140. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  4141. if (start_result != 0) { return start_result; }
  4142. // Wait for completion with timeout
  4143. int wait_result =
  4144. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  4145. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  4146. // Completed successfully, get the result
  4147. int gai_result = gai_error(&request);
  4148. if (gai_result == 0) {
  4149. *res = request.ar_result;
  4150. return 0;
  4151. } else {
  4152. // Clean up on error
  4153. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  4154. return gai_result;
  4155. }
  4156. } else if (wait_result == EAI_AGAIN) {
  4157. // Timeout occurred, cancel the request
  4158. gai_cancel(&request);
  4159. return EAI_AGAIN;
  4160. } else {
  4161. // Other error occurred
  4162. gai_cancel(&request);
  4163. return wait_result;
  4164. }
  4165. #else
  4166. // Fallback implementation using thread-based timeout for other Unix systems
  4167. struct GetAddrInfoState {
  4168. ~GetAddrInfoState() {
  4169. if (info) { freeaddrinfo(info); }
  4170. }
  4171. std::mutex mutex;
  4172. std::condition_variable result_cv;
  4173. bool completed = false;
  4174. int result = EAI_SYSTEM;
  4175. std::string node;
  4176. std::string service;
  4177. struct addrinfo hints;
  4178. struct addrinfo *info = nullptr;
  4179. };
  4180. // Allocate on the heap, so the resolver thread can keep using the data.
  4181. auto state = std::make_shared<GetAddrInfoState>();
  4182. if (node) { state->node = node; }
  4183. state->service = service;
  4184. state->hints = *hints;
  4185. std::thread resolve_thread([state]() {
  4186. auto thread_result =
  4187. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4188. &state->info);
  4189. std::lock_guard<std::mutex> lock(state->mutex);
  4190. state->result = thread_result;
  4191. state->completed = true;
  4192. state->result_cv.notify_one();
  4193. });
  4194. // Wait for completion or timeout
  4195. std::unique_lock<std::mutex> lock(state->mutex);
  4196. auto finished =
  4197. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4198. [&] { return state->completed; });
  4199. if (finished) {
  4200. // Operation completed within timeout
  4201. resolve_thread.join();
  4202. *res = state->info;
  4203. state->info = nullptr; // Pass ownership to caller
  4204. return state->result;
  4205. } else {
  4206. // Timeout occurred
  4207. resolve_thread.detach(); // Let the thread finish in background
  4208. return EAI_AGAIN; // Return timeout error
  4209. }
  4210. #endif
  4211. #else
  4212. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4213. return getaddrinfo(node, service, hints, res);
  4214. #endif
  4215. }
  4216. template <typename BindOrConnect>
  4217. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4218. int address_family, int socket_flags, bool tcp_nodelay,
  4219. bool ipv6_v6only, SocketOptions socket_options,
  4220. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4221. // Get address info
  4222. const char *node = nullptr;
  4223. struct addrinfo hints;
  4224. struct addrinfo *result;
  4225. memset(&hints, 0, sizeof(struct addrinfo));
  4226. hints.ai_socktype = SOCK_STREAM;
  4227. hints.ai_protocol = IPPROTO_IP;
  4228. if (!ip.empty()) {
  4229. node = ip.c_str();
  4230. // Ask getaddrinfo to convert IP in c-string to address
  4231. hints.ai_family = AF_UNSPEC;
  4232. hints.ai_flags = AI_NUMERICHOST;
  4233. } else {
  4234. if (!host.empty()) { node = host.c_str(); }
  4235. hints.ai_family = address_family;
  4236. hints.ai_flags = socket_flags;
  4237. }
  4238. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  4239. if (hints.ai_family == AF_UNIX) {
  4240. const auto addrlen = host.length();
  4241. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  4242. #ifdef SOCK_CLOEXEC
  4243. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  4244. hints.ai_protocol);
  4245. #else
  4246. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4247. #endif
  4248. if (sock != INVALID_SOCKET) {
  4249. sockaddr_un addr{};
  4250. addr.sun_family = AF_UNIX;
  4251. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  4252. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  4253. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  4254. hints.ai_addrlen = static_cast<socklen_t>(
  4255. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  4256. #ifndef SOCK_CLOEXEC
  4257. #ifndef _WIN32
  4258. fcntl(sock, F_SETFD, FD_CLOEXEC);
  4259. #endif
  4260. #endif
  4261. if (socket_options) { socket_options(sock); }
  4262. #ifdef _WIN32
  4263. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  4264. // remove the option.
  4265. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  4266. #endif
  4267. bool dummy;
  4268. if (!bind_or_connect(sock, hints, dummy)) {
  4269. close_socket(sock);
  4270. sock = INVALID_SOCKET;
  4271. }
  4272. }
  4273. return sock;
  4274. }
  4275. #endif
  4276. auto service = std::to_string(port);
  4277. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  4278. timeout_sec)) {
  4279. #if defined __linux__ && !defined __ANDROID__
  4280. res_init();
  4281. #endif
  4282. return INVALID_SOCKET;
  4283. }
  4284. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4285. for (auto rp = result; rp; rp = rp->ai_next) {
  4286. // Create a socket
  4287. #ifdef _WIN32
  4288. auto sock =
  4289. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  4290. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  4291. /**
  4292. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  4293. * and above the socket creation fails on older Windows Systems.
  4294. *
  4295. * Let's try to create a socket the old way in this case.
  4296. *
  4297. * Reference:
  4298. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  4299. *
  4300. * WSA_FLAG_NO_HANDLE_INHERIT:
  4301. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  4302. * SP1, and later
  4303. *
  4304. */
  4305. if (sock == INVALID_SOCKET) {
  4306. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4307. }
  4308. #else
  4309. #ifdef SOCK_CLOEXEC
  4310. auto sock =
  4311. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  4312. #else
  4313. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4314. #endif
  4315. #endif
  4316. if (sock == INVALID_SOCKET) { continue; }
  4317. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  4318. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  4319. close_socket(sock);
  4320. continue;
  4321. }
  4322. #endif
  4323. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  4324. if (rp->ai_family == AF_INET6) {
  4325. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  4326. }
  4327. if (socket_options) { socket_options(sock); }
  4328. // bind or connect
  4329. auto quit = false;
  4330. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  4331. close_socket(sock);
  4332. if (quit) { break; }
  4333. }
  4334. return INVALID_SOCKET;
  4335. }
  4336. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  4337. #ifdef _WIN32
  4338. auto flags = nonblocking ? 1UL : 0UL;
  4339. ioctlsocket(sock, FIONBIO, &flags);
  4340. #else
  4341. auto flags = fcntl(sock, F_GETFL, 0);
  4342. fcntl(sock, F_SETFL,
  4343. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  4344. #endif
  4345. }
  4346. inline bool is_connection_error() {
  4347. #ifdef _WIN32
  4348. return WSAGetLastError() != WSAEWOULDBLOCK;
  4349. #else
  4350. return errno != EINPROGRESS;
  4351. #endif
  4352. }
  4353. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  4354. struct addrinfo hints;
  4355. struct addrinfo *result;
  4356. memset(&hints, 0, sizeof(struct addrinfo));
  4357. hints.ai_family = AF_UNSPEC;
  4358. hints.ai_socktype = SOCK_STREAM;
  4359. hints.ai_protocol = 0;
  4360. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  4361. return false;
  4362. }
  4363. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4364. auto ret = false;
  4365. for (auto rp = result; rp; rp = rp->ai_next) {
  4366. const auto &ai = *rp;
  4367. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4368. ret = true;
  4369. break;
  4370. }
  4371. }
  4372. return ret;
  4373. }
  4374. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  4375. #define USE_IF2IP
  4376. #endif
  4377. #ifdef USE_IF2IP
  4378. inline std::string if2ip(int address_family, const std::string &ifn) {
  4379. struct ifaddrs *ifap;
  4380. getifaddrs(&ifap);
  4381. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  4382. std::string addr_candidate;
  4383. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  4384. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  4385. (AF_UNSPEC == address_family ||
  4386. ifa->ifa_addr->sa_family == address_family)) {
  4387. if (ifa->ifa_addr->sa_family == AF_INET) {
  4388. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  4389. char buf[INET_ADDRSTRLEN];
  4390. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  4391. return std::string(buf, INET_ADDRSTRLEN);
  4392. }
  4393. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  4394. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  4395. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  4396. char buf[INET6_ADDRSTRLEN] = {};
  4397. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  4398. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  4399. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  4400. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  4401. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  4402. } else {
  4403. return std::string(buf, INET6_ADDRSTRLEN);
  4404. }
  4405. }
  4406. }
  4407. }
  4408. }
  4409. }
  4410. return addr_candidate;
  4411. }
  4412. #endif
  4413. inline socket_t create_client_socket(
  4414. const std::string &host, const std::string &ip, int port,
  4415. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  4416. SocketOptions socket_options, time_t connection_timeout_sec,
  4417. time_t connection_timeout_usec, time_t read_timeout_sec,
  4418. time_t read_timeout_usec, time_t write_timeout_sec,
  4419. time_t write_timeout_usec, const std::string &intf, Error &error) {
  4420. auto sock = create_socket(
  4421. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  4422. std::move(socket_options),
  4423. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  4424. if (!intf.empty()) {
  4425. #ifdef USE_IF2IP
  4426. auto ip_from_if = if2ip(address_family, intf);
  4427. if (ip_from_if.empty()) { ip_from_if = intf; }
  4428. if (!bind_ip_address(sock2, ip_from_if)) {
  4429. error = Error::BindIPAddress;
  4430. return false;
  4431. }
  4432. #endif
  4433. }
  4434. set_nonblocking(sock2, true);
  4435. auto ret =
  4436. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  4437. if (ret < 0) {
  4438. if (is_connection_error()) {
  4439. error = Error::Connection;
  4440. return false;
  4441. }
  4442. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  4443. connection_timeout_usec);
  4444. if (error != Error::Success) {
  4445. if (error == Error::ConnectionTimeout) { quit = true; }
  4446. return false;
  4447. }
  4448. }
  4449. set_nonblocking(sock2, false);
  4450. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  4451. read_timeout_usec);
  4452. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  4453. write_timeout_usec);
  4454. error = Error::Success;
  4455. return true;
  4456. },
  4457. connection_timeout_sec); // Pass DNS timeout
  4458. if (sock != INVALID_SOCKET) {
  4459. error = Error::Success;
  4460. } else {
  4461. if (error == Error::Success) { error = Error::Connection; }
  4462. }
  4463. return sock;
  4464. }
  4465. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  4466. socklen_t addr_len, std::string &ip, int &port) {
  4467. if (addr.ss_family == AF_INET) {
  4468. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  4469. } else if (addr.ss_family == AF_INET6) {
  4470. port =
  4471. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  4472. } else {
  4473. return false;
  4474. }
  4475. std::array<char, NI_MAXHOST> ipstr{};
  4476. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  4477. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  4478. 0, NI_NUMERICHOST)) {
  4479. return false;
  4480. }
  4481. ip = ipstr.data();
  4482. return true;
  4483. }
  4484. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4485. struct sockaddr_storage addr;
  4486. socklen_t addr_len = sizeof(addr);
  4487. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4488. &addr_len)) {
  4489. get_ip_and_port(addr, addr_len, ip, port);
  4490. }
  4491. }
  4492. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4493. struct sockaddr_storage addr;
  4494. socklen_t addr_len = sizeof(addr);
  4495. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4496. &addr_len)) {
  4497. #ifndef _WIN32
  4498. if (addr.ss_family == AF_UNIX) {
  4499. #if defined(__linux__)
  4500. struct ucred ucred;
  4501. socklen_t len = sizeof(ucred);
  4502. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  4503. port = ucred.pid;
  4504. }
  4505. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  4506. pid_t pid;
  4507. socklen_t len = sizeof(pid);
  4508. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  4509. port = pid;
  4510. }
  4511. #endif
  4512. return;
  4513. }
  4514. #endif
  4515. get_ip_and_port(addr, addr_len, ip, port);
  4516. }
  4517. }
  4518. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  4519. unsigned int h) {
  4520. return (l == 0)
  4521. ? h
  4522. : str2tag_core(
  4523. s + 1, l - 1,
  4524. // Unsets the 6 high bits of h, therefore no overflow happens
  4525. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  4526. h * 33) ^
  4527. static_cast<unsigned char>(*s));
  4528. }
  4529. inline unsigned int str2tag(const std::string &s) {
  4530. return str2tag_core(s.data(), s.size(), 0);
  4531. }
  4532. namespace udl {
  4533. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  4534. return str2tag_core(s, l, 0);
  4535. }
  4536. } // namespace udl
  4537. inline std::string
  4538. find_content_type(const std::string &path,
  4539. const std::map<std::string, std::string> &user_data,
  4540. const std::string &default_content_type) {
  4541. auto ext = file_extension(path);
  4542. auto it = user_data.find(ext);
  4543. if (it != user_data.end()) { return it->second; }
  4544. using udl::operator""_t;
  4545. switch (str2tag(ext)) {
  4546. default: return default_content_type;
  4547. case "css"_t: return "text/css";
  4548. case "csv"_t: return "text/csv";
  4549. case "htm"_t:
  4550. case "html"_t: return "text/html";
  4551. case "js"_t:
  4552. case "mjs"_t: return "text/javascript";
  4553. case "txt"_t: return "text/plain";
  4554. case "vtt"_t: return "text/vtt";
  4555. case "apng"_t: return "image/apng";
  4556. case "avif"_t: return "image/avif";
  4557. case "bmp"_t: return "image/bmp";
  4558. case "gif"_t: return "image/gif";
  4559. case "png"_t: return "image/png";
  4560. case "svg"_t: return "image/svg+xml";
  4561. case "webp"_t: return "image/webp";
  4562. case "ico"_t: return "image/x-icon";
  4563. case "tif"_t: return "image/tiff";
  4564. case "tiff"_t: return "image/tiff";
  4565. case "jpg"_t:
  4566. case "jpeg"_t: return "image/jpeg";
  4567. case "mp4"_t: return "video/mp4";
  4568. case "mpeg"_t: return "video/mpeg";
  4569. case "webm"_t: return "video/webm";
  4570. case "mp3"_t: return "audio/mp3";
  4571. case "mpga"_t: return "audio/mpeg";
  4572. case "weba"_t: return "audio/webm";
  4573. case "wav"_t: return "audio/wave";
  4574. case "otf"_t: return "font/otf";
  4575. case "ttf"_t: return "font/ttf";
  4576. case "woff"_t: return "font/woff";
  4577. case "woff2"_t: return "font/woff2";
  4578. case "7z"_t: return "application/x-7z-compressed";
  4579. case "atom"_t: return "application/atom+xml";
  4580. case "pdf"_t: return "application/pdf";
  4581. case "json"_t: return "application/json";
  4582. case "rss"_t: return "application/rss+xml";
  4583. case "tar"_t: return "application/x-tar";
  4584. case "xht"_t:
  4585. case "xhtml"_t: return "application/xhtml+xml";
  4586. case "xslt"_t: return "application/xslt+xml";
  4587. case "xml"_t: return "application/xml";
  4588. case "gz"_t: return "application/gzip";
  4589. case "zip"_t: return "application/zip";
  4590. case "wasm"_t: return "application/wasm";
  4591. }
  4592. }
  4593. inline bool can_compress_content_type(const std::string &content_type) {
  4594. using udl::operator""_t;
  4595. auto tag = str2tag(content_type);
  4596. switch (tag) {
  4597. case "image/svg+xml"_t:
  4598. case "application/javascript"_t:
  4599. case "application/json"_t:
  4600. case "application/xml"_t:
  4601. case "application/protobuf"_t:
  4602. case "application/xhtml+xml"_t: return true;
  4603. case "text/event-stream"_t: return false;
  4604. default: return !content_type.rfind("text/", 0);
  4605. }
  4606. }
  4607. inline EncodingType encoding_type(const Request &req, const Response &res) {
  4608. auto ret =
  4609. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  4610. if (!ret) { return EncodingType::None; }
  4611. const auto &s = req.get_header_value("Accept-Encoding");
  4612. (void)(s);
  4613. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4614. // TODO: 'Accept-Encoding' has br, not br;q=0
  4615. ret = s.find("br") != std::string::npos;
  4616. if (ret) { return EncodingType::Brotli; }
  4617. #endif
  4618. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4619. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  4620. ret = s.find("gzip") != std::string::npos;
  4621. if (ret) { return EncodingType::Gzip; }
  4622. #endif
  4623. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4624. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  4625. ret = s.find("zstd") != std::string::npos;
  4626. if (ret) { return EncodingType::Zstd; }
  4627. #endif
  4628. return EncodingType::None;
  4629. }
  4630. inline bool nocompressor::compress(const char *data, size_t data_length,
  4631. bool /*last*/, Callback callback) {
  4632. if (!data_length) { return true; }
  4633. return callback(data, data_length);
  4634. }
  4635. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4636. inline gzip_compressor::gzip_compressor() {
  4637. std::memset(&strm_, 0, sizeof(strm_));
  4638. strm_.zalloc = Z_NULL;
  4639. strm_.zfree = Z_NULL;
  4640. strm_.opaque = Z_NULL;
  4641. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  4642. Z_DEFAULT_STRATEGY) == Z_OK;
  4643. }
  4644. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  4645. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  4646. bool last, Callback callback) {
  4647. assert(is_valid_);
  4648. do {
  4649. constexpr size_t max_avail_in =
  4650. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4651. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4652. (std::min)(data_length, max_avail_in));
  4653. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4654. data_length -= strm_.avail_in;
  4655. data += strm_.avail_in;
  4656. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  4657. auto ret = Z_OK;
  4658. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4659. do {
  4660. strm_.avail_out = static_cast<uInt>(buff.size());
  4661. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4662. ret = deflate(&strm_, flush);
  4663. if (ret == Z_STREAM_ERROR) { return false; }
  4664. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4665. return false;
  4666. }
  4667. } while (strm_.avail_out == 0);
  4668. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  4669. (flush == Z_NO_FLUSH && ret == Z_OK));
  4670. assert(strm_.avail_in == 0);
  4671. } while (data_length > 0);
  4672. return true;
  4673. }
  4674. inline gzip_decompressor::gzip_decompressor() {
  4675. std::memset(&strm_, 0, sizeof(strm_));
  4676. strm_.zalloc = Z_NULL;
  4677. strm_.zfree = Z_NULL;
  4678. strm_.opaque = Z_NULL;
  4679. // 15 is the value of wbits, which should be at the maximum possible value
  4680. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  4681. // that the stream type should be automatically detected either gzip or
  4682. // deflate.
  4683. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  4684. }
  4685. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  4686. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  4687. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  4688. Callback callback) {
  4689. assert(is_valid_);
  4690. auto ret = Z_OK;
  4691. do {
  4692. constexpr size_t max_avail_in =
  4693. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4694. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4695. (std::min)(data_length, max_avail_in));
  4696. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4697. data_length -= strm_.avail_in;
  4698. data += strm_.avail_in;
  4699. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4700. while (strm_.avail_in > 0 && ret == Z_OK) {
  4701. strm_.avail_out = static_cast<uInt>(buff.size());
  4702. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4703. ret = inflate(&strm_, Z_NO_FLUSH);
  4704. assert(ret != Z_STREAM_ERROR);
  4705. switch (ret) {
  4706. case Z_NEED_DICT:
  4707. case Z_DATA_ERROR:
  4708. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  4709. }
  4710. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4711. return false;
  4712. }
  4713. }
  4714. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  4715. } while (data_length > 0);
  4716. return true;
  4717. }
  4718. #endif
  4719. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4720. inline brotli_compressor::brotli_compressor() {
  4721. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  4722. }
  4723. inline brotli_compressor::~brotli_compressor() {
  4724. BrotliEncoderDestroyInstance(state_);
  4725. }
  4726. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  4727. bool last, Callback callback) {
  4728. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4729. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  4730. auto available_in = data_length;
  4731. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4732. for (;;) {
  4733. if (last) {
  4734. if (BrotliEncoderIsFinished(state_)) { break; }
  4735. } else {
  4736. if (!available_in) { break; }
  4737. }
  4738. auto available_out = buff.size();
  4739. auto next_out = buff.data();
  4740. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  4741. &available_out, &next_out, nullptr)) {
  4742. return false;
  4743. }
  4744. auto output_bytes = buff.size() - available_out;
  4745. if (output_bytes) {
  4746. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  4747. }
  4748. }
  4749. return true;
  4750. }
  4751. inline brotli_decompressor::brotli_decompressor() {
  4752. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  4753. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  4754. : BROTLI_DECODER_RESULT_ERROR;
  4755. }
  4756. inline brotli_decompressor::~brotli_decompressor() {
  4757. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  4758. }
  4759. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  4760. inline bool brotli_decompressor::decompress(const char *data,
  4761. size_t data_length,
  4762. Callback callback) {
  4763. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4764. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  4765. return 0;
  4766. }
  4767. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4768. size_t avail_in = data_length;
  4769. size_t total_out;
  4770. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  4771. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4772. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  4773. char *next_out = buff.data();
  4774. size_t avail_out = buff.size();
  4775. decoder_r = BrotliDecoderDecompressStream(
  4776. decoder_s, &avail_in, &next_in, &avail_out,
  4777. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  4778. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  4779. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  4780. }
  4781. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4782. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  4783. }
  4784. #endif
  4785. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4786. inline zstd_compressor::zstd_compressor() {
  4787. ctx_ = ZSTD_createCCtx();
  4788. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  4789. }
  4790. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  4791. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  4792. bool last, Callback callback) {
  4793. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4794. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  4795. ZSTD_inBuffer input = {data, data_length, 0};
  4796. bool finished;
  4797. do {
  4798. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4799. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  4800. if (ZSTD_isError(remaining)) { return false; }
  4801. if (!callback(buff.data(), output.pos)) { return false; }
  4802. finished = last ? (remaining == 0) : (input.pos == input.size);
  4803. } while (!finished);
  4804. return true;
  4805. }
  4806. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  4807. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  4808. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  4809. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  4810. Callback callback) {
  4811. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4812. ZSTD_inBuffer input = {data, data_length, 0};
  4813. while (input.pos < input.size) {
  4814. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4815. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  4816. if (ZSTD_isError(remaining)) { return false; }
  4817. if (!callback(buff.data(), output.pos)) { return false; }
  4818. }
  4819. return true;
  4820. }
  4821. #endif
  4822. inline std::unique_ptr<decompressor>
  4823. create_decompressor(const std::string &encoding) {
  4824. std::unique_ptr<decompressor> decompressor;
  4825. if (encoding == "gzip" || encoding == "deflate") {
  4826. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4827. decompressor = detail::make_unique<gzip_decompressor>();
  4828. #endif
  4829. } else if (encoding.find("br") != std::string::npos) {
  4830. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4831. decompressor = detail::make_unique<brotli_decompressor>();
  4832. #endif
  4833. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  4834. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4835. decompressor = detail::make_unique<zstd_decompressor>();
  4836. #endif
  4837. }
  4838. return decompressor;
  4839. }
  4840. inline bool is_prohibited_header_name(const std::string &name) {
  4841. using udl::operator""_t;
  4842. switch (str2tag(name)) {
  4843. case "REMOTE_ADDR"_t:
  4844. case "REMOTE_PORT"_t:
  4845. case "LOCAL_ADDR"_t:
  4846. case "LOCAL_PORT"_t: return true;
  4847. default: return false;
  4848. }
  4849. }
  4850. inline bool has_header(const Headers &headers, const std::string &key) {
  4851. if (is_prohibited_header_name(key)) { return false; }
  4852. return headers.find(key) != headers.end();
  4853. }
  4854. inline const char *get_header_value(const Headers &headers,
  4855. const std::string &key, const char *def,
  4856. size_t id) {
  4857. if (is_prohibited_header_name(key)) {
  4858. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4859. std::string msg = "Prohibited header name '" + key + "' is specified.";
  4860. throw std::invalid_argument(msg);
  4861. #else
  4862. return "";
  4863. #endif
  4864. }
  4865. auto rng = headers.equal_range(key);
  4866. auto it = rng.first;
  4867. std::advance(it, static_cast<ssize_t>(id));
  4868. if (it != rng.second) { return it->second.c_str(); }
  4869. return def;
  4870. }
  4871. inline bool read_headers(Stream &strm, Headers &headers) {
  4872. const auto bufsiz = 2048;
  4873. char buf[bufsiz];
  4874. stream_line_reader line_reader(strm, buf, bufsiz);
  4875. size_t header_count = 0;
  4876. for (;;) {
  4877. if (!line_reader.getline()) { return false; }
  4878. // Check if the line ends with CRLF.
  4879. auto line_terminator_len = 2;
  4880. if (line_reader.end_with_crlf()) {
  4881. // Blank line indicates end of headers.
  4882. if (line_reader.size() == 2) { break; }
  4883. } else {
  4884. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4885. // Blank line indicates end of headers.
  4886. if (line_reader.size() == 1) { break; }
  4887. line_terminator_len = 1;
  4888. #else
  4889. continue; // Skip invalid line.
  4890. #endif
  4891. }
  4892. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4893. // Check header count limit
  4894. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4895. // Exclude line terminator
  4896. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  4897. if (!parse_header(line_reader.ptr(), end,
  4898. [&](const std::string &key, const std::string &val) {
  4899. headers.emplace(key, val);
  4900. })) {
  4901. return false;
  4902. }
  4903. header_count++;
  4904. }
  4905. return true;
  4906. }
  4907. enum class ReadContentResult {
  4908. Success, // Successfully read the content
  4909. PayloadTooLarge, // The content exceeds the specified payload limit
  4910. Error // An error occurred while reading the content
  4911. };
  4912. inline ReadContentResult read_content_with_length(
  4913. Stream &strm, size_t len, DownloadProgress progress,
  4914. ContentReceiverWithProgress out,
  4915. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  4916. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4917. detail::BodyReader br;
  4918. br.stream = &strm;
  4919. br.has_content_length = true;
  4920. br.content_length = len;
  4921. br.payload_max_length = payload_max_length;
  4922. br.chunked = false;
  4923. br.bytes_read = 0;
  4924. br.last_error = Error::Success;
  4925. size_t r = 0;
  4926. while (r < len) {
  4927. auto read_len = static_cast<size_t>(len - r);
  4928. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  4929. auto n = detail::read_body_content(&strm, br, buf, to_read);
  4930. if (n <= 0) {
  4931. // Check if it was a payload size error
  4932. if (br.last_error == Error::ExceedMaxPayloadSize) {
  4933. return ReadContentResult::PayloadTooLarge;
  4934. }
  4935. return ReadContentResult::Error;
  4936. }
  4937. if (!out(buf, static_cast<size_t>(n), r, len)) {
  4938. return ReadContentResult::Error;
  4939. }
  4940. r += static_cast<size_t>(n);
  4941. if (progress) {
  4942. if (!progress(r, len)) { return ReadContentResult::Error; }
  4943. }
  4944. }
  4945. return ReadContentResult::Success;
  4946. }
  4947. inline ReadContentResult
  4948. read_content_without_length(Stream &strm, size_t payload_max_length,
  4949. ContentReceiverWithProgress out) {
  4950. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4951. size_t r = 0;
  4952. for (;;) {
  4953. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  4954. if (n == 0) { return ReadContentResult::Success; }
  4955. if (n < 0) { return ReadContentResult::Error; }
  4956. // Check if adding this data would exceed the payload limit
  4957. if (r > payload_max_length ||
  4958. payload_max_length - r < static_cast<size_t>(n)) {
  4959. return ReadContentResult::PayloadTooLarge;
  4960. }
  4961. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  4962. return ReadContentResult::Error;
  4963. }
  4964. r += static_cast<size_t>(n);
  4965. }
  4966. return ReadContentResult::Success;
  4967. }
  4968. template <typename T>
  4969. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  4970. size_t payload_max_length,
  4971. ContentReceiverWithProgress out) {
  4972. detail::ChunkedDecoder dec(strm);
  4973. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4974. size_t total_len = 0;
  4975. for (;;) {
  4976. size_t chunk_offset = 0;
  4977. size_t chunk_total = 0;
  4978. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  4979. if (n < 0) { return ReadContentResult::Error; }
  4980. if (n == 0) {
  4981. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  4982. return ReadContentResult::Error;
  4983. }
  4984. return ReadContentResult::Success;
  4985. }
  4986. if (total_len > payload_max_length ||
  4987. payload_max_length - total_len < static_cast<size_t>(n)) {
  4988. return ReadContentResult::PayloadTooLarge;
  4989. }
  4990. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  4991. return ReadContentResult::Error;
  4992. }
  4993. total_len += static_cast<size_t>(n);
  4994. }
  4995. }
  4996. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  4997. return case_ignore::equal(
  4998. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  4999. }
  5000. template <typename T, typename U>
  5001. bool prepare_content_receiver(T &x, int &status,
  5002. ContentReceiverWithProgress receiver,
  5003. bool decompress, U callback) {
  5004. if (decompress) {
  5005. std::string encoding = x.get_header_value("Content-Encoding");
  5006. std::unique_ptr<decompressor> decompressor;
  5007. if (!encoding.empty()) {
  5008. decompressor = detail::create_decompressor(encoding);
  5009. if (!decompressor) {
  5010. // Unsupported encoding or no support compiled in
  5011. status = StatusCode::UnsupportedMediaType_415;
  5012. return false;
  5013. }
  5014. }
  5015. if (decompressor) {
  5016. if (decompressor->is_valid()) {
  5017. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  5018. size_t off, size_t len) {
  5019. return decompressor->decompress(buf, n,
  5020. [&](const char *buf2, size_t n2) {
  5021. return receiver(buf2, n2, off, len);
  5022. });
  5023. };
  5024. return callback(std::move(out));
  5025. } else {
  5026. status = StatusCode::InternalServerError_500;
  5027. return false;
  5028. }
  5029. }
  5030. }
  5031. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  5032. size_t len) {
  5033. return receiver(buf, n, off, len);
  5034. };
  5035. return callback(std::move(out));
  5036. }
  5037. template <typename T>
  5038. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  5039. DownloadProgress progress,
  5040. ContentReceiverWithProgress receiver, bool decompress) {
  5041. return prepare_content_receiver(
  5042. x, status, std::move(receiver), decompress,
  5043. [&](const ContentReceiverWithProgress &out) {
  5044. auto ret = true;
  5045. auto exceed_payload_max_length = false;
  5046. if (is_chunked_transfer_encoding(x.headers)) {
  5047. auto result = read_content_chunked(strm, x, payload_max_length, out);
  5048. if (result == ReadContentResult::Success) {
  5049. ret = true;
  5050. } else if (result == ReadContentResult::PayloadTooLarge) {
  5051. exceed_payload_max_length = true;
  5052. ret = false;
  5053. } else {
  5054. ret = false;
  5055. }
  5056. } else if (!has_header(x.headers, "Content-Length")) {
  5057. auto result =
  5058. read_content_without_length(strm, payload_max_length, out);
  5059. if (result == ReadContentResult::Success) {
  5060. ret = true;
  5061. } else if (result == ReadContentResult::PayloadTooLarge) {
  5062. exceed_payload_max_length = true;
  5063. ret = false;
  5064. } else {
  5065. ret = false;
  5066. }
  5067. } else {
  5068. auto is_invalid_value = false;
  5069. auto len = get_header_value_u64(x.headers, "Content-Length",
  5070. (std::numeric_limits<size_t>::max)(),
  5071. 0, is_invalid_value);
  5072. if (is_invalid_value) {
  5073. ret = false;
  5074. } else if (len > 0) {
  5075. auto result = read_content_with_length(
  5076. strm, len, std::move(progress), out, payload_max_length);
  5077. ret = (result == ReadContentResult::Success);
  5078. if (result == ReadContentResult::PayloadTooLarge) {
  5079. exceed_payload_max_length = true;
  5080. }
  5081. }
  5082. }
  5083. if (!ret) {
  5084. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  5085. : StatusCode::BadRequest_400;
  5086. }
  5087. return ret;
  5088. });
  5089. }
  5090. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  5091. const std::string &path) {
  5092. std::string s = method;
  5093. s += ' ';
  5094. s += path;
  5095. s += " HTTP/1.1\r\n";
  5096. return strm.write(s.data(), s.size());
  5097. }
  5098. inline ssize_t write_response_line(Stream &strm, int status) {
  5099. std::string s = "HTTP/1.1 ";
  5100. s += std::to_string(status);
  5101. s += ' ';
  5102. s += httplib::status_message(status);
  5103. s += "\r\n";
  5104. return strm.write(s.data(), s.size());
  5105. }
  5106. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  5107. ssize_t write_len = 0;
  5108. for (const auto &x : headers) {
  5109. std::string s;
  5110. s = x.first;
  5111. s += ": ";
  5112. s += x.second;
  5113. s += "\r\n";
  5114. auto len = strm.write(s.data(), s.size());
  5115. if (len < 0) { return len; }
  5116. write_len += len;
  5117. }
  5118. auto len = strm.write("\r\n");
  5119. if (len < 0) { return len; }
  5120. write_len += len;
  5121. return write_len;
  5122. }
  5123. inline bool write_data(Stream &strm, const char *d, size_t l) {
  5124. size_t offset = 0;
  5125. while (offset < l) {
  5126. auto length = strm.write(d + offset, l - offset);
  5127. if (length < 0) { return false; }
  5128. offset += static_cast<size_t>(length);
  5129. }
  5130. return true;
  5131. }
  5132. template <typename T>
  5133. inline bool write_content_with_progress(Stream &strm,
  5134. const ContentProvider &content_provider,
  5135. size_t offset, size_t length,
  5136. T is_shutting_down,
  5137. const UploadProgress &upload_progress,
  5138. Error &error) {
  5139. size_t end_offset = offset + length;
  5140. size_t start_offset = offset;
  5141. auto ok = true;
  5142. DataSink data_sink;
  5143. data_sink.write = [&](const char *d, size_t l) -> bool {
  5144. if (ok) {
  5145. if (write_data(strm, d, l)) {
  5146. offset += l;
  5147. if (upload_progress && length > 0) {
  5148. size_t current_written = offset - start_offset;
  5149. if (!upload_progress(current_written, length)) {
  5150. ok = false;
  5151. return false;
  5152. }
  5153. }
  5154. } else {
  5155. ok = false;
  5156. }
  5157. }
  5158. return ok;
  5159. };
  5160. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5161. while (offset < end_offset && !is_shutting_down()) {
  5162. if (!strm.wait_writable()) {
  5163. error = Error::Write;
  5164. return false;
  5165. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  5166. error = Error::Canceled;
  5167. return false;
  5168. } else if (!ok) {
  5169. error = Error::Write;
  5170. return false;
  5171. }
  5172. }
  5173. error = Error::Success;
  5174. return true;
  5175. }
  5176. template <typename T>
  5177. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5178. size_t offset, size_t length, T is_shutting_down,
  5179. Error &error) {
  5180. return write_content_with_progress<T>(strm, content_provider, offset, length,
  5181. is_shutting_down, nullptr, error);
  5182. }
  5183. template <typename T>
  5184. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5185. size_t offset, size_t length,
  5186. const T &is_shutting_down) {
  5187. auto error = Error::Success;
  5188. return write_content(strm, content_provider, offset, length, is_shutting_down,
  5189. error);
  5190. }
  5191. template <typename T>
  5192. inline bool
  5193. write_content_without_length(Stream &strm,
  5194. const ContentProvider &content_provider,
  5195. const T &is_shutting_down) {
  5196. size_t offset = 0;
  5197. auto data_available = true;
  5198. auto ok = true;
  5199. DataSink data_sink;
  5200. data_sink.write = [&](const char *d, size_t l) -> bool {
  5201. if (ok) {
  5202. offset += l;
  5203. if (!write_data(strm, d, l)) { ok = false; }
  5204. }
  5205. return ok;
  5206. };
  5207. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5208. data_sink.done = [&](void) { data_available = false; };
  5209. while (data_available && !is_shutting_down()) {
  5210. if (!strm.wait_writable()) {
  5211. return false;
  5212. } else if (!content_provider(offset, 0, data_sink)) {
  5213. return false;
  5214. } else if (!ok) {
  5215. return false;
  5216. }
  5217. }
  5218. return true;
  5219. }
  5220. template <typename T, typename U>
  5221. inline bool
  5222. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  5223. const T &is_shutting_down, U &compressor, Error &error) {
  5224. size_t offset = 0;
  5225. auto data_available = true;
  5226. auto ok = true;
  5227. DataSink data_sink;
  5228. data_sink.write = [&](const char *d, size_t l) -> bool {
  5229. if (ok) {
  5230. data_available = l > 0;
  5231. offset += l;
  5232. std::string payload;
  5233. if (compressor.compress(d, l, false,
  5234. [&](const char *data, size_t data_len) {
  5235. payload.append(data, data_len);
  5236. return true;
  5237. })) {
  5238. if (!payload.empty()) {
  5239. // Emit chunked response header and footer for each chunk
  5240. auto chunk =
  5241. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5242. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  5243. }
  5244. } else {
  5245. ok = false;
  5246. }
  5247. }
  5248. return ok;
  5249. };
  5250. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5251. auto done_with_trailer = [&](const Headers *trailer) {
  5252. if (!ok) { return; }
  5253. data_available = false;
  5254. std::string payload;
  5255. if (!compressor.compress(nullptr, 0, true,
  5256. [&](const char *data, size_t data_len) {
  5257. payload.append(data, data_len);
  5258. return true;
  5259. })) {
  5260. ok = false;
  5261. return;
  5262. }
  5263. if (!payload.empty()) {
  5264. // Emit chunked response header and footer for each chunk
  5265. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5266. if (!write_data(strm, chunk.data(), chunk.size())) {
  5267. ok = false;
  5268. return;
  5269. }
  5270. }
  5271. constexpr const char done_marker[] = "0\r\n";
  5272. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  5273. // Trailer
  5274. if (trailer) {
  5275. for (const auto &kv : *trailer) {
  5276. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  5277. if (!write_data(strm, field_line.data(), field_line.size())) {
  5278. ok = false;
  5279. }
  5280. }
  5281. }
  5282. constexpr const char crlf[] = "\r\n";
  5283. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  5284. };
  5285. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  5286. data_sink.done_with_trailer = [&](const Headers &trailer) {
  5287. done_with_trailer(&trailer);
  5288. };
  5289. while (data_available && !is_shutting_down()) {
  5290. if (!strm.wait_writable()) {
  5291. error = Error::Write;
  5292. return false;
  5293. } else if (!content_provider(offset, 0, data_sink)) {
  5294. error = Error::Canceled;
  5295. return false;
  5296. } else if (!ok) {
  5297. error = Error::Write;
  5298. return false;
  5299. }
  5300. }
  5301. error = Error::Success;
  5302. return true;
  5303. }
  5304. template <typename T, typename U>
  5305. inline bool write_content_chunked(Stream &strm,
  5306. const ContentProvider &content_provider,
  5307. const T &is_shutting_down, U &compressor) {
  5308. auto error = Error::Success;
  5309. return write_content_chunked(strm, content_provider, is_shutting_down,
  5310. compressor, error);
  5311. }
  5312. template <typename T>
  5313. inline bool redirect(T &cli, Request &req, Response &res,
  5314. const std::string &path, const std::string &location,
  5315. Error &error) {
  5316. Request new_req = req;
  5317. new_req.path = path;
  5318. new_req.redirect_count_ -= 1;
  5319. if (res.status == StatusCode::SeeOther_303 &&
  5320. (req.method != "GET" && req.method != "HEAD")) {
  5321. new_req.method = "GET";
  5322. new_req.body.clear();
  5323. new_req.headers.clear();
  5324. }
  5325. Response new_res;
  5326. auto ret = cli.send(new_req, new_res, error);
  5327. if (ret) {
  5328. req = std::move(new_req);
  5329. res = std::move(new_res);
  5330. if (res.location.empty()) { res.location = location; }
  5331. }
  5332. return ret;
  5333. }
  5334. inline std::string params_to_query_str(const Params &params) {
  5335. std::string query;
  5336. for (auto it = params.begin(); it != params.end(); ++it) {
  5337. if (it != params.begin()) { query += '&'; }
  5338. query += encode_query_component(it->first);
  5339. query += '=';
  5340. query += encode_query_component(it->second);
  5341. }
  5342. return query;
  5343. }
  5344. inline void parse_query_text(const char *data, std::size_t size,
  5345. Params &params) {
  5346. std::set<std::string> cache;
  5347. split(data, data + size, '&', [&](const char *b, const char *e) {
  5348. std::string kv(b, e);
  5349. if (cache.find(kv) != cache.end()) { return; }
  5350. cache.insert(std::move(kv));
  5351. std::string key;
  5352. std::string val;
  5353. divide(b, static_cast<std::size_t>(e - b), '=',
  5354. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  5355. std::size_t rhs_size) {
  5356. key.assign(lhs_data, lhs_size);
  5357. val.assign(rhs_data, rhs_size);
  5358. });
  5359. if (!key.empty()) {
  5360. params.emplace(decode_query_component(key), decode_query_component(val));
  5361. }
  5362. });
  5363. }
  5364. inline void parse_query_text(const std::string &s, Params &params) {
  5365. parse_query_text(s.data(), s.size(), params);
  5366. }
  5367. // Normalize a query string by decoding and re-encoding each key/value pair
  5368. // while preserving the original parameter order. This avoids double-encoding
  5369. // and ensures consistent encoding without reordering (unlike Params which
  5370. // uses std::multimap and sorts keys).
  5371. inline std::string normalize_query_string(const std::string &query) {
  5372. std::string result;
  5373. split(query.data(), query.data() + query.size(), '&',
  5374. [&](const char *b, const char *e) {
  5375. std::string key;
  5376. std::string val;
  5377. divide(b, static_cast<std::size_t>(e - b), '=',
  5378. [&](const char *lhs_data, std::size_t lhs_size,
  5379. const char *rhs_data, std::size_t rhs_size) {
  5380. key.assign(lhs_data, lhs_size);
  5381. val.assign(rhs_data, rhs_size);
  5382. });
  5383. if (!key.empty()) {
  5384. auto dec_key = decode_query_component(key);
  5385. auto dec_val = decode_query_component(val);
  5386. if (!result.empty()) { result += '&'; }
  5387. result += encode_query_component(dec_key);
  5388. if (!val.empty() || std::find(b, e, '=') != e) {
  5389. result += '=';
  5390. result += encode_query_component(dec_val);
  5391. }
  5392. }
  5393. });
  5394. return result;
  5395. }
  5396. inline bool parse_multipart_boundary(const std::string &content_type,
  5397. std::string &boundary) {
  5398. auto boundary_keyword = "boundary=";
  5399. auto pos = content_type.find(boundary_keyword);
  5400. if (pos == std::string::npos) { return false; }
  5401. auto end = content_type.find(';', pos);
  5402. auto beg = pos + strlen(boundary_keyword);
  5403. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  5404. return !boundary.empty();
  5405. }
  5406. inline void parse_disposition_params(const std::string &s, Params &params) {
  5407. std::set<std::string> cache;
  5408. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  5409. std::string kv(b, e);
  5410. if (cache.find(kv) != cache.end()) { return; }
  5411. cache.insert(kv);
  5412. std::string key;
  5413. std::string val;
  5414. split(b, e, '=', [&](const char *b2, const char *e2) {
  5415. if (key.empty()) {
  5416. key.assign(b2, e2);
  5417. } else {
  5418. val.assign(b2, e2);
  5419. }
  5420. });
  5421. if (!key.empty()) {
  5422. params.emplace(trim_double_quotes_copy((key)),
  5423. trim_double_quotes_copy((val)));
  5424. }
  5425. });
  5426. }
  5427. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5428. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  5429. #else
  5430. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  5431. #endif
  5432. auto is_valid = [](const std::string &str) {
  5433. return std::all_of(str.cbegin(), str.cend(),
  5434. [](unsigned char c) { return std::isdigit(c); });
  5435. };
  5436. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  5437. const auto pos = static_cast<size_t>(6);
  5438. const auto len = static_cast<size_t>(s.size() - 6);
  5439. auto all_valid_ranges = true;
  5440. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  5441. if (!all_valid_ranges) { return; }
  5442. const auto it = std::find(b, e, '-');
  5443. if (it == e) {
  5444. all_valid_ranges = false;
  5445. return;
  5446. }
  5447. const auto lhs = std::string(b, it);
  5448. const auto rhs = std::string(it + 1, e);
  5449. if (!is_valid(lhs) || !is_valid(rhs)) {
  5450. all_valid_ranges = false;
  5451. return;
  5452. }
  5453. ssize_t first = -1;
  5454. if (!lhs.empty()) {
  5455. ssize_t v;
  5456. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  5457. if (res.ec == std::errc{}) { first = v; }
  5458. }
  5459. ssize_t last = -1;
  5460. if (!rhs.empty()) {
  5461. ssize_t v;
  5462. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  5463. if (res.ec == std::errc{}) { last = v; }
  5464. }
  5465. if ((first == -1 && last == -1) ||
  5466. (first != -1 && last != -1 && first > last)) {
  5467. all_valid_ranges = false;
  5468. return;
  5469. }
  5470. ranges.emplace_back(first, last);
  5471. });
  5472. return all_valid_ranges && !ranges.empty();
  5473. }
  5474. return false;
  5475. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5476. }
  5477. #else
  5478. } catch (...) { return false; }
  5479. #endif
  5480. inline bool parse_accept_header(const std::string &s,
  5481. std::vector<std::string> &content_types) {
  5482. content_types.clear();
  5483. // Empty string is considered valid (no preference)
  5484. if (s.empty()) { return true; }
  5485. // Check for invalid patterns: leading/trailing commas or consecutive commas
  5486. if (s.front() == ',' || s.back() == ',' ||
  5487. s.find(",,") != std::string::npos) {
  5488. return false;
  5489. }
  5490. struct AcceptEntry {
  5491. std::string media_type;
  5492. double quality;
  5493. int order; // Original order in header
  5494. };
  5495. std::vector<AcceptEntry> entries;
  5496. int order = 0;
  5497. bool has_invalid_entry = false;
  5498. // Split by comma and parse each entry
  5499. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5500. std::string entry(b, e);
  5501. entry = trim_copy(entry);
  5502. if (entry.empty()) {
  5503. has_invalid_entry = true;
  5504. return;
  5505. }
  5506. AcceptEntry accept_entry;
  5507. accept_entry.quality = 1.0; // Default quality
  5508. accept_entry.order = order++;
  5509. // Find q= parameter
  5510. auto q_pos = entry.find(";q=");
  5511. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  5512. if (q_pos != std::string::npos) {
  5513. // Extract media type (before q parameter)
  5514. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  5515. // Extract quality value
  5516. auto q_start = entry.find('=', q_pos) + 1;
  5517. auto q_end = entry.find(';', q_start);
  5518. if (q_end == std::string::npos) { q_end = entry.length(); }
  5519. std::string quality_str =
  5520. trim_copy(entry.substr(q_start, q_end - q_start));
  5521. if (quality_str.empty()) {
  5522. has_invalid_entry = true;
  5523. return;
  5524. }
  5525. {
  5526. double v = 0.0;
  5527. auto res = detail::from_chars(
  5528. quality_str.data(), quality_str.data() + quality_str.size(), v);
  5529. if (res.ec == std::errc{}) {
  5530. accept_entry.quality = v;
  5531. } else {
  5532. has_invalid_entry = true;
  5533. return;
  5534. }
  5535. }
  5536. // Check if quality is in valid range [0.0, 1.0]
  5537. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  5538. has_invalid_entry = true;
  5539. return;
  5540. }
  5541. } else {
  5542. // No quality parameter, use entire entry as media type
  5543. accept_entry.media_type = entry;
  5544. }
  5545. // Remove additional parameters from media type
  5546. auto param_pos = accept_entry.media_type.find(';');
  5547. if (param_pos != std::string::npos) {
  5548. accept_entry.media_type =
  5549. trim_copy(accept_entry.media_type.substr(0, param_pos));
  5550. }
  5551. // Basic validation of media type format
  5552. if (accept_entry.media_type.empty()) {
  5553. has_invalid_entry = true;
  5554. return;
  5555. }
  5556. // Check for basic media type format (should contain '/' or be '*')
  5557. if (accept_entry.media_type != "*" &&
  5558. accept_entry.media_type.find('/') == std::string::npos) {
  5559. has_invalid_entry = true;
  5560. return;
  5561. }
  5562. entries.push_back(std::move(accept_entry));
  5563. });
  5564. // Return false if any invalid entry was found
  5565. if (has_invalid_entry) { return false; }
  5566. // Sort by quality (descending), then by original order (ascending)
  5567. std::sort(entries.begin(), entries.end(),
  5568. [](const AcceptEntry &a, const AcceptEntry &b) {
  5569. if (a.quality != b.quality) {
  5570. return a.quality > b.quality; // Higher quality first
  5571. }
  5572. return a.order < b.order; // Earlier order first for same quality
  5573. });
  5574. // Extract sorted media types
  5575. content_types.reserve(entries.size());
  5576. for (auto &entry : entries) {
  5577. content_types.push_back(std::move(entry.media_type));
  5578. }
  5579. return true;
  5580. }
  5581. class FormDataParser {
  5582. public:
  5583. FormDataParser() = default;
  5584. void set_boundary(std::string &&boundary) {
  5585. boundary_ = std::move(boundary);
  5586. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  5587. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  5588. }
  5589. bool is_valid() const { return is_valid_; }
  5590. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  5591. const ContentReceiver &content_callback) {
  5592. buf_append(buf, n);
  5593. while (buf_size() > 0) {
  5594. switch (state_) {
  5595. case 0: { // Initial boundary
  5596. auto pos = buf_find(dash_boundary_crlf_);
  5597. if (pos == buf_size()) { return true; }
  5598. buf_erase(pos + dash_boundary_crlf_.size());
  5599. state_ = 1;
  5600. break;
  5601. }
  5602. case 1: { // New entry
  5603. clear_file_info();
  5604. state_ = 2;
  5605. break;
  5606. }
  5607. case 2: { // Headers
  5608. auto pos = buf_find(crlf_);
  5609. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5610. while (pos < buf_size()) {
  5611. // Empty line
  5612. if (pos == 0) {
  5613. if (!header_callback(file_)) {
  5614. is_valid_ = false;
  5615. return false;
  5616. }
  5617. buf_erase(crlf_.size());
  5618. state_ = 3;
  5619. break;
  5620. }
  5621. const auto header = buf_head(pos);
  5622. if (!parse_header(header.data(), header.data() + header.size(),
  5623. [&](const std::string &, const std::string &) {})) {
  5624. is_valid_ = false;
  5625. return false;
  5626. }
  5627. // Parse and emplace space trimmed headers into a map
  5628. if (!parse_header(
  5629. header.data(), header.data() + header.size(),
  5630. [&](const std::string &key, const std::string &val) {
  5631. file_.headers.emplace(key, val);
  5632. })) {
  5633. is_valid_ = false;
  5634. return false;
  5635. }
  5636. constexpr const char header_content_type[] = "Content-Type:";
  5637. if (start_with_case_ignore(header, header_content_type)) {
  5638. file_.content_type =
  5639. trim_copy(header.substr(str_len(header_content_type)));
  5640. } else {
  5641. thread_local const std::regex re_content_disposition(
  5642. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  5643. std::regex_constants::icase);
  5644. std::smatch m;
  5645. if (std::regex_match(header, m, re_content_disposition)) {
  5646. Params params;
  5647. parse_disposition_params(m[1], params);
  5648. auto it = params.find("name");
  5649. if (it != params.end()) {
  5650. file_.name = it->second;
  5651. } else {
  5652. is_valid_ = false;
  5653. return false;
  5654. }
  5655. it = params.find("filename");
  5656. if (it != params.end()) { file_.filename = it->second; }
  5657. it = params.find("filename*");
  5658. if (it != params.end()) {
  5659. // Only allow UTF-8 encoding...
  5660. thread_local const std::regex re_rfc5987_encoding(
  5661. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  5662. std::smatch m2;
  5663. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  5664. file_.filename = decode_path_component(m2[1]); // override...
  5665. } else {
  5666. is_valid_ = false;
  5667. return false;
  5668. }
  5669. }
  5670. }
  5671. }
  5672. buf_erase(pos + crlf_.size());
  5673. pos = buf_find(crlf_);
  5674. }
  5675. if (state_ != 3) { return true; }
  5676. break;
  5677. }
  5678. case 3: { // Body
  5679. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  5680. auto pos = buf_find(crlf_dash_boundary_);
  5681. if (pos < buf_size()) {
  5682. if (!content_callback(buf_data(), pos)) {
  5683. is_valid_ = false;
  5684. return false;
  5685. }
  5686. buf_erase(pos + crlf_dash_boundary_.size());
  5687. state_ = 4;
  5688. } else {
  5689. auto len = buf_size() - crlf_dash_boundary_.size();
  5690. if (len > 0) {
  5691. if (!content_callback(buf_data(), len)) {
  5692. is_valid_ = false;
  5693. return false;
  5694. }
  5695. buf_erase(len);
  5696. }
  5697. return true;
  5698. }
  5699. break;
  5700. }
  5701. case 4: { // Boundary
  5702. if (crlf_.size() > buf_size()) { return true; }
  5703. if (buf_start_with(crlf_)) {
  5704. buf_erase(crlf_.size());
  5705. state_ = 1;
  5706. } else {
  5707. if (dash_.size() > buf_size()) { return true; }
  5708. if (buf_start_with(dash_)) {
  5709. buf_erase(dash_.size());
  5710. is_valid_ = true;
  5711. buf_erase(buf_size()); // Remove epilogue
  5712. } else {
  5713. return true;
  5714. }
  5715. }
  5716. break;
  5717. }
  5718. }
  5719. }
  5720. return true;
  5721. }
  5722. private:
  5723. void clear_file_info() {
  5724. file_.name.clear();
  5725. file_.filename.clear();
  5726. file_.content_type.clear();
  5727. file_.headers.clear();
  5728. }
  5729. bool start_with_case_ignore(const std::string &a, const char *b) const {
  5730. const auto b_len = strlen(b);
  5731. if (a.size() < b_len) { return false; }
  5732. for (size_t i = 0; i < b_len; i++) {
  5733. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  5734. return false;
  5735. }
  5736. }
  5737. return true;
  5738. }
  5739. const std::string dash_ = "--";
  5740. const std::string crlf_ = "\r\n";
  5741. std::string boundary_;
  5742. std::string dash_boundary_crlf_;
  5743. std::string crlf_dash_boundary_;
  5744. size_t state_ = 0;
  5745. bool is_valid_ = false;
  5746. FormData file_;
  5747. // Buffer
  5748. bool start_with(const std::string &a, size_t spos, size_t epos,
  5749. const std::string &b) const {
  5750. if (epos - spos < b.size()) { return false; }
  5751. for (size_t i = 0; i < b.size(); i++) {
  5752. if (a[i + spos] != b[i]) { return false; }
  5753. }
  5754. return true;
  5755. }
  5756. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  5757. const char *buf_data() const { return &buf_[buf_spos_]; }
  5758. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  5759. bool buf_start_with(const std::string &s) const {
  5760. return start_with(buf_, buf_spos_, buf_epos_, s);
  5761. }
  5762. size_t buf_find(const std::string &s) const {
  5763. auto c = s.front();
  5764. size_t off = buf_spos_;
  5765. while (off < buf_epos_) {
  5766. auto pos = off;
  5767. while (true) {
  5768. if (pos == buf_epos_) { return buf_size(); }
  5769. if (buf_[pos] == c) { break; }
  5770. pos++;
  5771. }
  5772. auto remaining_size = buf_epos_ - pos;
  5773. if (s.size() > remaining_size) { return buf_size(); }
  5774. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  5775. off = pos + 1;
  5776. }
  5777. return buf_size();
  5778. }
  5779. void buf_append(const char *data, size_t n) {
  5780. auto remaining_size = buf_size();
  5781. if (remaining_size > 0 && buf_spos_ > 0) {
  5782. for (size_t i = 0; i < remaining_size; i++) {
  5783. buf_[i] = buf_[buf_spos_ + i];
  5784. }
  5785. }
  5786. buf_spos_ = 0;
  5787. buf_epos_ = remaining_size;
  5788. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  5789. for (size_t i = 0; i < n; i++) {
  5790. buf_[buf_epos_ + i] = data[i];
  5791. }
  5792. buf_epos_ += n;
  5793. }
  5794. void buf_erase(size_t size) { buf_spos_ += size; }
  5795. std::string buf_;
  5796. size_t buf_spos_ = 0;
  5797. size_t buf_epos_ = 0;
  5798. };
  5799. inline std::string random_string(size_t length) {
  5800. constexpr const char data[] =
  5801. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  5802. thread_local auto engine([]() {
  5803. // std::random_device might actually be deterministic on some
  5804. // platforms, but due to lack of support in the c++ standard library,
  5805. // doing better requires either some ugly hacks or breaking portability.
  5806. std::random_device seed_gen;
  5807. // Request 128 bits of entropy for initialization
  5808. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  5809. return std::mt19937(seed_sequence);
  5810. }());
  5811. std::string result;
  5812. for (size_t i = 0; i < length; i++) {
  5813. result += data[engine() % (sizeof(data) - 1)];
  5814. }
  5815. return result;
  5816. }
  5817. inline std::string make_multipart_data_boundary() {
  5818. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  5819. }
  5820. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  5821. auto valid = true;
  5822. for (size_t i = 0; i < boundary.size(); i++) {
  5823. auto c = boundary[i];
  5824. if (!std::isalnum(c) && c != '-' && c != '_') {
  5825. valid = false;
  5826. break;
  5827. }
  5828. }
  5829. return valid;
  5830. }
  5831. template <typename T>
  5832. inline std::string
  5833. serialize_multipart_formdata_item_begin(const T &item,
  5834. const std::string &boundary) {
  5835. std::string body = "--" + boundary + "\r\n";
  5836. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5837. if (!item.filename.empty()) {
  5838. body += "; filename=\"" + item.filename + "\"";
  5839. }
  5840. body += "\r\n";
  5841. if (!item.content_type.empty()) {
  5842. body += "Content-Type: " + item.content_type + "\r\n";
  5843. }
  5844. body += "\r\n";
  5845. return body;
  5846. }
  5847. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  5848. inline std::string
  5849. serialize_multipart_formdata_finish(const std::string &boundary) {
  5850. return "--" + boundary + "--\r\n";
  5851. }
  5852. inline std::string
  5853. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  5854. return "multipart/form-data; boundary=" + boundary;
  5855. }
  5856. inline std::string
  5857. serialize_multipart_formdata(const UploadFormDataItems &items,
  5858. const std::string &boundary, bool finish = true) {
  5859. std::string body;
  5860. for (const auto &item : items) {
  5861. body += serialize_multipart_formdata_item_begin(item, boundary);
  5862. body += item.content + serialize_multipart_formdata_item_end();
  5863. }
  5864. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  5865. return body;
  5866. }
  5867. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  5868. if (ranges.size() <= 1) return;
  5869. // Sort ranges by start position
  5870. std::sort(ranges.begin(), ranges.end(),
  5871. [](const Range &a, const Range &b) { return a.first < b.first; });
  5872. Ranges coalesced;
  5873. coalesced.reserve(ranges.size());
  5874. for (auto &r : ranges) {
  5875. auto first_pos = r.first;
  5876. auto last_pos = r.second;
  5877. // Handle special cases like in range_error
  5878. if (first_pos == -1 && last_pos == -1) {
  5879. first_pos = 0;
  5880. last_pos = static_cast<ssize_t>(content_length);
  5881. }
  5882. if (first_pos == -1) {
  5883. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  5884. last_pos = static_cast<ssize_t>(content_length) - 1;
  5885. }
  5886. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  5887. last_pos = static_cast<ssize_t>(content_length) - 1;
  5888. }
  5889. // Skip invalid ranges
  5890. if (!(0 <= first_pos && first_pos <= last_pos &&
  5891. last_pos < static_cast<ssize_t>(content_length))) {
  5892. continue;
  5893. }
  5894. // Coalesce with previous range if overlapping or adjacent (but not
  5895. // identical)
  5896. if (!coalesced.empty()) {
  5897. auto &prev = coalesced.back();
  5898. // Check if current range overlaps or is adjacent to previous range
  5899. // but don't coalesce identical ranges (allow duplicates)
  5900. if (first_pos <= prev.second + 1 &&
  5901. !(first_pos == prev.first && last_pos == prev.second)) {
  5902. // Extend the previous range
  5903. prev.second = (std::max)(prev.second, last_pos);
  5904. continue;
  5905. }
  5906. }
  5907. // Add new range
  5908. coalesced.emplace_back(first_pos, last_pos);
  5909. }
  5910. ranges = std::move(coalesced);
  5911. }
  5912. inline bool range_error(Request &req, Response &res) {
  5913. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  5914. ssize_t content_len = static_cast<ssize_t>(
  5915. res.content_length_ ? res.content_length_ : res.body.size());
  5916. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  5917. size_t overwrapping_count = 0;
  5918. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  5919. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  5920. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  5921. // Too many ranges
  5922. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  5923. for (auto &r : req.ranges) {
  5924. auto &first_pos = r.first;
  5925. auto &last_pos = r.second;
  5926. if (first_pos == -1 && last_pos == -1) {
  5927. first_pos = 0;
  5928. last_pos = content_len;
  5929. }
  5930. if (first_pos == -1) {
  5931. first_pos = content_len - last_pos;
  5932. last_pos = content_len - 1;
  5933. }
  5934. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  5935. // A client can limit the number of bytes requested without knowing the
  5936. // size of the selected representation. If the last-pos value is absent,
  5937. // or if the value is greater than or equal to the current length of the
  5938. // representation data, the byte range is interpreted as the remainder of
  5939. // the representation (i.e., the server replaces the value of last-pos
  5940. // with a value that is one less than the current length of the selected
  5941. // representation).
  5942. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  5943. if (last_pos == -1 || last_pos >= content_len) {
  5944. last_pos = content_len - 1;
  5945. }
  5946. // Range must be within content length
  5947. if (!(0 <= first_pos && first_pos <= last_pos &&
  5948. last_pos <= content_len - 1)) {
  5949. return true;
  5950. }
  5951. // Request must not have more than two overlapping ranges
  5952. for (const auto &processed_range : processed_ranges) {
  5953. if (!(last_pos < processed_range.first ||
  5954. first_pos > processed_range.second)) {
  5955. overwrapping_count++;
  5956. if (overwrapping_count > 2) { return true; }
  5957. break; // Only count once per range
  5958. }
  5959. }
  5960. processed_ranges.emplace_back(first_pos, last_pos);
  5961. }
  5962. // After validation, coalesce overlapping ranges as per RFC 9110
  5963. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  5964. }
  5965. return false;
  5966. }
  5967. inline std::pair<size_t, size_t>
  5968. get_range_offset_and_length(Range r, size_t content_length) {
  5969. assert(r.first != -1 && r.second != -1);
  5970. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  5971. assert(r.first <= r.second &&
  5972. r.second < static_cast<ssize_t>(content_length));
  5973. (void)(content_length);
  5974. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  5975. }
  5976. inline std::string make_content_range_header_field(
  5977. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  5978. auto st = offset_and_length.first;
  5979. auto ed = st + offset_and_length.second - 1;
  5980. std::string field = "bytes ";
  5981. field += std::to_string(st);
  5982. field += '-';
  5983. field += std::to_string(ed);
  5984. field += '/';
  5985. field += std::to_string(content_length);
  5986. return field;
  5987. }
  5988. template <typename SToken, typename CToken, typename Content>
  5989. bool process_multipart_ranges_data(const Request &req,
  5990. const std::string &boundary,
  5991. const std::string &content_type,
  5992. size_t content_length, SToken stoken,
  5993. CToken ctoken, Content content) {
  5994. for (size_t i = 0; i < req.ranges.size(); i++) {
  5995. ctoken("--");
  5996. stoken(boundary);
  5997. ctoken("\r\n");
  5998. if (!content_type.empty()) {
  5999. ctoken("Content-Type: ");
  6000. stoken(content_type);
  6001. ctoken("\r\n");
  6002. }
  6003. auto offset_and_length =
  6004. get_range_offset_and_length(req.ranges[i], content_length);
  6005. ctoken("Content-Range: ");
  6006. stoken(make_content_range_header_field(offset_and_length, content_length));
  6007. ctoken("\r\n");
  6008. ctoken("\r\n");
  6009. if (!content(offset_and_length.first, offset_and_length.second)) {
  6010. return false;
  6011. }
  6012. ctoken("\r\n");
  6013. }
  6014. ctoken("--");
  6015. stoken(boundary);
  6016. ctoken("--");
  6017. return true;
  6018. }
  6019. inline void make_multipart_ranges_data(const Request &req, Response &res,
  6020. const std::string &boundary,
  6021. const std::string &content_type,
  6022. size_t content_length,
  6023. std::string &data) {
  6024. process_multipart_ranges_data(
  6025. req, boundary, content_type, content_length,
  6026. [&](const std::string &token) { data += token; },
  6027. [&](const std::string &token) { data += token; },
  6028. [&](size_t offset, size_t length) {
  6029. assert(offset + length <= content_length);
  6030. data += res.body.substr(offset, length);
  6031. return true;
  6032. });
  6033. }
  6034. inline size_t get_multipart_ranges_data_length(const Request &req,
  6035. const std::string &boundary,
  6036. const std::string &content_type,
  6037. size_t content_length) {
  6038. size_t data_length = 0;
  6039. process_multipart_ranges_data(
  6040. req, boundary, content_type, content_length,
  6041. [&](const std::string &token) { data_length += token.size(); },
  6042. [&](const std::string &token) { data_length += token.size(); },
  6043. [&](size_t /*offset*/, size_t length) {
  6044. data_length += length;
  6045. return true;
  6046. });
  6047. return data_length;
  6048. }
  6049. template <typename T>
  6050. inline bool
  6051. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  6052. const std::string &boundary,
  6053. const std::string &content_type,
  6054. size_t content_length, const T &is_shutting_down) {
  6055. return process_multipart_ranges_data(
  6056. req, boundary, content_type, content_length,
  6057. [&](const std::string &token) { strm.write(token); },
  6058. [&](const std::string &token) { strm.write(token); },
  6059. [&](size_t offset, size_t length) {
  6060. return write_content(strm, res.content_provider_, offset, length,
  6061. is_shutting_down);
  6062. });
  6063. }
  6064. inline bool expect_content(const Request &req) {
  6065. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  6066. req.method == "DELETE") {
  6067. return true;
  6068. }
  6069. if (req.has_header("Content-Length") &&
  6070. req.get_header_value_u64("Content-Length") > 0) {
  6071. return true;
  6072. }
  6073. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  6074. return false;
  6075. }
  6076. inline bool has_crlf(const std::string &s) {
  6077. auto p = s.c_str();
  6078. while (*p) {
  6079. if (*p == '\r' || *p == '\n') { return true; }
  6080. p++;
  6081. }
  6082. return false;
  6083. }
  6084. #ifdef _WIN32
  6085. class WSInit {
  6086. public:
  6087. WSInit() {
  6088. WSADATA wsaData;
  6089. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  6090. }
  6091. ~WSInit() {
  6092. if (is_valid_) WSACleanup();
  6093. }
  6094. bool is_valid_ = false;
  6095. };
  6096. static WSInit wsinit_;
  6097. #endif
  6098. inline bool parse_www_authenticate(const Response &res,
  6099. std::map<std::string, std::string> &auth,
  6100. bool is_proxy) {
  6101. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  6102. if (res.has_header(auth_key)) {
  6103. thread_local auto re =
  6104. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  6105. auto s = res.get_header_value(auth_key);
  6106. auto pos = s.find(' ');
  6107. if (pos != std::string::npos) {
  6108. auto type = s.substr(0, pos);
  6109. if (type == "Basic") {
  6110. return false;
  6111. } else if (type == "Digest") {
  6112. s = s.substr(pos + 1);
  6113. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  6114. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  6115. const auto &m = *i;
  6116. auto key = s.substr(static_cast<size_t>(m.position(1)),
  6117. static_cast<size_t>(m.length(1)));
  6118. auto val = m.length(2) > 0
  6119. ? s.substr(static_cast<size_t>(m.position(2)),
  6120. static_cast<size_t>(m.length(2)))
  6121. : s.substr(static_cast<size_t>(m.position(3)),
  6122. static_cast<size_t>(m.length(3)));
  6123. auth[std::move(key)] = std::move(val);
  6124. }
  6125. return true;
  6126. }
  6127. }
  6128. }
  6129. return false;
  6130. }
  6131. class ContentProviderAdapter {
  6132. public:
  6133. explicit ContentProviderAdapter(
  6134. ContentProviderWithoutLength &&content_provider)
  6135. : content_provider_(std::move(content_provider)) {}
  6136. bool operator()(size_t offset, size_t, DataSink &sink) {
  6137. return content_provider_(offset, sink);
  6138. }
  6139. private:
  6140. ContentProviderWithoutLength content_provider_;
  6141. };
  6142. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  6143. namespace fields {
  6144. inline bool is_token_char(char c) {
  6145. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  6146. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  6147. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  6148. }
  6149. inline bool is_token(const std::string &s) {
  6150. if (s.empty()) { return false; }
  6151. for (auto c : s) {
  6152. if (!is_token_char(c)) { return false; }
  6153. }
  6154. return true;
  6155. }
  6156. inline bool is_field_name(const std::string &s) { return is_token(s); }
  6157. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  6158. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  6159. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  6160. inline bool is_field_content(const std::string &s) {
  6161. if (s.empty()) { return true; }
  6162. if (s.size() == 1) {
  6163. return is_field_vchar(s[0]);
  6164. } else if (s.size() == 2) {
  6165. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  6166. } else {
  6167. size_t i = 0;
  6168. if (!is_field_vchar(s[i])) { return false; }
  6169. i++;
  6170. while (i < s.size() - 1) {
  6171. auto c = s[i++];
  6172. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  6173. } else {
  6174. return false;
  6175. }
  6176. }
  6177. return is_field_vchar(s[i]);
  6178. }
  6179. }
  6180. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  6181. } // namespace fields
  6182. } // namespace detail
  6183. /*
  6184. * Group 2: detail namespace - SSL common utilities
  6185. */
  6186. #ifdef CPPHTTPLIB_SSL_ENABLED
  6187. namespace detail {
  6188. class SSLSocketStream final : public Stream {
  6189. public:
  6190. SSLSocketStream(
  6191. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  6192. time_t read_timeout_usec, time_t write_timeout_sec,
  6193. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  6194. std::chrono::time_point<std::chrono::steady_clock> start_time =
  6195. (std::chrono::steady_clock::time_point::min)());
  6196. ~SSLSocketStream() override;
  6197. bool is_readable() const override;
  6198. bool wait_readable() const override;
  6199. bool wait_writable() const override;
  6200. ssize_t read(char *ptr, size_t size) override;
  6201. ssize_t write(const char *ptr, size_t size) override;
  6202. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  6203. void get_local_ip_and_port(std::string &ip, int &port) const override;
  6204. socket_t socket() const override;
  6205. time_t duration() const override;
  6206. private:
  6207. socket_t sock_;
  6208. tls::session_t session_;
  6209. time_t read_timeout_sec_;
  6210. time_t read_timeout_usec_;
  6211. time_t write_timeout_sec_;
  6212. time_t write_timeout_usec_;
  6213. time_t max_timeout_msec_;
  6214. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  6215. };
  6216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6217. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  6218. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  6219. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  6220. unsigned int hash_length = 0;
  6221. unsigned char hash[EVP_MAX_MD_SIZE];
  6222. EVP_DigestInit_ex(context.get(), algo, nullptr);
  6223. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  6224. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  6225. std::stringstream ss;
  6226. for (auto i = 0u; i < hash_length; ++i) {
  6227. ss << std::hex << std::setw(2) << std::setfill('0')
  6228. << static_cast<unsigned int>(hash[i]);
  6229. }
  6230. return ss.str();
  6231. }
  6232. inline std::string MD5(const std::string &s) {
  6233. return message_digest(s, EVP_md5());
  6234. }
  6235. inline std::string SHA_256(const std::string &s) {
  6236. return message_digest(s, EVP_sha256());
  6237. }
  6238. inline std::string SHA_512(const std::string &s) {
  6239. return message_digest(s, EVP_sha512());
  6240. }
  6241. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  6242. namespace {
  6243. template <size_t N>
  6244. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  6245. std::stringstream ss;
  6246. for (size_t i = 0; i < N; ++i) {
  6247. ss << std::hex << std::setw(2) << std::setfill('0')
  6248. << static_cast<unsigned int>(hash[i]);
  6249. }
  6250. return ss.str();
  6251. }
  6252. } // namespace
  6253. inline std::string MD5(const std::string &s) {
  6254. unsigned char hash[16];
  6255. #ifdef CPPHTTPLIB_MBEDTLS_V3
  6256. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6257. hash);
  6258. #else
  6259. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6260. hash);
  6261. #endif
  6262. return hash_to_hex(hash);
  6263. }
  6264. inline std::string SHA_256(const std::string &s) {
  6265. unsigned char hash[32];
  6266. #ifdef CPPHTTPLIB_MBEDTLS_V3
  6267. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6268. hash, 0);
  6269. #else
  6270. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6271. s.size(), hash, 0);
  6272. #endif
  6273. return hash_to_hex(hash);
  6274. }
  6275. inline std::string SHA_512(const std::string &s) {
  6276. unsigned char hash[64];
  6277. #ifdef CPPHTTPLIB_MBEDTLS_V3
  6278. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6279. hash, 0);
  6280. #else
  6281. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6282. s.size(), hash, 0);
  6283. #endif
  6284. return hash_to_hex(hash);
  6285. }
  6286. #endif
  6287. inline bool is_ip_address(const std::string &host) {
  6288. struct in_addr addr4;
  6289. struct in6_addr addr6;
  6290. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  6291. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  6292. }
  6293. template <typename T>
  6294. inline bool process_server_socket_ssl(
  6295. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  6296. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  6297. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  6298. time_t write_timeout_usec, T callback) {
  6299. return process_server_socket_core(
  6300. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  6301. [&](bool close_connection, bool &connection_closed) {
  6302. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  6303. write_timeout_sec, write_timeout_usec);
  6304. return callback(strm, close_connection, connection_closed);
  6305. });
  6306. }
  6307. template <typename T>
  6308. inline bool process_client_socket_ssl(
  6309. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  6310. time_t read_timeout_usec, time_t write_timeout_sec,
  6311. time_t write_timeout_usec, time_t max_timeout_msec,
  6312. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  6313. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  6314. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  6315. start_time);
  6316. return callback(strm);
  6317. }
  6318. inline std::pair<std::string, std::string> make_digest_authentication_header(
  6319. const Request &req, const std::map<std::string, std::string> &auth,
  6320. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  6321. const std::string &password, bool is_proxy = false) {
  6322. std::string nc;
  6323. {
  6324. std::stringstream ss;
  6325. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  6326. nc = ss.str();
  6327. }
  6328. std::string qop;
  6329. if (auth.find("qop") != auth.end()) {
  6330. qop = auth.at("qop");
  6331. if (qop.find("auth-int") != std::string::npos) {
  6332. qop = "auth-int";
  6333. } else if (qop.find("auth") != std::string::npos) {
  6334. qop = "auth";
  6335. } else {
  6336. qop.clear();
  6337. }
  6338. }
  6339. std::string algo = "MD5";
  6340. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  6341. std::string response;
  6342. {
  6343. auto H = algo == "SHA-256" ? detail::SHA_256
  6344. : algo == "SHA-512" ? detail::SHA_512
  6345. : detail::MD5;
  6346. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  6347. auto A2 = req.method + ":" + req.path;
  6348. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  6349. if (qop.empty()) {
  6350. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  6351. } else {
  6352. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  6353. ":" + qop + ":" + H(A2));
  6354. }
  6355. }
  6356. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  6357. auto field = "Digest username=\"" + username + "\", realm=\"" +
  6358. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  6359. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  6360. (qop.empty() ? ", response=\""
  6361. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  6362. cnonce + "\", response=\"") +
  6363. response + "\"" +
  6364. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  6365. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6366. return std::make_pair(key, field);
  6367. }
  6368. inline bool match_hostname(const std::string &pattern,
  6369. const std::string &hostname) {
  6370. // Exact match (case-insensitive)
  6371. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  6372. // Split both pattern and hostname into components by '.'
  6373. std::vector<std::string> pattern_components;
  6374. if (!pattern.empty()) {
  6375. split(pattern.data(), pattern.data() + pattern.size(), '.',
  6376. [&](const char *b, const char *e) {
  6377. pattern_components.emplace_back(b, e);
  6378. });
  6379. }
  6380. std::vector<std::string> host_components;
  6381. if (!hostname.empty()) {
  6382. split(hostname.data(), hostname.data() + hostname.size(), '.',
  6383. [&](const char *b, const char *e) {
  6384. host_components.emplace_back(b, e);
  6385. });
  6386. }
  6387. // Component count must match
  6388. if (host_components.size() != pattern_components.size()) { return false; }
  6389. // Compare each component with wildcard support
  6390. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  6391. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  6392. auto itr = pattern_components.begin();
  6393. for (const auto &h : host_components) {
  6394. auto &p = *itr;
  6395. if (!detail::case_ignore::equal(p, h) && p != "*") {
  6396. bool partial_match = false;
  6397. if (!p.empty() && p[p.size() - 1] == '*') {
  6398. const auto prefix_length = p.size() - 1;
  6399. if (prefix_length == 0) {
  6400. partial_match = true;
  6401. } else if (h.size() >= prefix_length) {
  6402. partial_match =
  6403. std::equal(p.begin(),
  6404. p.begin() + static_cast<std::string::difference_type>(
  6405. prefix_length),
  6406. h.begin(), [](const char ca, const char cb) {
  6407. return detail::case_ignore::to_lower(ca) ==
  6408. detail::case_ignore::to_lower(cb);
  6409. });
  6410. }
  6411. }
  6412. if (!partial_match) { return false; }
  6413. }
  6414. ++itr;
  6415. }
  6416. return true;
  6417. }
  6418. #ifdef _WIN32
  6419. // Verify certificate using Windows CertGetCertificateChain API.
  6420. // This provides real-time certificate validation with Windows Update
  6421. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  6422. inline bool verify_cert_with_windows_schannel(
  6423. const std::vector<unsigned char> &der_cert, const std::string &hostname,
  6424. bool verify_hostname, unsigned long &out_error) {
  6425. if (der_cert.empty()) { return false; }
  6426. out_error = 0;
  6427. // Create Windows certificate context from DER data
  6428. auto cert_context = CertCreateCertificateContext(
  6429. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  6430. static_cast<DWORD>(der_cert.size()));
  6431. if (!cert_context) {
  6432. out_error = GetLastError();
  6433. return false;
  6434. }
  6435. auto cert_guard =
  6436. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  6437. // Setup chain parameters
  6438. CERT_CHAIN_PARA chain_para = {};
  6439. chain_para.cbSize = sizeof(chain_para);
  6440. // Build certificate chain with revocation checking
  6441. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  6442. auto chain_result = CertGetCertificateChain(
  6443. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  6444. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  6445. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  6446. nullptr, &chain_context);
  6447. if (!chain_result || !chain_context) {
  6448. out_error = GetLastError();
  6449. return false;
  6450. }
  6451. auto chain_guard =
  6452. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  6453. // Check if chain has errors
  6454. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  6455. out_error = chain_context->TrustStatus.dwErrorStatus;
  6456. return false;
  6457. }
  6458. // Verify SSL policy
  6459. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  6460. extra_policy_para.cbSize = sizeof(extra_policy_para);
  6461. #ifdef AUTHTYPE_SERVER
  6462. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  6463. #endif
  6464. std::wstring whost;
  6465. if (verify_hostname) {
  6466. whost = u8string_to_wstring(hostname.c_str());
  6467. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  6468. }
  6469. CERT_CHAIN_POLICY_PARA policy_para = {};
  6470. policy_para.cbSize = sizeof(policy_para);
  6471. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  6472. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  6473. #else
  6474. policy_para.dwFlags = 0;
  6475. #endif
  6476. policy_para.pvExtraPolicyPara = &extra_policy_para;
  6477. CERT_CHAIN_POLICY_STATUS policy_status = {};
  6478. policy_status.cbSize = sizeof(policy_status);
  6479. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  6480. &policy_para, &policy_status)) {
  6481. out_error = GetLastError();
  6482. return false;
  6483. }
  6484. if (policy_status.dwError != 0) {
  6485. out_error = policy_status.dwError;
  6486. return false;
  6487. }
  6488. return true;
  6489. }
  6490. #endif // _WIN32
  6491. } // namespace detail
  6492. #endif // CPPHTTPLIB_SSL_ENABLED
  6493. /*
  6494. * Group 3: httplib namespace - Non-SSL public API implementations
  6495. */
  6496. inline void default_socket_options(socket_t sock) {
  6497. detail::set_socket_opt(sock, SOL_SOCKET,
  6498. #ifdef SO_REUSEPORT
  6499. SO_REUSEPORT,
  6500. #else
  6501. SO_REUSEADDR,
  6502. #endif
  6503. 1);
  6504. }
  6505. inline std::string get_bearer_token_auth(const Request &req) {
  6506. if (req.has_header("Authorization")) {
  6507. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  6508. return req.get_header_value("Authorization")
  6509. .substr(bearer_header_prefix_len);
  6510. }
  6511. return "";
  6512. }
  6513. inline const char *status_message(int status) {
  6514. switch (status) {
  6515. case StatusCode::Continue_100: return "Continue";
  6516. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  6517. case StatusCode::Processing_102: return "Processing";
  6518. case StatusCode::EarlyHints_103: return "Early Hints";
  6519. case StatusCode::OK_200: return "OK";
  6520. case StatusCode::Created_201: return "Created";
  6521. case StatusCode::Accepted_202: return "Accepted";
  6522. case StatusCode::NonAuthoritativeInformation_203:
  6523. return "Non-Authoritative Information";
  6524. case StatusCode::NoContent_204: return "No Content";
  6525. case StatusCode::ResetContent_205: return "Reset Content";
  6526. case StatusCode::PartialContent_206: return "Partial Content";
  6527. case StatusCode::MultiStatus_207: return "Multi-Status";
  6528. case StatusCode::AlreadyReported_208: return "Already Reported";
  6529. case StatusCode::IMUsed_226: return "IM Used";
  6530. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  6531. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  6532. case StatusCode::Found_302: return "Found";
  6533. case StatusCode::SeeOther_303: return "See Other";
  6534. case StatusCode::NotModified_304: return "Not Modified";
  6535. case StatusCode::UseProxy_305: return "Use Proxy";
  6536. case StatusCode::unused_306: return "unused";
  6537. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  6538. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  6539. case StatusCode::BadRequest_400: return "Bad Request";
  6540. case StatusCode::Unauthorized_401: return "Unauthorized";
  6541. case StatusCode::PaymentRequired_402: return "Payment Required";
  6542. case StatusCode::Forbidden_403: return "Forbidden";
  6543. case StatusCode::NotFound_404: return "Not Found";
  6544. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  6545. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  6546. case StatusCode::ProxyAuthenticationRequired_407:
  6547. return "Proxy Authentication Required";
  6548. case StatusCode::RequestTimeout_408: return "Request Timeout";
  6549. case StatusCode::Conflict_409: return "Conflict";
  6550. case StatusCode::Gone_410: return "Gone";
  6551. case StatusCode::LengthRequired_411: return "Length Required";
  6552. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  6553. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  6554. case StatusCode::UriTooLong_414: return "URI Too Long";
  6555. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  6556. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  6557. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  6558. case StatusCode::ImATeapot_418: return "I'm a teapot";
  6559. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  6560. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  6561. case StatusCode::Locked_423: return "Locked";
  6562. case StatusCode::FailedDependency_424: return "Failed Dependency";
  6563. case StatusCode::TooEarly_425: return "Too Early";
  6564. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  6565. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  6566. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  6567. case StatusCode::RequestHeaderFieldsTooLarge_431:
  6568. return "Request Header Fields Too Large";
  6569. case StatusCode::UnavailableForLegalReasons_451:
  6570. return "Unavailable For Legal Reasons";
  6571. case StatusCode::NotImplemented_501: return "Not Implemented";
  6572. case StatusCode::BadGateway_502: return "Bad Gateway";
  6573. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  6574. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  6575. case StatusCode::HttpVersionNotSupported_505:
  6576. return "HTTP Version Not Supported";
  6577. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  6578. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  6579. case StatusCode::LoopDetected_508: return "Loop Detected";
  6580. case StatusCode::NotExtended_510: return "Not Extended";
  6581. case StatusCode::NetworkAuthenticationRequired_511:
  6582. return "Network Authentication Required";
  6583. default:
  6584. case StatusCode::InternalServerError_500: return "Internal Server Error";
  6585. }
  6586. }
  6587. inline std::string to_string(const Error error) {
  6588. switch (error) {
  6589. case Error::Success: return "Success (no error)";
  6590. case Error::Unknown: return "Unknown";
  6591. case Error::Connection: return "Could not establish connection";
  6592. case Error::BindIPAddress: return "Failed to bind IP address";
  6593. case Error::Read: return "Failed to read connection";
  6594. case Error::Write: return "Failed to write connection";
  6595. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  6596. case Error::Canceled: return "Connection handling canceled";
  6597. case Error::SSLConnection: return "SSL connection failed";
  6598. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  6599. case Error::SSLServerVerification: return "SSL server verification failed";
  6600. case Error::SSLServerHostnameVerification:
  6601. return "SSL server hostname verification failed";
  6602. case Error::UnsupportedMultipartBoundaryChars:
  6603. return "Unsupported HTTP multipart boundary characters";
  6604. case Error::Compression: return "Compression failed";
  6605. case Error::ConnectionTimeout: return "Connection timed out";
  6606. case Error::ProxyConnection: return "Proxy connection failed";
  6607. case Error::ConnectionClosed: return "Connection closed by server";
  6608. case Error::Timeout: return "Read timeout";
  6609. case Error::ResourceExhaustion: return "Resource exhaustion";
  6610. case Error::TooManyFormDataFiles: return "Too many form data files";
  6611. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  6612. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  6613. case Error::ExceedMaxSocketDescriptorCount:
  6614. return "Exceeded maximum socket descriptor count";
  6615. case Error::InvalidRequestLine: return "Invalid request line";
  6616. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  6617. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  6618. case Error::InvalidHeaders: return "Invalid headers";
  6619. case Error::MultipartParsing: return "Multipart parsing failed";
  6620. case Error::OpenFile: return "Failed to open file";
  6621. case Error::Listen: return "Failed to listen on socket";
  6622. case Error::GetSockName: return "Failed to get socket name";
  6623. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  6624. case Error::HTTPParsing: return "HTTP parsing failed";
  6625. case Error::InvalidRangeHeader: return "Invalid Range header";
  6626. default: break;
  6627. }
  6628. return "Invalid";
  6629. }
  6630. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  6631. os << to_string(obj);
  6632. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  6633. return os;
  6634. }
  6635. inline std::string hosted_at(const std::string &hostname) {
  6636. std::vector<std::string> addrs;
  6637. hosted_at(hostname, addrs);
  6638. if (addrs.empty()) { return std::string(); }
  6639. return addrs[0];
  6640. }
  6641. inline void hosted_at(const std::string &hostname,
  6642. std::vector<std::string> &addrs) {
  6643. struct addrinfo hints;
  6644. struct addrinfo *result;
  6645. memset(&hints, 0, sizeof(struct addrinfo));
  6646. hints.ai_family = AF_UNSPEC;
  6647. hints.ai_socktype = SOCK_STREAM;
  6648. hints.ai_protocol = 0;
  6649. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  6650. &result, 0)) {
  6651. #if defined __linux__ && !defined __ANDROID__
  6652. res_init();
  6653. #endif
  6654. return;
  6655. }
  6656. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6657. for (auto rp = result; rp; rp = rp->ai_next) {
  6658. const auto &addr =
  6659. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  6660. std::string ip;
  6661. auto dummy = -1;
  6662. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  6663. dummy)) {
  6664. addrs.emplace_back(std::move(ip));
  6665. }
  6666. }
  6667. }
  6668. inline std::string encode_uri_component(const std::string &value) {
  6669. std::ostringstream escaped;
  6670. escaped.fill('0');
  6671. escaped << std::hex;
  6672. for (auto c : value) {
  6673. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6674. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6675. c == ')') {
  6676. escaped << c;
  6677. } else {
  6678. escaped << std::uppercase;
  6679. escaped << '%' << std::setw(2)
  6680. << static_cast<int>(static_cast<unsigned char>(c));
  6681. escaped << std::nouppercase;
  6682. }
  6683. }
  6684. return escaped.str();
  6685. }
  6686. inline std::string encode_uri(const std::string &value) {
  6687. std::ostringstream escaped;
  6688. escaped.fill('0');
  6689. escaped << std::hex;
  6690. for (auto c : value) {
  6691. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6692. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6693. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  6694. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  6695. escaped << c;
  6696. } else {
  6697. escaped << std::uppercase;
  6698. escaped << '%' << std::setw(2)
  6699. << static_cast<int>(static_cast<unsigned char>(c));
  6700. escaped << std::nouppercase;
  6701. }
  6702. }
  6703. return escaped.str();
  6704. }
  6705. inline std::string decode_uri_component(const std::string &value) {
  6706. std::string result;
  6707. for (size_t i = 0; i < value.size(); i++) {
  6708. if (value[i] == '%' && i + 2 < value.size()) {
  6709. auto val = 0;
  6710. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6711. result += static_cast<char>(val);
  6712. i += 2;
  6713. } else {
  6714. result += value[i];
  6715. }
  6716. } else {
  6717. result += value[i];
  6718. }
  6719. }
  6720. return result;
  6721. }
  6722. inline std::string decode_uri(const std::string &value) {
  6723. std::string result;
  6724. for (size_t i = 0; i < value.size(); i++) {
  6725. if (value[i] == '%' && i + 2 < value.size()) {
  6726. auto val = 0;
  6727. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6728. result += static_cast<char>(val);
  6729. i += 2;
  6730. } else {
  6731. result += value[i];
  6732. }
  6733. } else {
  6734. result += value[i];
  6735. }
  6736. }
  6737. return result;
  6738. }
  6739. inline std::string encode_path_component(const std::string &component) {
  6740. std::string result;
  6741. result.reserve(component.size() * 3);
  6742. for (size_t i = 0; i < component.size(); i++) {
  6743. auto c = static_cast<unsigned char>(component[i]);
  6744. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  6745. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6746. result += static_cast<char>(c);
  6747. }
  6748. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  6749. // "," / ";" / "="
  6750. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  6751. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  6752. c == '=') {
  6753. result += static_cast<char>(c);
  6754. }
  6755. // Colon is allowed in path segments except first segment
  6756. else if (c == ':') {
  6757. result += static_cast<char>(c);
  6758. }
  6759. // @ is allowed in path
  6760. else if (c == '@') {
  6761. result += static_cast<char>(c);
  6762. } else {
  6763. result += '%';
  6764. char hex[3];
  6765. snprintf(hex, sizeof(hex), "%02X", c);
  6766. result.append(hex, 2);
  6767. }
  6768. }
  6769. return result;
  6770. }
  6771. inline std::string decode_path_component(const std::string &component) {
  6772. std::string result;
  6773. result.reserve(component.size());
  6774. for (size_t i = 0; i < component.size(); i++) {
  6775. if (component[i] == '%' && i + 1 < component.size()) {
  6776. if (component[i + 1] == 'u') {
  6777. // Unicode %uXXXX encoding
  6778. auto val = 0;
  6779. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  6780. // 4 digits Unicode codes
  6781. char buff[4];
  6782. size_t len = detail::to_utf8(val, buff);
  6783. if (len > 0) { result.append(buff, len); }
  6784. i += 5; // 'u0000'
  6785. } else {
  6786. result += component[i];
  6787. }
  6788. } else {
  6789. // Standard %XX encoding
  6790. auto val = 0;
  6791. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  6792. // 2 digits hex codes
  6793. result += static_cast<char>(val);
  6794. i += 2; // 'XX'
  6795. } else {
  6796. result += component[i];
  6797. }
  6798. }
  6799. } else {
  6800. result += component[i];
  6801. }
  6802. }
  6803. return result;
  6804. }
  6805. inline std::string encode_query_component(const std::string &component,
  6806. bool space_as_plus) {
  6807. std::string result;
  6808. result.reserve(component.size() * 3);
  6809. for (size_t i = 0; i < component.size(); i++) {
  6810. auto c = static_cast<unsigned char>(component[i]);
  6811. // Unreserved characters per RFC 3986
  6812. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6813. result += static_cast<char>(c);
  6814. }
  6815. // Space handling
  6816. else if (c == ' ') {
  6817. if (space_as_plus) {
  6818. result += '+';
  6819. } else {
  6820. result += "%20";
  6821. }
  6822. }
  6823. // Plus sign handling
  6824. else if (c == '+') {
  6825. if (space_as_plus) {
  6826. result += "%2B";
  6827. } else {
  6828. result += static_cast<char>(c);
  6829. }
  6830. }
  6831. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  6832. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  6833. c == '*' || c == ',' || c == ';') {
  6834. result += static_cast<char>(c);
  6835. }
  6836. // Colon and @ are allowed in query
  6837. else if (c == ':' || c == '@') {
  6838. result += static_cast<char>(c);
  6839. }
  6840. // Forward slash is allowed in query values
  6841. else if (c == '/') {
  6842. result += static_cast<char>(c);
  6843. }
  6844. // Question mark is allowed in query values (after first ?)
  6845. else if (c == '?') {
  6846. result += static_cast<char>(c);
  6847. } else {
  6848. result += '%';
  6849. char hex[3];
  6850. snprintf(hex, sizeof(hex), "%02X", c);
  6851. result.append(hex, 2);
  6852. }
  6853. }
  6854. return result;
  6855. }
  6856. inline std::string decode_query_component(const std::string &component,
  6857. bool plus_as_space) {
  6858. std::string result;
  6859. result.reserve(component.size());
  6860. for (size_t i = 0; i < component.size(); i++) {
  6861. if (component[i] == '%' && i + 2 < component.size()) {
  6862. std::string hex = component.substr(i + 1, 2);
  6863. char *end;
  6864. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  6865. if (end == hex.c_str() + 2) {
  6866. result += static_cast<char>(value);
  6867. i += 2;
  6868. } else {
  6869. result += component[i];
  6870. }
  6871. } else if (component[i] == '+' && plus_as_space) {
  6872. result += ' '; // + becomes space in form-urlencoded
  6873. } else {
  6874. result += component[i];
  6875. }
  6876. }
  6877. return result;
  6878. }
  6879. inline std::string append_query_params(const std::string &path,
  6880. const Params &params) {
  6881. std::string path_with_query = path;
  6882. thread_local const std::regex re("[^?]+\\?.*");
  6883. auto delm = std::regex_match(path, re) ? '&' : '?';
  6884. path_with_query += delm + detail::params_to_query_str(params);
  6885. return path_with_query;
  6886. }
  6887. // Header utilities
  6888. inline std::pair<std::string, std::string>
  6889. make_range_header(const Ranges &ranges) {
  6890. std::string field = "bytes=";
  6891. auto i = 0;
  6892. for (const auto &r : ranges) {
  6893. if (i != 0) { field += ", "; }
  6894. if (r.first != -1) { field += std::to_string(r.first); }
  6895. field += '-';
  6896. if (r.second != -1) { field += std::to_string(r.second); }
  6897. i++;
  6898. }
  6899. return std::make_pair("Range", std::move(field));
  6900. }
  6901. inline std::pair<std::string, std::string>
  6902. make_basic_authentication_header(const std::string &username,
  6903. const std::string &password, bool is_proxy) {
  6904. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  6905. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6906. return std::make_pair(key, std::move(field));
  6907. }
  6908. inline std::pair<std::string, std::string>
  6909. make_bearer_token_authentication_header(const std::string &token,
  6910. bool is_proxy = false) {
  6911. auto field = "Bearer " + token;
  6912. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6913. return std::make_pair(key, std::move(field));
  6914. }
  6915. // Request implementation
  6916. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  6917. size_t id) const {
  6918. return detail::get_header_value_u64(headers, key, def, id);
  6919. }
  6920. inline bool Request::has_header(const std::string &key) const {
  6921. return detail::has_header(headers, key);
  6922. }
  6923. inline std::string Request::get_header_value(const std::string &key,
  6924. const char *def, size_t id) const {
  6925. return detail::get_header_value(headers, key, def, id);
  6926. }
  6927. inline size_t Request::get_header_value_count(const std::string &key) const {
  6928. auto r = headers.equal_range(key);
  6929. return static_cast<size_t>(std::distance(r.first, r.second));
  6930. }
  6931. inline void Request::set_header(const std::string &key,
  6932. const std::string &val) {
  6933. if (detail::fields::is_field_name(key) &&
  6934. detail::fields::is_field_value(val)) {
  6935. headers.emplace(key, val);
  6936. }
  6937. }
  6938. inline bool Request::has_trailer(const std::string &key) const {
  6939. return trailers.find(key) != trailers.end();
  6940. }
  6941. inline std::string Request::get_trailer_value(const std::string &key,
  6942. size_t id) const {
  6943. auto rng = trailers.equal_range(key);
  6944. auto it = rng.first;
  6945. std::advance(it, static_cast<ssize_t>(id));
  6946. if (it != rng.second) { return it->second; }
  6947. return std::string();
  6948. }
  6949. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  6950. auto r = trailers.equal_range(key);
  6951. return static_cast<size_t>(std::distance(r.first, r.second));
  6952. }
  6953. inline bool Request::has_param(const std::string &key) const {
  6954. return params.find(key) != params.end();
  6955. }
  6956. inline std::string Request::get_param_value(const std::string &key,
  6957. size_t id) const {
  6958. auto rng = params.equal_range(key);
  6959. auto it = rng.first;
  6960. std::advance(it, static_cast<ssize_t>(id));
  6961. if (it != rng.second) { return it->second; }
  6962. return std::string();
  6963. }
  6964. inline size_t Request::get_param_value_count(const std::string &key) const {
  6965. auto r = params.equal_range(key);
  6966. return static_cast<size_t>(std::distance(r.first, r.second));
  6967. }
  6968. inline bool Request::is_multipart_form_data() const {
  6969. const auto &content_type = get_header_value("Content-Type");
  6970. return !content_type.rfind("multipart/form-data", 0);
  6971. }
  6972. // Multipart FormData implementation
  6973. inline std::string MultipartFormData::get_field(const std::string &key,
  6974. size_t id) const {
  6975. auto rng = fields.equal_range(key);
  6976. auto it = rng.first;
  6977. std::advance(it, static_cast<ssize_t>(id));
  6978. if (it != rng.second) { return it->second.content; }
  6979. return std::string();
  6980. }
  6981. inline std::vector<std::string>
  6982. MultipartFormData::get_fields(const std::string &key) const {
  6983. std::vector<std::string> values;
  6984. auto rng = fields.equal_range(key);
  6985. for (auto it = rng.first; it != rng.second; it++) {
  6986. values.push_back(it->second.content);
  6987. }
  6988. return values;
  6989. }
  6990. inline bool MultipartFormData::has_field(const std::string &key) const {
  6991. return fields.find(key) != fields.end();
  6992. }
  6993. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  6994. auto r = fields.equal_range(key);
  6995. return static_cast<size_t>(std::distance(r.first, r.second));
  6996. }
  6997. inline FormData MultipartFormData::get_file(const std::string &key,
  6998. size_t id) const {
  6999. auto rng = files.equal_range(key);
  7000. auto it = rng.first;
  7001. std::advance(it, static_cast<ssize_t>(id));
  7002. if (it != rng.second) { return it->second; }
  7003. return FormData();
  7004. }
  7005. inline std::vector<FormData>
  7006. MultipartFormData::get_files(const std::string &key) const {
  7007. std::vector<FormData> values;
  7008. auto rng = files.equal_range(key);
  7009. for (auto it = rng.first; it != rng.second; it++) {
  7010. values.push_back(it->second);
  7011. }
  7012. return values;
  7013. }
  7014. inline bool MultipartFormData::has_file(const std::string &key) const {
  7015. return files.find(key) != files.end();
  7016. }
  7017. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  7018. auto r = files.equal_range(key);
  7019. return static_cast<size_t>(std::distance(r.first, r.second));
  7020. }
  7021. // Response implementation
  7022. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  7023. size_t id) const {
  7024. return detail::get_header_value_u64(headers, key, def, id);
  7025. }
  7026. inline bool Response::has_header(const std::string &key) const {
  7027. return headers.find(key) != headers.end();
  7028. }
  7029. inline std::string Response::get_header_value(const std::string &key,
  7030. const char *def,
  7031. size_t id) const {
  7032. return detail::get_header_value(headers, key, def, id);
  7033. }
  7034. inline size_t Response::get_header_value_count(const std::string &key) const {
  7035. auto r = headers.equal_range(key);
  7036. return static_cast<size_t>(std::distance(r.first, r.second));
  7037. }
  7038. inline void Response::set_header(const std::string &key,
  7039. const std::string &val) {
  7040. if (detail::fields::is_field_name(key) &&
  7041. detail::fields::is_field_value(val)) {
  7042. headers.emplace(key, val);
  7043. }
  7044. }
  7045. inline bool Response::has_trailer(const std::string &key) const {
  7046. return trailers.find(key) != trailers.end();
  7047. }
  7048. inline std::string Response::get_trailer_value(const std::string &key,
  7049. size_t id) const {
  7050. auto rng = trailers.equal_range(key);
  7051. auto it = rng.first;
  7052. std::advance(it, static_cast<ssize_t>(id));
  7053. if (it != rng.second) { return it->second; }
  7054. return std::string();
  7055. }
  7056. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  7057. auto r = trailers.equal_range(key);
  7058. return static_cast<size_t>(std::distance(r.first, r.second));
  7059. }
  7060. inline void Response::set_redirect(const std::string &url, int stat) {
  7061. if (detail::fields::is_field_value(url)) {
  7062. set_header("Location", url);
  7063. if (300 <= stat && stat < 400) {
  7064. this->status = stat;
  7065. } else {
  7066. this->status = StatusCode::Found_302;
  7067. }
  7068. }
  7069. }
  7070. inline void Response::set_content(const char *s, size_t n,
  7071. const std::string &content_type) {
  7072. body.assign(s, n);
  7073. auto rng = headers.equal_range("Content-Type");
  7074. headers.erase(rng.first, rng.second);
  7075. set_header("Content-Type", content_type);
  7076. }
  7077. inline void Response::set_content(const std::string &s,
  7078. const std::string &content_type) {
  7079. set_content(s.data(), s.size(), content_type);
  7080. }
  7081. inline void Response::set_content(std::string &&s,
  7082. const std::string &content_type) {
  7083. body = std::move(s);
  7084. auto rng = headers.equal_range("Content-Type");
  7085. headers.erase(rng.first, rng.second);
  7086. set_header("Content-Type", content_type);
  7087. }
  7088. inline void Response::set_content_provider(
  7089. size_t in_length, const std::string &content_type, ContentProvider provider,
  7090. ContentProviderResourceReleaser resource_releaser) {
  7091. set_header("Content-Type", content_type);
  7092. content_length_ = in_length;
  7093. if (in_length > 0) { content_provider_ = std::move(provider); }
  7094. content_provider_resource_releaser_ = std::move(resource_releaser);
  7095. is_chunked_content_provider_ = false;
  7096. }
  7097. inline void Response::set_content_provider(
  7098. const std::string &content_type, ContentProviderWithoutLength provider,
  7099. ContentProviderResourceReleaser resource_releaser) {
  7100. set_header("Content-Type", content_type);
  7101. content_length_ = 0;
  7102. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  7103. content_provider_resource_releaser_ = std::move(resource_releaser);
  7104. is_chunked_content_provider_ = false;
  7105. }
  7106. inline void Response::set_chunked_content_provider(
  7107. const std::string &content_type, ContentProviderWithoutLength provider,
  7108. ContentProviderResourceReleaser resource_releaser) {
  7109. set_header("Content-Type", content_type);
  7110. content_length_ = 0;
  7111. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  7112. content_provider_resource_releaser_ = std::move(resource_releaser);
  7113. is_chunked_content_provider_ = true;
  7114. }
  7115. inline void Response::set_file_content(const std::string &path,
  7116. const std::string &content_type) {
  7117. file_content_path_ = path;
  7118. file_content_content_type_ = content_type;
  7119. }
  7120. inline void Response::set_file_content(const std::string &path) {
  7121. file_content_path_ = path;
  7122. }
  7123. // Result implementation
  7124. inline size_t Result::get_request_header_value_u64(const std::string &key,
  7125. size_t def,
  7126. size_t id) const {
  7127. return detail::get_header_value_u64(request_headers_, key, def, id);
  7128. }
  7129. inline bool Result::has_request_header(const std::string &key) const {
  7130. return request_headers_.find(key) != request_headers_.end();
  7131. }
  7132. inline std::string Result::get_request_header_value(const std::string &key,
  7133. const char *def,
  7134. size_t id) const {
  7135. return detail::get_header_value(request_headers_, key, def, id);
  7136. }
  7137. inline size_t
  7138. Result::get_request_header_value_count(const std::string &key) const {
  7139. auto r = request_headers_.equal_range(key);
  7140. return static_cast<size_t>(std::distance(r.first, r.second));
  7141. }
  7142. // Stream implementation
  7143. inline ssize_t Stream::write(const char *ptr) {
  7144. return write(ptr, strlen(ptr));
  7145. }
  7146. inline ssize_t Stream::write(const std::string &s) {
  7147. return write(s.data(), s.size());
  7148. }
  7149. // BodyReader implementation
  7150. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  7151. if (!stream) {
  7152. last_error = Error::Connection;
  7153. return -1;
  7154. }
  7155. if (eof) { return 0; }
  7156. if (!chunked) {
  7157. // Content-Length based reading
  7158. if (has_content_length && bytes_read >= content_length) {
  7159. eof = true;
  7160. return 0;
  7161. }
  7162. auto to_read = len;
  7163. if (has_content_length) {
  7164. auto remaining = content_length - bytes_read;
  7165. to_read = (std::min)(len, remaining);
  7166. }
  7167. auto n = stream->read(buf, to_read);
  7168. if (n < 0) {
  7169. last_error = stream->get_error();
  7170. if (last_error == Error::Success) { last_error = Error::Read; }
  7171. eof = true;
  7172. return n;
  7173. }
  7174. if (n == 0) {
  7175. // Unexpected EOF before content_length
  7176. last_error = stream->get_error();
  7177. if (last_error == Error::Success) { last_error = Error::Read; }
  7178. eof = true;
  7179. return 0;
  7180. }
  7181. bytes_read += static_cast<size_t>(n);
  7182. if (has_content_length && bytes_read >= content_length) { eof = true; }
  7183. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  7184. last_error = Error::ExceedMaxPayloadSize;
  7185. eof = true;
  7186. return -1;
  7187. }
  7188. return n;
  7189. }
  7190. // Chunked transfer encoding: delegate to shared decoder instance.
  7191. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  7192. size_t chunk_offset = 0;
  7193. size_t chunk_total = 0;
  7194. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  7195. if (n < 0) {
  7196. last_error = stream->get_error();
  7197. if (last_error == Error::Success) { last_error = Error::Read; }
  7198. eof = true;
  7199. return n;
  7200. }
  7201. if (n == 0) {
  7202. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  7203. eof = true;
  7204. return 0;
  7205. }
  7206. bytes_read += static_cast<size_t>(n);
  7207. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  7208. last_error = Error::ExceedMaxPayloadSize;
  7209. eof = true;
  7210. return -1;
  7211. }
  7212. return n;
  7213. }
  7214. // ThreadPool implementation
  7215. inline ThreadPool::ThreadPool(size_t n, size_t mqr)
  7216. : shutdown_(false), max_queued_requests_(mqr) {
  7217. threads_.reserve(n);
  7218. while (n) {
  7219. threads_.emplace_back(worker(*this));
  7220. n--;
  7221. }
  7222. }
  7223. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  7224. {
  7225. std::unique_lock<std::mutex> lock(mutex_);
  7226. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  7227. return false;
  7228. }
  7229. jobs_.push_back(std::move(fn));
  7230. }
  7231. cond_.notify_one();
  7232. return true;
  7233. }
  7234. inline void ThreadPool::shutdown() {
  7235. // Stop all worker threads...
  7236. {
  7237. std::unique_lock<std::mutex> lock(mutex_);
  7238. shutdown_ = true;
  7239. }
  7240. cond_.notify_all();
  7241. // Join...
  7242. for (auto &t : threads_) {
  7243. t.join();
  7244. }
  7245. }
  7246. inline ThreadPool::worker::worker(ThreadPool &pool) : pool_(pool) {}
  7247. inline void ThreadPool::worker::operator()() {
  7248. for (;;) {
  7249. std::function<void()> fn;
  7250. {
  7251. std::unique_lock<std::mutex> lock(pool_.mutex_);
  7252. pool_.cond_.wait(lock,
  7253. [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  7254. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  7255. fn = pool_.jobs_.front();
  7256. pool_.jobs_.pop_front();
  7257. }
  7258. assert(true == static_cast<bool>(fn));
  7259. fn();
  7260. }
  7261. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  7262. !defined(LIBRESSL_VERSION_NUMBER)
  7263. OPENSSL_thread_stop();
  7264. #endif
  7265. }
  7266. /*
  7267. * Group 1 (continued): detail namespace - Stream implementations
  7268. */
  7269. namespace detail {
  7270. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  7271. time_t timeout_sec, time_t timeout_usec,
  7272. time_t &actual_timeout_sec,
  7273. time_t &actual_timeout_usec) {
  7274. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  7275. auto actual_timeout_msec =
  7276. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  7277. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  7278. actual_timeout_sec = actual_timeout_msec / 1000;
  7279. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  7280. }
  7281. // Socket stream implementation
  7282. inline SocketStream::SocketStream(
  7283. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  7284. time_t write_timeout_sec, time_t write_timeout_usec,
  7285. time_t max_timeout_msec,
  7286. std::chrono::time_point<std::chrono::steady_clock> start_time)
  7287. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  7288. read_timeout_usec_(read_timeout_usec),
  7289. write_timeout_sec_(write_timeout_sec),
  7290. write_timeout_usec_(write_timeout_usec),
  7291. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  7292. read_buff_(read_buff_size_, 0) {}
  7293. inline SocketStream::~SocketStream() = default;
  7294. inline bool SocketStream::is_readable() const {
  7295. return read_buff_off_ < read_buff_content_size_;
  7296. }
  7297. inline bool SocketStream::wait_readable() const {
  7298. if (max_timeout_msec_ <= 0) {
  7299. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  7300. }
  7301. time_t read_timeout_sec;
  7302. time_t read_timeout_usec;
  7303. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  7304. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  7305. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  7306. }
  7307. inline bool SocketStream::wait_writable() const {
  7308. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  7309. is_socket_alive(sock_);
  7310. }
  7311. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  7312. #ifdef _WIN32
  7313. size =
  7314. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7315. #else
  7316. size = (std::min)(size,
  7317. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  7318. #endif
  7319. if (read_buff_off_ < read_buff_content_size_) {
  7320. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  7321. if (size <= remaining_size) {
  7322. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  7323. read_buff_off_ += size;
  7324. return static_cast<ssize_t>(size);
  7325. } else {
  7326. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  7327. read_buff_off_ += remaining_size;
  7328. return static_cast<ssize_t>(remaining_size);
  7329. }
  7330. }
  7331. if (!wait_readable()) {
  7332. error_ = Error::Timeout;
  7333. return -1;
  7334. }
  7335. read_buff_off_ = 0;
  7336. read_buff_content_size_ = 0;
  7337. if (size < read_buff_size_) {
  7338. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  7339. CPPHTTPLIB_RECV_FLAGS);
  7340. if (n <= 0) {
  7341. if (n == 0) {
  7342. error_ = Error::ConnectionClosed;
  7343. } else {
  7344. error_ = Error::Read;
  7345. }
  7346. return n;
  7347. } else if (n <= static_cast<ssize_t>(size)) {
  7348. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  7349. return n;
  7350. } else {
  7351. memcpy(ptr, read_buff_.data(), size);
  7352. read_buff_off_ = size;
  7353. read_buff_content_size_ = static_cast<size_t>(n);
  7354. return static_cast<ssize_t>(size);
  7355. }
  7356. } else {
  7357. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  7358. if (n <= 0) {
  7359. if (n == 0) {
  7360. error_ = Error::ConnectionClosed;
  7361. } else {
  7362. error_ = Error::Read;
  7363. }
  7364. }
  7365. return n;
  7366. }
  7367. }
  7368. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  7369. if (!wait_writable()) { return -1; }
  7370. #if defined(_WIN32) && !defined(_WIN64)
  7371. size =
  7372. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7373. #endif
  7374. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  7375. }
  7376. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  7377. int &port) const {
  7378. return detail::get_remote_ip_and_port(sock_, ip, port);
  7379. }
  7380. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  7381. int &port) const {
  7382. return detail::get_local_ip_and_port(sock_, ip, port);
  7383. }
  7384. inline socket_t SocketStream::socket() const { return sock_; }
  7385. inline time_t SocketStream::duration() const {
  7386. return std::chrono::duration_cast<std::chrono::milliseconds>(
  7387. std::chrono::steady_clock::now() - start_time_)
  7388. .count();
  7389. }
  7390. // Buffer stream implementation
  7391. inline bool BufferStream::is_readable() const { return true; }
  7392. inline bool BufferStream::wait_readable() const { return true; }
  7393. inline bool BufferStream::wait_writable() const { return true; }
  7394. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  7395. #if defined(_MSC_VER) && _MSC_VER < 1910
  7396. auto len_read = buffer._Copy_s(ptr, size, size, position);
  7397. #else
  7398. auto len_read = buffer.copy(ptr, size, position);
  7399. #endif
  7400. position += static_cast<size_t>(len_read);
  7401. return static_cast<ssize_t>(len_read);
  7402. }
  7403. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  7404. buffer.append(ptr, size);
  7405. return static_cast<ssize_t>(size);
  7406. }
  7407. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  7408. int & /*port*/) const {}
  7409. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  7410. int & /*port*/) const {}
  7411. inline socket_t BufferStream::socket() const { return 0; }
  7412. inline time_t BufferStream::duration() const { return 0; }
  7413. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  7414. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  7415. : MatcherBase(pattern) {
  7416. constexpr const char marker[] = "/:";
  7417. // One past the last ending position of a path param substring
  7418. std::size_t last_param_end = 0;
  7419. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7420. // Needed to ensure that parameter names are unique during matcher
  7421. // construction
  7422. // If exceptions are disabled, only last duplicate path
  7423. // parameter will be set
  7424. std::unordered_set<std::string> param_name_set;
  7425. #endif
  7426. while (true) {
  7427. const auto marker_pos = pattern.find(
  7428. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  7429. if (marker_pos == std::string::npos) { break; }
  7430. static_fragments_.push_back(
  7431. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  7432. const auto param_name_start = marker_pos + str_len(marker);
  7433. auto sep_pos = pattern.find(separator, param_name_start);
  7434. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  7435. auto param_name =
  7436. pattern.substr(param_name_start, sep_pos - param_name_start);
  7437. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7438. if (param_name_set.find(param_name) != param_name_set.cend()) {
  7439. std::string msg = "Encountered path parameter '" + param_name +
  7440. "' multiple times in route pattern '" + pattern + "'.";
  7441. throw std::invalid_argument(msg);
  7442. }
  7443. #endif
  7444. param_names_.push_back(std::move(param_name));
  7445. last_param_end = sep_pos + 1;
  7446. }
  7447. if (last_param_end < pattern.length()) {
  7448. static_fragments_.push_back(pattern.substr(last_param_end));
  7449. }
  7450. }
  7451. inline bool PathParamsMatcher::match(Request &request) const {
  7452. request.matches = std::smatch();
  7453. request.path_params.clear();
  7454. request.path_params.reserve(param_names_.size());
  7455. // One past the position at which the path matched the pattern last time
  7456. std::size_t starting_pos = 0;
  7457. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  7458. const auto &fragment = static_fragments_[i];
  7459. if (starting_pos + fragment.length() > request.path.length()) {
  7460. return false;
  7461. }
  7462. // Avoid unnecessary allocation by using strncmp instead of substr +
  7463. // comparison
  7464. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  7465. fragment.length()) != 0) {
  7466. return false;
  7467. }
  7468. starting_pos += fragment.length();
  7469. // Should only happen when we have a static fragment after a param
  7470. // Example: '/users/:id/subscriptions'
  7471. // The 'subscriptions' fragment here does not have a corresponding param
  7472. if (i >= param_names_.size()) { continue; }
  7473. auto sep_pos = request.path.find(separator, starting_pos);
  7474. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  7475. const auto &param_name = param_names_[i];
  7476. request.path_params.emplace(
  7477. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  7478. // Mark everything up to '/' as matched
  7479. starting_pos = sep_pos + 1;
  7480. }
  7481. // Returns false if the path is longer than the pattern
  7482. return starting_pos >= request.path.length();
  7483. }
  7484. inline bool RegexMatcher::match(Request &request) const {
  7485. request.path_params.clear();
  7486. return std::regex_match(request.path, request.matches, regex_);
  7487. }
  7488. // Enclose IPv6 address in brackets if needed
  7489. inline std::string prepare_host_string(const std::string &host) {
  7490. // Enclose IPv6 address in brackets (but not if already enclosed)
  7491. if (host.find(':') == std::string::npos ||
  7492. (!host.empty() && host[0] == '[')) {
  7493. // IPv4, hostname, or already bracketed IPv6
  7494. return host;
  7495. } else {
  7496. // IPv6 address without brackets
  7497. return "[" + host + "]";
  7498. }
  7499. }
  7500. inline std::string make_host_and_port_string(const std::string &host, int port,
  7501. bool is_ssl) {
  7502. auto result = prepare_host_string(host);
  7503. // Append port if not default
  7504. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  7505. ; // do nothing
  7506. } else {
  7507. result += ":" + std::to_string(port);
  7508. }
  7509. return result;
  7510. }
  7511. // Create "host:port" string always including port number (for CONNECT method)
  7512. inline std::string
  7513. make_host_and_port_string_always_port(const std::string &host, int port) {
  7514. return prepare_host_string(host) + ":" + std::to_string(port);
  7515. }
  7516. template <typename T>
  7517. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  7518. T header_writer, Error &error) {
  7519. for (const auto &h : headers) {
  7520. if (!detail::fields::is_field_name(h.first) ||
  7521. !detail::fields::is_field_value(h.second)) {
  7522. error = Error::InvalidHeaders;
  7523. return false;
  7524. }
  7525. }
  7526. if (header_writer(strm, headers) <= 0) {
  7527. error = Error::Write;
  7528. return false;
  7529. }
  7530. return true;
  7531. }
  7532. } // namespace detail
  7533. /*
  7534. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  7535. */
  7536. #ifdef CPPHTTPLIB_SSL_ENABLED
  7537. namespace detail {
  7538. // SSL socket stream implementation
  7539. inline SSLSocketStream::SSLSocketStream(
  7540. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7541. time_t read_timeout_usec, time_t write_timeout_sec,
  7542. time_t write_timeout_usec, time_t max_timeout_msec,
  7543. std::chrono::time_point<std::chrono::steady_clock> start_time)
  7544. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  7545. read_timeout_usec_(read_timeout_usec),
  7546. write_timeout_sec_(write_timeout_sec),
  7547. write_timeout_usec_(write_timeout_usec),
  7548. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  7549. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7550. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  7551. // Note: create_session() also clears this, but SSLClient currently
  7552. // uses ssl_new() which does not. Until full TLS API migration is complete,
  7553. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  7554. // SSL session was created.
  7555. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  7556. #endif
  7557. }
  7558. inline SSLSocketStream::~SSLSocketStream() = default;
  7559. inline bool SSLSocketStream::is_readable() const {
  7560. return tls::pending(session_) > 0;
  7561. }
  7562. inline bool SSLSocketStream::wait_readable() const {
  7563. if (max_timeout_msec_ <= 0) {
  7564. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  7565. }
  7566. time_t read_timeout_sec;
  7567. time_t read_timeout_usec;
  7568. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  7569. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  7570. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  7571. }
  7572. inline bool SSLSocketStream::wait_writable() const {
  7573. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  7574. is_socket_alive(sock_) && !tls::is_peer_closed(session_, sock_);
  7575. }
  7576. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  7577. if (tls::pending(session_) > 0) {
  7578. tls::TlsError err;
  7579. auto ret = tls::read(session_, ptr, size, err);
  7580. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  7581. error_ = Error::ConnectionClosed;
  7582. }
  7583. return ret;
  7584. } else if (wait_readable()) {
  7585. tls::TlsError err;
  7586. auto ret = tls::read(session_, ptr, size, err);
  7587. if (ret < 0) {
  7588. auto n = 1000;
  7589. #ifdef _WIN32
  7590. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  7591. (err.code == tls::ErrorCode::SyscallError &&
  7592. WSAGetLastError() == WSAETIMEDOUT))) {
  7593. #else
  7594. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  7595. #endif
  7596. if (tls::pending(session_) > 0) {
  7597. return tls::read(session_, ptr, size, err);
  7598. } else if (wait_readable()) {
  7599. std::this_thread::sleep_for(std::chrono::microseconds{10});
  7600. ret = tls::read(session_, ptr, size, err);
  7601. if (ret >= 0) { return ret; }
  7602. } else {
  7603. break;
  7604. }
  7605. }
  7606. assert(ret < 0);
  7607. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  7608. error_ = Error::ConnectionClosed;
  7609. }
  7610. return ret;
  7611. } else {
  7612. error_ = Error::Timeout;
  7613. return -1;
  7614. }
  7615. }
  7616. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  7617. if (wait_writable()) {
  7618. auto handle_size =
  7619. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  7620. tls::TlsError err;
  7621. auto ret = tls::write(session_, ptr, handle_size, err);
  7622. if (ret < 0) {
  7623. auto n = 1000;
  7624. #ifdef _WIN32
  7625. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  7626. (err.code == tls::ErrorCode::SyscallError &&
  7627. WSAGetLastError() == WSAETIMEDOUT))) {
  7628. #else
  7629. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  7630. #endif
  7631. if (wait_writable()) {
  7632. std::this_thread::sleep_for(std::chrono::microseconds{10});
  7633. ret = tls::write(session_, ptr, handle_size, err);
  7634. if (ret >= 0) { return ret; }
  7635. } else {
  7636. break;
  7637. }
  7638. }
  7639. assert(ret < 0);
  7640. }
  7641. return ret;
  7642. }
  7643. return -1;
  7644. }
  7645. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  7646. int &port) const {
  7647. detail::get_remote_ip_and_port(sock_, ip, port);
  7648. }
  7649. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  7650. int &port) const {
  7651. detail::get_local_ip_and_port(sock_, ip, port);
  7652. }
  7653. inline socket_t SSLSocketStream::socket() const { return sock_; }
  7654. inline time_t SSLSocketStream::duration() const {
  7655. return std::chrono::duration_cast<std::chrono::milliseconds>(
  7656. std::chrono::steady_clock::now() - start_time_)
  7657. .count();
  7658. }
  7659. } // namespace detail
  7660. #endif // CPPHTTPLIB_SSL_ENABLED
  7661. /*
  7662. * Group 4: Server implementation
  7663. */
  7664. // HTTP server implementation
  7665. inline Server::Server()
  7666. : new_task_queue(
  7667. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  7668. #ifndef _WIN32
  7669. signal(SIGPIPE, SIG_IGN);
  7670. #endif
  7671. }
  7672. inline Server::~Server() = default;
  7673. inline std::unique_ptr<detail::MatcherBase>
  7674. Server::make_matcher(const std::string &pattern) {
  7675. if (pattern.find("/:") != std::string::npos) {
  7676. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  7677. } else {
  7678. return detail::make_unique<detail::RegexMatcher>(pattern);
  7679. }
  7680. }
  7681. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  7682. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7683. return *this;
  7684. }
  7685. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  7686. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7687. return *this;
  7688. }
  7689. inline Server &Server::Post(const std::string &pattern,
  7690. HandlerWithContentReader handler) {
  7691. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7692. std::move(handler));
  7693. return *this;
  7694. }
  7695. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  7696. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7697. return *this;
  7698. }
  7699. inline Server &Server::Put(const std::string &pattern,
  7700. HandlerWithContentReader handler) {
  7701. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7702. std::move(handler));
  7703. return *this;
  7704. }
  7705. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  7706. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7707. return *this;
  7708. }
  7709. inline Server &Server::Patch(const std::string &pattern,
  7710. HandlerWithContentReader handler) {
  7711. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7712. std::move(handler));
  7713. return *this;
  7714. }
  7715. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  7716. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7717. return *this;
  7718. }
  7719. inline Server &Server::Delete(const std::string &pattern,
  7720. HandlerWithContentReader handler) {
  7721. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7722. std::move(handler));
  7723. return *this;
  7724. }
  7725. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  7726. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7727. return *this;
  7728. }
  7729. inline bool Server::set_base_dir(const std::string &dir,
  7730. const std::string &mount_point) {
  7731. return set_mount_point(mount_point, dir);
  7732. }
  7733. inline bool Server::set_mount_point(const std::string &mount_point,
  7734. const std::string &dir, Headers headers) {
  7735. detail::FileStat stat(dir);
  7736. if (stat.is_dir()) {
  7737. std::string mnt = !mount_point.empty() ? mount_point : "/";
  7738. if (!mnt.empty() && mnt[0] == '/') {
  7739. base_dirs_.push_back({std::move(mnt), dir, std::move(headers)});
  7740. return true;
  7741. }
  7742. }
  7743. return false;
  7744. }
  7745. inline bool Server::remove_mount_point(const std::string &mount_point) {
  7746. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  7747. if (it->mount_point == mount_point) {
  7748. base_dirs_.erase(it);
  7749. return true;
  7750. }
  7751. }
  7752. return false;
  7753. }
  7754. inline Server &
  7755. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  7756. const std::string &mime) {
  7757. file_extension_and_mimetype_map_[ext] = mime;
  7758. return *this;
  7759. }
  7760. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  7761. default_file_mimetype_ = mime;
  7762. return *this;
  7763. }
  7764. inline Server &Server::set_file_request_handler(Handler handler) {
  7765. file_request_handler_ = std::move(handler);
  7766. return *this;
  7767. }
  7768. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  7769. std::true_type) {
  7770. error_handler_ = std::move(handler);
  7771. return *this;
  7772. }
  7773. inline Server &Server::set_error_handler_core(Handler handler,
  7774. std::false_type) {
  7775. error_handler_ = [handler](const Request &req, Response &res) {
  7776. handler(req, res);
  7777. return HandlerResponse::Handled;
  7778. };
  7779. return *this;
  7780. }
  7781. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  7782. exception_handler_ = std::move(handler);
  7783. return *this;
  7784. }
  7785. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  7786. pre_routing_handler_ = std::move(handler);
  7787. return *this;
  7788. }
  7789. inline Server &Server::set_post_routing_handler(Handler handler) {
  7790. post_routing_handler_ = std::move(handler);
  7791. return *this;
  7792. }
  7793. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  7794. pre_request_handler_ = std::move(handler);
  7795. return *this;
  7796. }
  7797. inline Server &Server::set_logger(Logger logger) {
  7798. logger_ = std::move(logger);
  7799. return *this;
  7800. }
  7801. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  7802. error_logger_ = std::move(error_logger);
  7803. return *this;
  7804. }
  7805. inline Server &Server::set_pre_compression_logger(Logger logger) {
  7806. pre_compression_logger_ = std::move(logger);
  7807. return *this;
  7808. }
  7809. inline Server &
  7810. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  7811. expect_100_continue_handler_ = std::move(handler);
  7812. return *this;
  7813. }
  7814. inline Server &Server::set_address_family(int family) {
  7815. address_family_ = family;
  7816. return *this;
  7817. }
  7818. inline Server &Server::set_tcp_nodelay(bool on) {
  7819. tcp_nodelay_ = on;
  7820. return *this;
  7821. }
  7822. inline Server &Server::set_ipv6_v6only(bool on) {
  7823. ipv6_v6only_ = on;
  7824. return *this;
  7825. }
  7826. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  7827. socket_options_ = std::move(socket_options);
  7828. return *this;
  7829. }
  7830. inline Server &Server::set_default_headers(Headers headers) {
  7831. default_headers_ = std::move(headers);
  7832. return *this;
  7833. }
  7834. inline Server &Server::set_header_writer(
  7835. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7836. header_writer_ = writer;
  7837. return *this;
  7838. }
  7839. inline Server &
  7840. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  7841. trusted_proxies_ = proxies;
  7842. return *this;
  7843. }
  7844. inline Server &Server::set_keep_alive_max_count(size_t count) {
  7845. keep_alive_max_count_ = count;
  7846. return *this;
  7847. }
  7848. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  7849. keep_alive_timeout_sec_ = sec;
  7850. return *this;
  7851. }
  7852. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  7853. read_timeout_sec_ = sec;
  7854. read_timeout_usec_ = usec;
  7855. return *this;
  7856. }
  7857. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  7858. write_timeout_sec_ = sec;
  7859. write_timeout_usec_ = usec;
  7860. return *this;
  7861. }
  7862. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  7863. idle_interval_sec_ = sec;
  7864. idle_interval_usec_ = usec;
  7865. return *this;
  7866. }
  7867. inline Server &Server::set_payload_max_length(size_t length) {
  7868. payload_max_length_ = length;
  7869. return *this;
  7870. }
  7871. inline bool Server::bind_to_port(const std::string &host, int port,
  7872. int socket_flags) {
  7873. auto ret = bind_internal(host, port, socket_flags);
  7874. if (ret == -1) { is_decommissioned = true; }
  7875. return ret >= 0;
  7876. }
  7877. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  7878. auto ret = bind_internal(host, 0, socket_flags);
  7879. if (ret == -1) { is_decommissioned = true; }
  7880. return ret;
  7881. }
  7882. inline bool Server::listen_after_bind() { return listen_internal(); }
  7883. inline bool Server::listen(const std::string &host, int port,
  7884. int socket_flags) {
  7885. return bind_to_port(host, port, socket_flags) && listen_internal();
  7886. }
  7887. inline bool Server::is_running() const { return is_running_; }
  7888. inline void Server::wait_until_ready() const {
  7889. while (!is_running_ && !is_decommissioned) {
  7890. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7891. }
  7892. }
  7893. inline void Server::stop() {
  7894. if (is_running_) {
  7895. assert(svr_sock_ != INVALID_SOCKET);
  7896. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  7897. detail::shutdown_socket(sock);
  7898. detail::close_socket(sock);
  7899. }
  7900. is_decommissioned = false;
  7901. }
  7902. inline void Server::decommission() { is_decommissioned = true; }
  7903. inline bool Server::parse_request_line(const char *s, Request &req) const {
  7904. auto len = strlen(s);
  7905. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  7906. len -= 2;
  7907. {
  7908. size_t count = 0;
  7909. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  7910. switch (count) {
  7911. case 0: req.method = std::string(b, e); break;
  7912. case 1: req.target = std::string(b, e); break;
  7913. case 2: req.version = std::string(b, e); break;
  7914. default: break;
  7915. }
  7916. count++;
  7917. });
  7918. if (count != 3) { return false; }
  7919. }
  7920. thread_local const std::set<std::string> methods{
  7921. "GET", "HEAD", "POST", "PUT", "DELETE",
  7922. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7923. if (methods.find(req.method) == methods.end()) {
  7924. output_error_log(Error::InvalidHTTPMethod, &req);
  7925. return false;
  7926. }
  7927. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  7928. output_error_log(Error::InvalidHTTPVersion, &req);
  7929. return false;
  7930. }
  7931. {
  7932. // Skip URL fragment
  7933. for (size_t i = 0; i < req.target.size(); i++) {
  7934. if (req.target[i] == '#') {
  7935. req.target.erase(i);
  7936. break;
  7937. }
  7938. }
  7939. detail::divide(req.target, '?',
  7940. [&](const char *lhs_data, std::size_t lhs_size,
  7941. const char *rhs_data, std::size_t rhs_size) {
  7942. req.path =
  7943. decode_path_component(std::string(lhs_data, lhs_size));
  7944. detail::parse_query_text(rhs_data, rhs_size, req.params);
  7945. });
  7946. }
  7947. return true;
  7948. }
  7949. inline bool Server::write_response(Stream &strm, bool close_connection,
  7950. Request &req, Response &res) {
  7951. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  7952. // incorrectly to the error content.
  7953. req.ranges.clear();
  7954. return write_response_core(strm, close_connection, req, res, false);
  7955. }
  7956. inline bool Server::write_response_with_content(Stream &strm,
  7957. bool close_connection,
  7958. const Request &req,
  7959. Response &res) {
  7960. return write_response_core(strm, close_connection, req, res, true);
  7961. }
  7962. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  7963. const Request &req, Response &res,
  7964. bool need_apply_ranges) {
  7965. assert(res.status != -1);
  7966. if (400 <= res.status && error_handler_ &&
  7967. error_handler_(req, res) == HandlerResponse::Handled) {
  7968. need_apply_ranges = true;
  7969. }
  7970. std::string content_type;
  7971. std::string boundary;
  7972. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  7973. // Prepare additional headers
  7974. if (close_connection || req.get_header_value("Connection") == "close" ||
  7975. 400 <= res.status) { // Don't leave connections open after errors
  7976. res.set_header("Connection", "close");
  7977. } else {
  7978. std::string s = "timeout=";
  7979. s += std::to_string(keep_alive_timeout_sec_);
  7980. s += ", max=";
  7981. s += std::to_string(keep_alive_max_count_);
  7982. res.set_header("Keep-Alive", s);
  7983. }
  7984. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  7985. !res.has_header("Content-Type")) {
  7986. res.set_header("Content-Type", "text/plain");
  7987. }
  7988. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  7989. !res.has_header("Content-Length")) {
  7990. res.set_header("Content-Length", "0");
  7991. }
  7992. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  7993. res.set_header("Accept-Ranges", "bytes");
  7994. }
  7995. if (post_routing_handler_) { post_routing_handler_(req, res); }
  7996. // Response line and headers
  7997. {
  7998. detail::BufferStream bstrm;
  7999. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  8000. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  8001. // Flush buffer
  8002. auto &data = bstrm.get_buffer();
  8003. detail::write_data(strm, data.data(), data.size());
  8004. }
  8005. // Body
  8006. auto ret = true;
  8007. if (req.method != "HEAD") {
  8008. if (!res.body.empty()) {
  8009. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  8010. ret = false;
  8011. }
  8012. } else if (res.content_provider_) {
  8013. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  8014. res.content_provider_success_ = true;
  8015. } else {
  8016. ret = false;
  8017. }
  8018. }
  8019. }
  8020. // Log
  8021. output_log(req, res);
  8022. return ret;
  8023. }
  8024. inline bool
  8025. Server::write_content_with_provider(Stream &strm, const Request &req,
  8026. Response &res, const std::string &boundary,
  8027. const std::string &content_type) {
  8028. auto is_shutting_down = [this]() {
  8029. return this->svr_sock_ == INVALID_SOCKET;
  8030. };
  8031. if (res.content_length_ > 0) {
  8032. if (req.ranges.empty()) {
  8033. return detail::write_content(strm, res.content_provider_, 0,
  8034. res.content_length_, is_shutting_down);
  8035. } else if (req.ranges.size() == 1) {
  8036. auto offset_and_length = detail::get_range_offset_and_length(
  8037. req.ranges[0], res.content_length_);
  8038. return detail::write_content(strm, res.content_provider_,
  8039. offset_and_length.first,
  8040. offset_and_length.second, is_shutting_down);
  8041. } else {
  8042. return detail::write_multipart_ranges_data(
  8043. strm, req, res, boundary, content_type, res.content_length_,
  8044. is_shutting_down);
  8045. }
  8046. } else {
  8047. if (res.is_chunked_content_provider_) {
  8048. auto type = detail::encoding_type(req, res);
  8049. std::unique_ptr<detail::compressor> compressor;
  8050. if (type == detail::EncodingType::Gzip) {
  8051. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8052. compressor = detail::make_unique<detail::gzip_compressor>();
  8053. #endif
  8054. } else if (type == detail::EncodingType::Brotli) {
  8055. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8056. compressor = detail::make_unique<detail::brotli_compressor>();
  8057. #endif
  8058. } else if (type == detail::EncodingType::Zstd) {
  8059. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8060. compressor = detail::make_unique<detail::zstd_compressor>();
  8061. #endif
  8062. } else {
  8063. compressor = detail::make_unique<detail::nocompressor>();
  8064. }
  8065. assert(compressor != nullptr);
  8066. return detail::write_content_chunked(strm, res.content_provider_,
  8067. is_shutting_down, *compressor);
  8068. } else {
  8069. return detail::write_content_without_length(strm, res.content_provider_,
  8070. is_shutting_down);
  8071. }
  8072. }
  8073. }
  8074. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  8075. FormFields::iterator cur_field;
  8076. FormFiles::iterator cur_file;
  8077. auto is_text_field = false;
  8078. size_t count = 0;
  8079. if (read_content_core(
  8080. strm, req, res,
  8081. // Regular
  8082. [&](const char *buf, size_t n) {
  8083. // Prevent arithmetic overflow when checking sizes.
  8084. // Avoid computing (req.body.size() + n) directly because
  8085. // adding two unsigned `size_t` values can wrap around and
  8086. // produce a small result instead of indicating overflow.
  8087. // Instead, check using subtraction: ensure `n` does not
  8088. // exceed the remaining capacity `max_size() - size()`.
  8089. if (req.body.size() >= req.body.max_size() ||
  8090. n > req.body.max_size() - req.body.size()) {
  8091. return false;
  8092. }
  8093. // Limit decompressed body size to payload_max_length_ to protect
  8094. // against "zip bomb" attacks where a small compressed payload
  8095. // decompresses to a massive size.
  8096. if (payload_max_length_ > 0 &&
  8097. (req.body.size() >= payload_max_length_ ||
  8098. n > payload_max_length_ - req.body.size())) {
  8099. return false;
  8100. }
  8101. req.body.append(buf, n);
  8102. return true;
  8103. },
  8104. // Multipart FormData
  8105. [&](const FormData &file) {
  8106. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  8107. output_error_log(Error::TooManyFormDataFiles, &req);
  8108. return false;
  8109. }
  8110. if (file.filename.empty()) {
  8111. cur_field = req.form.fields.emplace(
  8112. file.name, FormField{file.name, file.content, file.headers});
  8113. is_text_field = true;
  8114. } else {
  8115. cur_file = req.form.files.emplace(file.name, file);
  8116. is_text_field = false;
  8117. }
  8118. return true;
  8119. },
  8120. [&](const char *buf, size_t n) {
  8121. if (is_text_field) {
  8122. auto &content = cur_field->second.content;
  8123. if (content.size() + n > content.max_size()) { return false; }
  8124. content.append(buf, n);
  8125. } else {
  8126. auto &content = cur_file->second.content;
  8127. if (content.size() + n > content.max_size()) { return false; }
  8128. content.append(buf, n);
  8129. }
  8130. return true;
  8131. })) {
  8132. const auto &content_type = req.get_header_value("Content-Type");
  8133. if (!content_type.find("application/x-www-form-urlencoded")) {
  8134. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  8135. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  8136. output_error_log(Error::ExceedMaxPayloadSize, &req);
  8137. return false;
  8138. }
  8139. detail::parse_query_text(req.body, req.params);
  8140. }
  8141. return true;
  8142. }
  8143. return false;
  8144. }
  8145. inline bool Server::read_content_with_content_receiver(
  8146. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  8147. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  8148. return read_content_core(strm, req, res, std::move(receiver),
  8149. std::move(multipart_header),
  8150. std::move(multipart_receiver));
  8151. }
  8152. inline bool Server::read_content_core(
  8153. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  8154. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  8155. detail::FormDataParser multipart_form_data_parser;
  8156. ContentReceiverWithProgress out;
  8157. if (req.is_multipart_form_data()) {
  8158. const auto &content_type = req.get_header_value("Content-Type");
  8159. std::string boundary;
  8160. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  8161. res.status = StatusCode::BadRequest_400;
  8162. output_error_log(Error::MultipartParsing, &req);
  8163. return false;
  8164. }
  8165. multipart_form_data_parser.set_boundary(std::move(boundary));
  8166. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  8167. return multipart_form_data_parser.parse(buf, n, multipart_header,
  8168. multipart_receiver);
  8169. };
  8170. } else {
  8171. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  8172. size_t /*len*/) { return receiver(buf, n); };
  8173. }
  8174. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  8175. // are true (no Transfer-Encoding and no Content-Length), then the message
  8176. // body length is zero (no message body is present).
  8177. //
  8178. // For non-SSL builds, detect clients that send a body without a
  8179. // Content-Length header (raw HTTP over TCP). Check both the stream's
  8180. // internal read buffer (data already read from the socket during header
  8181. // parsing) and the socket itself for pending data. If data is found and
  8182. // exceeds the configured payload limit, reject with 413.
  8183. // For SSL builds we cannot reliably peek the decrypted application bytes,
  8184. // so keep the original behaviour.
  8185. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  8186. if (!req.has_header("Content-Length") &&
  8187. !detail::is_chunked_transfer_encoding(req.headers)) {
  8188. // Only check if payload_max_length is set to a finite value
  8189. if (payload_max_length_ > 0 &&
  8190. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  8191. // Check if there is data already buffered in the stream (read during
  8192. // header parsing) or pending on the socket. Use a non-blocking socket
  8193. // check to avoid deadlock when the client sends no body.
  8194. bool has_data = strm.is_readable();
  8195. if (!has_data) {
  8196. socket_t s = strm.socket();
  8197. if (s != INVALID_SOCKET) {
  8198. has_data = detail::select_read(s, 0, 0) > 0;
  8199. }
  8200. }
  8201. if (has_data) {
  8202. auto result =
  8203. detail::read_content_without_length(strm, payload_max_length_, out);
  8204. if (result == detail::ReadContentResult::PayloadTooLarge) {
  8205. res.status = StatusCode::PayloadTooLarge_413;
  8206. return false;
  8207. } else if (result != detail::ReadContentResult::Success) {
  8208. return false;
  8209. }
  8210. return true;
  8211. }
  8212. }
  8213. return true;
  8214. }
  8215. #else
  8216. if (!req.has_header("Content-Length") &&
  8217. !detail::is_chunked_transfer_encoding(req.headers)) {
  8218. return true;
  8219. }
  8220. #endif
  8221. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  8222. out, true)) {
  8223. return false;
  8224. }
  8225. if (req.is_multipart_form_data()) {
  8226. if (!multipart_form_data_parser.is_valid()) {
  8227. res.status = StatusCode::BadRequest_400;
  8228. output_error_log(Error::MultipartParsing, &req);
  8229. return false;
  8230. }
  8231. }
  8232. return true;
  8233. }
  8234. inline bool Server::handle_file_request(Request &req, Response &res) {
  8235. for (const auto &entry : base_dirs_) {
  8236. // Prefix match
  8237. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  8238. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  8239. if (detail::is_valid_path(sub_path)) {
  8240. auto path = entry.base_dir + sub_path;
  8241. if (path.back() == '/') { path += "index.html"; }
  8242. detail::FileStat stat(path);
  8243. if (stat.is_dir()) {
  8244. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  8245. return true;
  8246. }
  8247. if (stat.is_file()) {
  8248. for (const auto &kv : entry.headers) {
  8249. res.set_header(kv.first, kv.second);
  8250. }
  8251. auto etag = detail::compute_etag(stat);
  8252. if (!etag.empty()) { res.set_header("ETag", etag); }
  8253. auto mtime = stat.mtime();
  8254. auto last_modified = detail::file_mtime_to_http_date(mtime);
  8255. if (!last_modified.empty()) {
  8256. res.set_header("Last-Modified", last_modified);
  8257. }
  8258. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  8259. check_if_range(req, etag, mtime);
  8260. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8261. if (!mm->is_open()) {
  8262. output_error_log(Error::OpenFile, &req);
  8263. return false;
  8264. }
  8265. res.set_content_provider(
  8266. mm->size(),
  8267. detail::find_content_type(path, file_extension_and_mimetype_map_,
  8268. default_file_mimetype_),
  8269. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8270. sink.write(mm->data() + offset, length);
  8271. return true;
  8272. });
  8273. if (req.method != "HEAD" && file_request_handler_) {
  8274. file_request_handler_(req, res);
  8275. }
  8276. return true;
  8277. } else {
  8278. output_error_log(Error::OpenFile, &req);
  8279. }
  8280. }
  8281. }
  8282. }
  8283. return false;
  8284. }
  8285. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  8286. const std::string &etag,
  8287. time_t mtime) const {
  8288. // Handle conditional GET:
  8289. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  8290. // 2. If-Modified-Since is checked only when If-None-Match is absent
  8291. if (req.has_header("If-None-Match")) {
  8292. if (!etag.empty()) {
  8293. auto val = req.get_header_value("If-None-Match");
  8294. // NOTE: We use exact string matching here. This works correctly
  8295. // because our server always generates weak ETags (W/"..."), and
  8296. // clients typically send back the same ETag they received.
  8297. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  8298. // If-None-Match, where W/"x" and "x" would match, but this
  8299. // simplified implementation requires exact matches.
  8300. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  8301. [&](const char *b, const char *e) {
  8302. auto seg_len = static_cast<size_t>(e - b);
  8303. return (seg_len == 1 && *b == '*') ||
  8304. (seg_len == etag.size() &&
  8305. std::equal(b, e, etag.begin()));
  8306. });
  8307. if (ret) {
  8308. res.status = StatusCode::NotModified_304;
  8309. return true;
  8310. }
  8311. }
  8312. } else if (req.has_header("If-Modified-Since")) {
  8313. auto val = req.get_header_value("If-Modified-Since");
  8314. auto t = detail::parse_http_date(val);
  8315. if (t != static_cast<time_t>(-1) && mtime <= t) {
  8316. res.status = StatusCode::NotModified_304;
  8317. return true;
  8318. }
  8319. }
  8320. return false;
  8321. }
  8322. inline bool Server::check_if_range(Request &req, const std::string &etag,
  8323. time_t mtime) const {
  8324. // Handle If-Range for partial content requests (RFC 9110
  8325. // Section 13.1.5). If-Range is only evaluated when Range header is
  8326. // present. If the validator matches, serve partial content; otherwise
  8327. // serve full content.
  8328. if (!req.ranges.empty() && req.has_header("If-Range")) {
  8329. auto val = req.get_header_value("If-Range");
  8330. auto is_valid_range = [&]() {
  8331. if (detail::is_strong_etag(val)) {
  8332. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  8333. // comparison.
  8334. return (!etag.empty() && val == etag);
  8335. } else if (detail::is_weak_etag(val)) {
  8336. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  8337. return false;
  8338. } else {
  8339. // HTTP-date comparison
  8340. auto t = detail::parse_http_date(val);
  8341. return (t != static_cast<time_t>(-1) && mtime <= t);
  8342. }
  8343. };
  8344. if (!is_valid_range()) {
  8345. // Validator doesn't match: ignore Range and serve full content
  8346. req.ranges.clear();
  8347. return false;
  8348. }
  8349. }
  8350. return true;
  8351. }
  8352. inline socket_t
  8353. Server::create_server_socket(const std::string &host, int port,
  8354. int socket_flags,
  8355. SocketOptions socket_options) const {
  8356. return detail::create_socket(
  8357. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  8358. ipv6_v6only_, std::move(socket_options),
  8359. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  8360. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  8361. output_error_log(Error::BindIPAddress, nullptr);
  8362. return false;
  8363. }
  8364. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  8365. output_error_log(Error::Listen, nullptr);
  8366. return false;
  8367. }
  8368. return true;
  8369. });
  8370. }
  8371. inline int Server::bind_internal(const std::string &host, int port,
  8372. int socket_flags) {
  8373. if (is_decommissioned) { return -1; }
  8374. if (!is_valid()) { return -1; }
  8375. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  8376. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  8377. if (port == 0) {
  8378. struct sockaddr_storage addr;
  8379. socklen_t addr_len = sizeof(addr);
  8380. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  8381. &addr_len) == -1) {
  8382. output_error_log(Error::GetSockName, nullptr);
  8383. return -1;
  8384. }
  8385. if (addr.ss_family == AF_INET) {
  8386. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  8387. } else if (addr.ss_family == AF_INET6) {
  8388. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  8389. } else {
  8390. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  8391. return -1;
  8392. }
  8393. } else {
  8394. return port;
  8395. }
  8396. }
  8397. inline bool Server::listen_internal() {
  8398. if (is_decommissioned) { return false; }
  8399. auto ret = true;
  8400. is_running_ = true;
  8401. auto se = detail::scope_exit([&]() { is_running_ = false; });
  8402. {
  8403. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  8404. while (svr_sock_ != INVALID_SOCKET) {
  8405. #ifndef _WIN32
  8406. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  8407. #endif
  8408. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  8409. idle_interval_usec_);
  8410. if (val == 0) { // Timeout
  8411. task_queue->on_idle();
  8412. continue;
  8413. }
  8414. #ifndef _WIN32
  8415. }
  8416. #endif
  8417. #if defined _WIN32
  8418. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  8419. // OVERLAPPED
  8420. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  8421. #elif defined SOCK_CLOEXEC
  8422. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  8423. #else
  8424. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  8425. #endif
  8426. if (sock == INVALID_SOCKET) {
  8427. if (errno == EMFILE) {
  8428. // The per-process limit of open file descriptors has been reached.
  8429. // Try to accept new connections after a short sleep.
  8430. std::this_thread::sleep_for(std::chrono::microseconds{1});
  8431. continue;
  8432. } else if (errno == EINTR || errno == EAGAIN) {
  8433. continue;
  8434. }
  8435. if (svr_sock_ != INVALID_SOCKET) {
  8436. detail::close_socket(svr_sock_);
  8437. ret = false;
  8438. output_error_log(Error::Connection, nullptr);
  8439. } else {
  8440. ; // The server socket was closed by user.
  8441. }
  8442. break;
  8443. }
  8444. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  8445. read_timeout_sec_, read_timeout_usec_);
  8446. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  8447. write_timeout_sec_, write_timeout_usec_);
  8448. if (!task_queue->enqueue(
  8449. [this, sock]() { process_and_close_socket(sock); })) {
  8450. output_error_log(Error::ResourceExhaustion, nullptr);
  8451. detail::shutdown_socket(sock);
  8452. detail::close_socket(sock);
  8453. }
  8454. }
  8455. task_queue->shutdown();
  8456. }
  8457. is_decommissioned = !ret;
  8458. return ret;
  8459. }
  8460. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  8461. if (pre_routing_handler_ &&
  8462. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  8463. return true;
  8464. }
  8465. // File handler
  8466. if ((req.method == "GET" || req.method == "HEAD") &&
  8467. handle_file_request(req, res)) {
  8468. return true;
  8469. }
  8470. if (detail::expect_content(req)) {
  8471. // Content reader handler
  8472. {
  8473. ContentReader reader(
  8474. [&](ContentReceiver receiver) {
  8475. auto result = read_content_with_content_receiver(
  8476. strm, req, res, std::move(receiver), nullptr, nullptr);
  8477. if (!result) { output_error_log(Error::Read, &req); }
  8478. return result;
  8479. },
  8480. [&](FormDataHeader header, ContentReceiver receiver) {
  8481. auto result = read_content_with_content_receiver(
  8482. strm, req, res, nullptr, std::move(header),
  8483. std::move(receiver));
  8484. if (!result) { output_error_log(Error::Read, &req); }
  8485. return result;
  8486. });
  8487. if (req.method == "POST") {
  8488. if (dispatch_request_for_content_reader(
  8489. req, res, std::move(reader),
  8490. post_handlers_for_content_reader_)) {
  8491. return true;
  8492. }
  8493. } else if (req.method == "PUT") {
  8494. if (dispatch_request_for_content_reader(
  8495. req, res, std::move(reader),
  8496. put_handlers_for_content_reader_)) {
  8497. return true;
  8498. }
  8499. } else if (req.method == "PATCH") {
  8500. if (dispatch_request_for_content_reader(
  8501. req, res, std::move(reader),
  8502. patch_handlers_for_content_reader_)) {
  8503. return true;
  8504. }
  8505. } else if (req.method == "DELETE") {
  8506. if (dispatch_request_for_content_reader(
  8507. req, res, std::move(reader),
  8508. delete_handlers_for_content_reader_)) {
  8509. return true;
  8510. }
  8511. }
  8512. }
  8513. // Read content into `req.body`
  8514. if (!read_content(strm, req, res)) {
  8515. output_error_log(Error::Read, &req);
  8516. return false;
  8517. }
  8518. }
  8519. // Regular handler
  8520. if (req.method == "GET" || req.method == "HEAD") {
  8521. return dispatch_request(req, res, get_handlers_);
  8522. } else if (req.method == "POST") {
  8523. return dispatch_request(req, res, post_handlers_);
  8524. } else if (req.method == "PUT") {
  8525. return dispatch_request(req, res, put_handlers_);
  8526. } else if (req.method == "DELETE") {
  8527. return dispatch_request(req, res, delete_handlers_);
  8528. } else if (req.method == "OPTIONS") {
  8529. return dispatch_request(req, res, options_handlers_);
  8530. } else if (req.method == "PATCH") {
  8531. return dispatch_request(req, res, patch_handlers_);
  8532. }
  8533. res.status = StatusCode::BadRequest_400;
  8534. return false;
  8535. }
  8536. inline bool Server::dispatch_request(Request &req, Response &res,
  8537. const Handlers &handlers) const {
  8538. for (const auto &x : handlers) {
  8539. const auto &matcher = x.first;
  8540. const auto &handler = x.second;
  8541. if (matcher->match(req)) {
  8542. req.matched_route = matcher->pattern();
  8543. if (!pre_request_handler_ ||
  8544. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8545. handler(req, res);
  8546. }
  8547. return true;
  8548. }
  8549. }
  8550. return false;
  8551. }
  8552. inline void Server::apply_ranges(const Request &req, Response &res,
  8553. std::string &content_type,
  8554. std::string &boundary) const {
  8555. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  8556. auto it = res.headers.find("Content-Type");
  8557. if (it != res.headers.end()) {
  8558. content_type = it->second;
  8559. res.headers.erase(it);
  8560. }
  8561. boundary = detail::make_multipart_data_boundary();
  8562. res.set_header("Content-Type",
  8563. "multipart/byteranges; boundary=" + boundary);
  8564. }
  8565. auto type = detail::encoding_type(req, res);
  8566. if (res.body.empty()) {
  8567. if (res.content_length_ > 0) {
  8568. size_t length = 0;
  8569. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8570. length = res.content_length_;
  8571. } else if (req.ranges.size() == 1) {
  8572. auto offset_and_length = detail::get_range_offset_and_length(
  8573. req.ranges[0], res.content_length_);
  8574. length = offset_and_length.second;
  8575. auto content_range = detail::make_content_range_header_field(
  8576. offset_and_length, res.content_length_);
  8577. res.set_header("Content-Range", content_range);
  8578. } else {
  8579. length = detail::get_multipart_ranges_data_length(
  8580. req, boundary, content_type, res.content_length_);
  8581. }
  8582. res.set_header("Content-Length", std::to_string(length));
  8583. } else {
  8584. if (res.content_provider_) {
  8585. if (res.is_chunked_content_provider_) {
  8586. res.set_header("Transfer-Encoding", "chunked");
  8587. if (type == detail::EncodingType::Gzip) {
  8588. res.set_header("Content-Encoding", "gzip");
  8589. res.set_header("Vary", "Accept-Encoding");
  8590. } else if (type == detail::EncodingType::Brotli) {
  8591. res.set_header("Content-Encoding", "br");
  8592. res.set_header("Vary", "Accept-Encoding");
  8593. } else if (type == detail::EncodingType::Zstd) {
  8594. res.set_header("Content-Encoding", "zstd");
  8595. res.set_header("Vary", "Accept-Encoding");
  8596. }
  8597. }
  8598. }
  8599. }
  8600. } else {
  8601. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8602. ;
  8603. } else if (req.ranges.size() == 1) {
  8604. auto offset_and_length =
  8605. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  8606. auto offset = offset_and_length.first;
  8607. auto length = offset_and_length.second;
  8608. auto content_range = detail::make_content_range_header_field(
  8609. offset_and_length, res.body.size());
  8610. res.set_header("Content-Range", content_range);
  8611. assert(offset + length <= res.body.size());
  8612. res.body = res.body.substr(offset, length);
  8613. } else {
  8614. std::string data;
  8615. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  8616. res.body.size(), data);
  8617. res.body.swap(data);
  8618. }
  8619. if (type != detail::EncodingType::None) {
  8620. output_pre_compression_log(req, res);
  8621. std::unique_ptr<detail::compressor> compressor;
  8622. std::string content_encoding;
  8623. if (type == detail::EncodingType::Gzip) {
  8624. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8625. compressor = detail::make_unique<detail::gzip_compressor>();
  8626. content_encoding = "gzip";
  8627. #endif
  8628. } else if (type == detail::EncodingType::Brotli) {
  8629. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8630. compressor = detail::make_unique<detail::brotli_compressor>();
  8631. content_encoding = "br";
  8632. #endif
  8633. } else if (type == detail::EncodingType::Zstd) {
  8634. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8635. compressor = detail::make_unique<detail::zstd_compressor>();
  8636. content_encoding = "zstd";
  8637. #endif
  8638. }
  8639. if (compressor) {
  8640. std::string compressed;
  8641. if (compressor->compress(res.body.data(), res.body.size(), true,
  8642. [&](const char *data, size_t data_len) {
  8643. compressed.append(data, data_len);
  8644. return true;
  8645. })) {
  8646. res.body.swap(compressed);
  8647. res.set_header("Content-Encoding", content_encoding);
  8648. res.set_header("Vary", "Accept-Encoding");
  8649. }
  8650. }
  8651. }
  8652. auto length = std::to_string(res.body.size());
  8653. res.set_header("Content-Length", length);
  8654. }
  8655. }
  8656. inline bool Server::dispatch_request_for_content_reader(
  8657. Request &req, Response &res, ContentReader content_reader,
  8658. const HandlersForContentReader &handlers) const {
  8659. for (const auto &x : handlers) {
  8660. const auto &matcher = x.first;
  8661. const auto &handler = x.second;
  8662. if (matcher->match(req)) {
  8663. req.matched_route = matcher->pattern();
  8664. if (!pre_request_handler_ ||
  8665. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8666. handler(req, res, content_reader);
  8667. }
  8668. return true;
  8669. }
  8670. }
  8671. return false;
  8672. }
  8673. inline std::string
  8674. get_client_ip(const std::string &x_forwarded_for,
  8675. const std::vector<std::string> &trusted_proxies) {
  8676. // X-Forwarded-For is a comma-separated list per RFC 7239
  8677. std::vector<std::string> ip_list;
  8678. detail::split(x_forwarded_for.data(),
  8679. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  8680. [&](const char *b, const char *e) {
  8681. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  8682. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  8683. });
  8684. for (size_t i = 0; i < ip_list.size(); ++i) {
  8685. auto ip = ip_list[i];
  8686. auto is_trusted_proxy =
  8687. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  8688. [&](const std::string &proxy) { return ip == proxy; });
  8689. if (is_trusted_proxy) {
  8690. if (i == 0) {
  8691. // If the trusted proxy is the first IP, there's no preceding client IP
  8692. return ip;
  8693. } else {
  8694. // Return the IP immediately before the trusted proxy
  8695. return ip_list[i - 1];
  8696. }
  8697. }
  8698. }
  8699. // If no trusted proxy is found, return the first IP in the list
  8700. return ip_list.front();
  8701. }
  8702. inline bool
  8703. Server::process_request(Stream &strm, const std::string &remote_addr,
  8704. int remote_port, const std::string &local_addr,
  8705. int local_port, bool close_connection,
  8706. bool &connection_closed,
  8707. const std::function<void(Request &)> &setup_request) {
  8708. std::array<char, 2048> buf{};
  8709. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8710. // Connection has been closed on client
  8711. if (!line_reader.getline()) { return false; }
  8712. Request req;
  8713. req.start_time_ = std::chrono::steady_clock::now();
  8714. req.remote_addr = remote_addr;
  8715. req.remote_port = remote_port;
  8716. req.local_addr = local_addr;
  8717. req.local_port = local_port;
  8718. Response res;
  8719. res.version = "HTTP/1.1";
  8720. res.headers = default_headers_;
  8721. // Request line and headers
  8722. if (!parse_request_line(line_reader.ptr(), req)) {
  8723. res.status = StatusCode::BadRequest_400;
  8724. output_error_log(Error::InvalidRequestLine, &req);
  8725. return write_response(strm, close_connection, req, res);
  8726. }
  8727. // Request headers
  8728. if (!detail::read_headers(strm, req.headers)) {
  8729. res.status = StatusCode::BadRequest_400;
  8730. output_error_log(Error::InvalidHeaders, &req);
  8731. return write_response(strm, close_connection, req, res);
  8732. }
  8733. // Check if the request URI doesn't exceed the limit
  8734. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  8735. res.status = StatusCode::UriTooLong_414;
  8736. output_error_log(Error::ExceedUriMaxLength, &req);
  8737. return write_response(strm, close_connection, req, res);
  8738. }
  8739. if (req.get_header_value("Connection") == "close") {
  8740. connection_closed = true;
  8741. }
  8742. if (req.version == "HTTP/1.0" &&
  8743. req.get_header_value("Connection") != "Keep-Alive") {
  8744. connection_closed = true;
  8745. }
  8746. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  8747. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  8748. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  8749. } else {
  8750. req.remote_addr = remote_addr;
  8751. }
  8752. req.remote_port = remote_port;
  8753. req.local_addr = local_addr;
  8754. req.local_port = local_port;
  8755. if (req.has_header("Accept")) {
  8756. const auto &accept_header = req.get_header_value("Accept");
  8757. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  8758. res.status = StatusCode::BadRequest_400;
  8759. output_error_log(Error::HTTPParsing, &req);
  8760. return write_response(strm, close_connection, req, res);
  8761. }
  8762. }
  8763. if (req.has_header("Range")) {
  8764. const auto &range_header_value = req.get_header_value("Range");
  8765. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  8766. res.status = StatusCode::RangeNotSatisfiable_416;
  8767. output_error_log(Error::InvalidRangeHeader, &req);
  8768. return write_response(strm, close_connection, req, res);
  8769. }
  8770. }
  8771. if (setup_request) { setup_request(req); }
  8772. if (req.get_header_value("Expect") == "100-continue") {
  8773. int status = StatusCode::Continue_100;
  8774. if (expect_100_continue_handler_) {
  8775. status = expect_100_continue_handler_(req, res);
  8776. }
  8777. switch (status) {
  8778. case StatusCode::Continue_100:
  8779. case StatusCode::ExpectationFailed_417:
  8780. detail::write_response_line(strm, status);
  8781. strm.write("\r\n");
  8782. break;
  8783. default:
  8784. connection_closed = true;
  8785. return write_response(strm, true, req, res);
  8786. }
  8787. }
  8788. // Setup `is_connection_closed` method
  8789. auto sock = strm.socket();
  8790. req.is_connection_closed = [sock]() {
  8791. return !detail::is_socket_alive(sock);
  8792. };
  8793. // Routing
  8794. auto routed = false;
  8795. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8796. routed = routing(req, res, strm);
  8797. #else
  8798. try {
  8799. routed = routing(req, res, strm);
  8800. } catch (std::exception &e) {
  8801. if (exception_handler_) {
  8802. auto ep = std::current_exception();
  8803. exception_handler_(req, res, ep);
  8804. routed = true;
  8805. } else {
  8806. res.status = StatusCode::InternalServerError_500;
  8807. std::string val;
  8808. auto s = e.what();
  8809. for (size_t i = 0; s[i]; i++) {
  8810. switch (s[i]) {
  8811. case '\r': val += "\\r"; break;
  8812. case '\n': val += "\\n"; break;
  8813. default: val += s[i]; break;
  8814. }
  8815. }
  8816. res.set_header("EXCEPTION_WHAT", val);
  8817. }
  8818. } catch (...) {
  8819. if (exception_handler_) {
  8820. auto ep = std::current_exception();
  8821. exception_handler_(req, res, ep);
  8822. routed = true;
  8823. } else {
  8824. res.status = StatusCode::InternalServerError_500;
  8825. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  8826. }
  8827. }
  8828. #endif
  8829. if (routed) {
  8830. if (res.status == -1) {
  8831. res.status = req.ranges.empty() ? StatusCode::OK_200
  8832. : StatusCode::PartialContent_206;
  8833. }
  8834. // Serve file content by using a content provider
  8835. if (!res.file_content_path_.empty()) {
  8836. const auto &path = res.file_content_path_;
  8837. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8838. if (!mm->is_open()) {
  8839. res.body.clear();
  8840. res.content_length_ = 0;
  8841. res.content_provider_ = nullptr;
  8842. res.status = StatusCode::NotFound_404;
  8843. output_error_log(Error::OpenFile, &req);
  8844. return write_response(strm, close_connection, req, res);
  8845. }
  8846. auto content_type = res.file_content_content_type_;
  8847. if (content_type.empty()) {
  8848. content_type = detail::find_content_type(
  8849. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  8850. }
  8851. res.set_content_provider(
  8852. mm->size(), content_type,
  8853. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8854. sink.write(mm->data() + offset, length);
  8855. return true;
  8856. });
  8857. }
  8858. if (detail::range_error(req, res)) {
  8859. res.body.clear();
  8860. res.content_length_ = 0;
  8861. res.content_provider_ = nullptr;
  8862. res.status = StatusCode::RangeNotSatisfiable_416;
  8863. return write_response(strm, close_connection, req, res);
  8864. }
  8865. return write_response_with_content(strm, close_connection, req, res);
  8866. } else {
  8867. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  8868. return write_response(strm, close_connection, req, res);
  8869. }
  8870. }
  8871. inline bool Server::is_valid() const { return true; }
  8872. inline bool Server::process_and_close_socket(socket_t sock) {
  8873. std::string remote_addr;
  8874. int remote_port = 0;
  8875. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8876. std::string local_addr;
  8877. int local_port = 0;
  8878. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8879. auto ret = detail::process_server_socket(
  8880. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8881. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8882. write_timeout_usec_,
  8883. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8884. return process_request(strm, remote_addr, remote_port, local_addr,
  8885. local_port, close_connection, connection_closed,
  8886. nullptr);
  8887. });
  8888. detail::shutdown_socket(sock);
  8889. detail::close_socket(sock);
  8890. return ret;
  8891. }
  8892. inline void Server::output_log(const Request &req, const Response &res) const {
  8893. if (logger_) {
  8894. std::lock_guard<std::mutex> guard(logger_mutex_);
  8895. logger_(req, res);
  8896. }
  8897. }
  8898. inline void Server::output_pre_compression_log(const Request &req,
  8899. const Response &res) const {
  8900. if (pre_compression_logger_) {
  8901. std::lock_guard<std::mutex> guard(logger_mutex_);
  8902. pre_compression_logger_(req, res);
  8903. }
  8904. }
  8905. inline void Server::output_error_log(const Error &err,
  8906. const Request *req) const {
  8907. if (error_logger_) {
  8908. std::lock_guard<std::mutex> guard(logger_mutex_);
  8909. error_logger_(err, req);
  8910. }
  8911. }
  8912. /*
  8913. * Group 5: ClientImpl and Client (Universal) implementation
  8914. */
  8915. // HTTP client implementation
  8916. inline ClientImpl::ClientImpl(const std::string &host)
  8917. : ClientImpl(host, 80, std::string(), std::string()) {}
  8918. inline ClientImpl::ClientImpl(const std::string &host, int port)
  8919. : ClientImpl(host, port, std::string(), std::string()) {}
  8920. inline ClientImpl::ClientImpl(const std::string &host, int port,
  8921. const std::string &client_cert_path,
  8922. const std::string &client_key_path)
  8923. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  8924. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  8925. inline ClientImpl::~ClientImpl() {
  8926. // Wait until all the requests in flight are handled.
  8927. size_t retry_count = 10;
  8928. while (retry_count-- > 0) {
  8929. {
  8930. std::lock_guard<std::mutex> guard(socket_mutex_);
  8931. if (socket_requests_in_flight_ == 0) { break; }
  8932. }
  8933. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  8934. }
  8935. std::lock_guard<std::mutex> guard(socket_mutex_);
  8936. shutdown_socket(socket_);
  8937. close_socket(socket_);
  8938. }
  8939. inline bool ClientImpl::is_valid() const { return true; }
  8940. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  8941. client_cert_path_ = rhs.client_cert_path_;
  8942. client_key_path_ = rhs.client_key_path_;
  8943. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  8944. read_timeout_sec_ = rhs.read_timeout_sec_;
  8945. read_timeout_usec_ = rhs.read_timeout_usec_;
  8946. write_timeout_sec_ = rhs.write_timeout_sec_;
  8947. write_timeout_usec_ = rhs.write_timeout_usec_;
  8948. max_timeout_msec_ = rhs.max_timeout_msec_;
  8949. basic_auth_username_ = rhs.basic_auth_username_;
  8950. basic_auth_password_ = rhs.basic_auth_password_;
  8951. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  8952. keep_alive_ = rhs.keep_alive_;
  8953. follow_location_ = rhs.follow_location_;
  8954. path_encode_ = rhs.path_encode_;
  8955. address_family_ = rhs.address_family_;
  8956. tcp_nodelay_ = rhs.tcp_nodelay_;
  8957. ipv6_v6only_ = rhs.ipv6_v6only_;
  8958. socket_options_ = rhs.socket_options_;
  8959. compress_ = rhs.compress_;
  8960. decompress_ = rhs.decompress_;
  8961. payload_max_length_ = rhs.payload_max_length_;
  8962. has_payload_max_length_ = rhs.has_payload_max_length_;
  8963. interface_ = rhs.interface_;
  8964. proxy_host_ = rhs.proxy_host_;
  8965. proxy_port_ = rhs.proxy_port_;
  8966. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  8967. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  8968. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  8969. logger_ = rhs.logger_;
  8970. error_logger_ = rhs.error_logger_;
  8971. #ifdef CPPHTTPLIB_SSL_ENABLED
  8972. digest_auth_username_ = rhs.digest_auth_username_;
  8973. digest_auth_password_ = rhs.digest_auth_password_;
  8974. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  8975. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  8976. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  8977. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  8978. server_certificate_verification_ = rhs.server_certificate_verification_;
  8979. server_hostname_verification_ = rhs.server_hostname_verification_;
  8980. #endif
  8981. }
  8982. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  8983. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8984. return detail::create_client_socket(
  8985. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  8986. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  8987. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  8988. write_timeout_sec_, write_timeout_usec_, interface_, error);
  8989. }
  8990. // Check is custom IP specified for host_
  8991. std::string ip;
  8992. auto it = addr_map_.find(host_);
  8993. if (it != addr_map_.end()) { ip = it->second; }
  8994. return detail::create_client_socket(
  8995. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  8996. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  8997. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8998. write_timeout_usec_, interface_, error);
  8999. }
  9000. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  9001. Error &error) {
  9002. auto sock = create_client_socket(error);
  9003. if (sock == INVALID_SOCKET) { return false; }
  9004. socket.sock = sock;
  9005. return true;
  9006. }
  9007. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  9008. return create_and_connect_socket(socket, error);
  9009. }
  9010. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  9011. bool /*shutdown_gracefully*/) {
  9012. // If there are any requests in flight from threads other than us, then it's
  9013. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  9014. assert(socket_requests_in_flight_ == 0 ||
  9015. socket_requests_are_from_thread_ == std::this_thread::get_id());
  9016. }
  9017. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  9018. if (socket.sock == INVALID_SOCKET) { return; }
  9019. detail::shutdown_socket(socket.sock);
  9020. }
  9021. inline void ClientImpl::close_socket(Socket &socket) {
  9022. // If there are requests in flight in another thread, usually closing
  9023. // the socket will be fine and they will simply receive an error when
  9024. // using the closed socket, but it is still a bug since rarely the OS
  9025. // may reassign the socket id to be used for a new socket, and then
  9026. // suddenly they will be operating on a live socket that is different
  9027. // than the one they intended!
  9028. assert(socket_requests_in_flight_ == 0 ||
  9029. socket_requests_are_from_thread_ == std::this_thread::get_id());
  9030. // It is also a bug if this happens while SSL is still active
  9031. #ifdef CPPHTTPLIB_SSL_ENABLED
  9032. assert(socket.ssl == nullptr);
  9033. #endif
  9034. if (socket.sock == INVALID_SOCKET) { return; }
  9035. detail::close_socket(socket.sock);
  9036. socket.sock = INVALID_SOCKET;
  9037. }
  9038. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  9039. Response &res,
  9040. bool skip_100_continue) const {
  9041. std::array<char, 2048> buf{};
  9042. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  9043. if (!line_reader.getline()) { return false; }
  9044. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  9045. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  9046. #else
  9047. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  9048. #endif
  9049. std::cmatch m;
  9050. if (!std::regex_match(line_reader.ptr(), m, re)) {
  9051. return req.method == "CONNECT";
  9052. }
  9053. res.version = std::string(m[1]);
  9054. res.status = std::stoi(std::string(m[2]));
  9055. res.reason = std::string(m[3]);
  9056. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  9057. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  9058. if (!line_reader.getline()) { return false; } // CRLF
  9059. if (!line_reader.getline()) { return false; } // next response line
  9060. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  9061. res.version = std::string(m[1]);
  9062. res.status = std::stoi(std::string(m[2]));
  9063. res.reason = std::string(m[3]);
  9064. }
  9065. return true;
  9066. }
  9067. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  9068. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  9069. auto ret = send_(req, res, error);
  9070. if (error == Error::SSLPeerCouldBeClosed_) {
  9071. assert(!ret);
  9072. ret = send_(req, res, error);
  9073. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  9074. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  9075. }
  9076. return ret;
  9077. }
  9078. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  9079. {
  9080. std::lock_guard<std::mutex> guard(socket_mutex_);
  9081. // Set this to false immediately - if it ever gets set to true by the end
  9082. // of the request, we know another thread instructed us to close the
  9083. // socket.
  9084. socket_should_be_closed_when_request_is_done_ = false;
  9085. auto is_alive = false;
  9086. if (socket_.is_open()) {
  9087. is_alive = detail::is_socket_alive(socket_.sock);
  9088. #ifdef CPPHTTPLIB_SSL_ENABLED
  9089. if (is_alive && is_ssl()) {
  9090. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  9091. is_alive = false;
  9092. }
  9093. }
  9094. #endif
  9095. if (!is_alive) {
  9096. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  9097. // seems like the other side has already closed the connection Also,
  9098. // there cannot be any requests in flight from other threads since we
  9099. // locked request_mutex_, so safe to close everything immediately
  9100. const bool shutdown_gracefully = false;
  9101. shutdown_ssl(socket_, shutdown_gracefully);
  9102. shutdown_socket(socket_);
  9103. close_socket(socket_);
  9104. }
  9105. }
  9106. if (!is_alive) {
  9107. if (!ensure_socket_connection(socket_, error)) {
  9108. output_error_log(error, &req);
  9109. return false;
  9110. }
  9111. #ifdef CPPHTTPLIB_SSL_ENABLED
  9112. // TODO: refactoring
  9113. if (is_ssl()) {
  9114. auto &scli = static_cast<SSLClient &>(*this);
  9115. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9116. auto success = false;
  9117. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  9118. error)) {
  9119. if (!success) { output_error_log(error, &req); }
  9120. return success;
  9121. }
  9122. }
  9123. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9124. if (!scli.initialize_ssl(socket_, error)) {
  9125. output_error_log(error, &req);
  9126. return false;
  9127. }
  9128. }
  9129. }
  9130. #endif
  9131. }
  9132. // Mark the current socket as being in use so that it cannot be closed by
  9133. // anyone else while this request is ongoing, even though we will be
  9134. // releasing the mutex.
  9135. if (socket_requests_in_flight_ > 1) {
  9136. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  9137. }
  9138. socket_requests_in_flight_ += 1;
  9139. socket_requests_are_from_thread_ = std::this_thread::get_id();
  9140. }
  9141. for (const auto &header : default_headers_) {
  9142. if (req.headers.find(header.first) == req.headers.end()) {
  9143. req.headers.insert(header);
  9144. }
  9145. }
  9146. auto ret = false;
  9147. auto close_connection = !keep_alive_;
  9148. auto se = detail::scope_exit([&]() {
  9149. // Briefly lock mutex in order to mark that a request is no longer ongoing
  9150. std::lock_guard<std::mutex> guard(socket_mutex_);
  9151. socket_requests_in_flight_ -= 1;
  9152. if (socket_requests_in_flight_ <= 0) {
  9153. assert(socket_requests_in_flight_ == 0);
  9154. socket_requests_are_from_thread_ = std::thread::id();
  9155. }
  9156. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  9157. !ret) {
  9158. shutdown_ssl(socket_, true);
  9159. shutdown_socket(socket_);
  9160. close_socket(socket_);
  9161. }
  9162. });
  9163. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  9164. return handle_request(strm, req, res, close_connection, error);
  9165. });
  9166. if (!ret) {
  9167. if (error == Error::Success) {
  9168. error = Error::Unknown;
  9169. output_error_log(error, &req);
  9170. }
  9171. }
  9172. return ret;
  9173. }
  9174. inline Result ClientImpl::send(const Request &req) {
  9175. auto req2 = req;
  9176. return send_(std::move(req2));
  9177. }
  9178. inline Result ClientImpl::send_(Request &&req) {
  9179. auto res = detail::make_unique<Response>();
  9180. auto error = Error::Success;
  9181. auto ret = send(req, *res, error);
  9182. #ifdef CPPHTTPLIB_SSL_ENABLED
  9183. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  9184. last_ssl_error_, last_backend_error_};
  9185. #else
  9186. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  9187. #endif
  9188. }
  9189. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  9190. const std::string &ct) {
  9191. (void)for_stream;
  9192. for (const auto &header : default_headers_) {
  9193. if (!r.has_header(header.first)) { r.headers.insert(header); }
  9194. }
  9195. if (!r.has_header("Host")) {
  9196. if (address_family_ == AF_UNIX) {
  9197. r.headers.emplace("Host", "localhost");
  9198. } else {
  9199. r.headers.emplace(
  9200. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  9201. }
  9202. }
  9203. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  9204. if (!r.content_receiver) {
  9205. if (!r.has_header("Accept-Encoding")) {
  9206. std::string accept_encoding;
  9207. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9208. accept_encoding = "br";
  9209. #endif
  9210. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9211. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  9212. accept_encoding += "gzip, deflate";
  9213. #endif
  9214. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9215. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  9216. accept_encoding += "zstd";
  9217. #endif
  9218. r.set_header("Accept-Encoding", accept_encoding);
  9219. }
  9220. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  9221. if (!r.has_header("User-Agent")) {
  9222. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  9223. r.set_header("User-Agent", agent);
  9224. }
  9225. #endif
  9226. }
  9227. if (!r.body.empty()) {
  9228. if (!ct.empty() && !r.has_header("Content-Type")) {
  9229. r.headers.emplace("Content-Type", ct);
  9230. }
  9231. if (!r.has_header("Content-Length")) {
  9232. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  9233. }
  9234. }
  9235. }
  9236. inline ClientImpl::StreamHandle
  9237. ClientImpl::open_stream(const std::string &method, const std::string &path,
  9238. const Params &params, const Headers &headers,
  9239. const std::string &body,
  9240. const std::string &content_type) {
  9241. StreamHandle handle;
  9242. handle.response = detail::make_unique<Response>();
  9243. handle.error = Error::Success;
  9244. auto query_path = params.empty() ? path : append_query_params(path, params);
  9245. handle.connection_ = detail::make_unique<ClientConnection>();
  9246. {
  9247. std::lock_guard<std::mutex> guard(socket_mutex_);
  9248. auto is_alive = false;
  9249. if (socket_.is_open()) {
  9250. is_alive = detail::is_socket_alive(socket_.sock);
  9251. #ifdef CPPHTTPLIB_SSL_ENABLED
  9252. if (is_alive && is_ssl()) {
  9253. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  9254. is_alive = false;
  9255. }
  9256. }
  9257. #endif
  9258. if (!is_alive) {
  9259. shutdown_ssl(socket_, false);
  9260. shutdown_socket(socket_);
  9261. close_socket(socket_);
  9262. }
  9263. }
  9264. if (!is_alive) {
  9265. if (!ensure_socket_connection(socket_, handle.error)) {
  9266. handle.response.reset();
  9267. return handle;
  9268. }
  9269. #ifdef CPPHTTPLIB_SSL_ENABLED
  9270. if (is_ssl()) {
  9271. auto &scli = static_cast<SSLClient &>(*this);
  9272. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9273. if (!scli.initialize_ssl(socket_, handle.error)) {
  9274. handle.response.reset();
  9275. return handle;
  9276. }
  9277. }
  9278. }
  9279. #endif
  9280. }
  9281. transfer_socket_ownership_to_handle(handle);
  9282. }
  9283. #ifdef CPPHTTPLIB_SSL_ENABLED
  9284. if (is_ssl() && handle.connection_->session) {
  9285. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  9286. handle.connection_->sock, handle.connection_->session,
  9287. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9288. write_timeout_usec_);
  9289. } else {
  9290. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  9291. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  9292. write_timeout_sec_, write_timeout_usec_);
  9293. }
  9294. #else
  9295. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  9296. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  9297. write_timeout_sec_, write_timeout_usec_);
  9298. #endif
  9299. handle.stream_ = handle.socket_stream_.get();
  9300. Request req;
  9301. req.method = method;
  9302. req.path = query_path;
  9303. req.headers = headers;
  9304. req.body = body;
  9305. prepare_default_headers(req, true, content_type);
  9306. auto &strm = *handle.stream_;
  9307. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  9308. handle.error = Error::Write;
  9309. handle.response.reset();
  9310. return handle;
  9311. }
  9312. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  9313. handle.error)) {
  9314. handle.response.reset();
  9315. return handle;
  9316. }
  9317. if (!body.empty()) {
  9318. if (strm.write(body.data(), body.size()) < 0) {
  9319. handle.error = Error::Write;
  9320. handle.response.reset();
  9321. return handle;
  9322. }
  9323. }
  9324. if (!read_response_line(strm, req, *handle.response) ||
  9325. !detail::read_headers(strm, handle.response->headers)) {
  9326. handle.error = Error::Read;
  9327. handle.response.reset();
  9328. return handle;
  9329. }
  9330. handle.body_reader_.stream = handle.stream_;
  9331. handle.body_reader_.payload_max_length = payload_max_length_;
  9332. auto content_length_str = handle.response->get_header_value("Content-Length");
  9333. if (!content_length_str.empty()) {
  9334. handle.body_reader_.has_content_length = true;
  9335. handle.body_reader_.content_length =
  9336. static_cast<size_t>(std::stoull(content_length_str));
  9337. }
  9338. auto transfer_encoding =
  9339. handle.response->get_header_value("Transfer-Encoding");
  9340. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  9341. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  9342. if (!content_encoding.empty()) {
  9343. handle.decompressor_ = detail::create_decompressor(content_encoding);
  9344. }
  9345. return handle;
  9346. }
  9347. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  9348. if (!is_valid() || !response) { return -1; }
  9349. if (decompressor_) { return read_with_decompression(buf, len); }
  9350. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  9351. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  9352. trailers_parsed_ = true;
  9353. if (body_reader_.chunked_decoder) {
  9354. if (!body_reader_.chunked_decoder->parse_trailers_into(
  9355. response->trailers, response->headers)) {
  9356. return n;
  9357. }
  9358. } else {
  9359. detail::ChunkedDecoder dec(*stream_);
  9360. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  9361. return n;
  9362. }
  9363. }
  9364. }
  9365. return n;
  9366. }
  9367. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  9368. size_t len) {
  9369. if (decompress_offset_ < decompress_buffer_.size()) {
  9370. auto available = decompress_buffer_.size() - decompress_offset_;
  9371. auto to_copy = (std::min)(len, available);
  9372. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  9373. decompress_offset_ += to_copy;
  9374. decompressed_bytes_read_ += to_copy;
  9375. return static_cast<ssize_t>(to_copy);
  9376. }
  9377. decompress_buffer_.clear();
  9378. decompress_offset_ = 0;
  9379. constexpr size_t kDecompressionBufferSize = 8192;
  9380. char compressed_buf[kDecompressionBufferSize];
  9381. while (true) {
  9382. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  9383. sizeof(compressed_buf));
  9384. if (n <= 0) { return n; }
  9385. bool decompress_ok = decompressor_->decompress(
  9386. compressed_buf, static_cast<size_t>(n),
  9387. [this](const char *data, size_t data_len) {
  9388. decompress_buffer_.append(data, data_len);
  9389. auto limit = body_reader_.payload_max_length;
  9390. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  9391. return false;
  9392. }
  9393. return true;
  9394. });
  9395. if (!decompress_ok) {
  9396. body_reader_.last_error = Error::Read;
  9397. return -1;
  9398. }
  9399. if (!decompress_buffer_.empty()) { break; }
  9400. }
  9401. auto to_copy = (std::min)(len, decompress_buffer_.size());
  9402. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  9403. decompress_offset_ = to_copy;
  9404. decompressed_bytes_read_ += to_copy;
  9405. return static_cast<ssize_t>(to_copy);
  9406. }
  9407. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  9408. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  9409. return;
  9410. }
  9411. trailers_parsed_ = true;
  9412. const auto bufsiz = 128;
  9413. char line_buf[bufsiz];
  9414. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  9415. if (!line_reader.getline()) { return; }
  9416. if (!detail::parse_trailers(line_reader, response->trailers,
  9417. response->headers)) {
  9418. return;
  9419. }
  9420. }
  9421. namespace detail {
  9422. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  9423. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  9424. size_t &out_chunk_offset,
  9425. size_t &out_chunk_total) {
  9426. if (finished) { return 0; }
  9427. if (chunk_remaining == 0) {
  9428. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9429. if (!lr.getline()) { return -1; }
  9430. char *endptr = nullptr;
  9431. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  9432. if (endptr == lr.ptr()) { return -1; }
  9433. if (chunk_len == ULONG_MAX) { return -1; }
  9434. if (chunk_len == 0) {
  9435. chunk_remaining = 0;
  9436. finished = true;
  9437. out_chunk_offset = 0;
  9438. out_chunk_total = 0;
  9439. return 0;
  9440. }
  9441. chunk_remaining = static_cast<size_t>(chunk_len);
  9442. last_chunk_total = chunk_remaining;
  9443. last_chunk_offset = 0;
  9444. }
  9445. auto to_read = (std::min)(chunk_remaining, len);
  9446. auto n = strm.read(buf, to_read);
  9447. if (n <= 0) { return -1; }
  9448. auto offset_before = last_chunk_offset;
  9449. last_chunk_offset += static_cast<size_t>(n);
  9450. chunk_remaining -= static_cast<size_t>(n);
  9451. out_chunk_offset = offset_before;
  9452. out_chunk_total = last_chunk_total;
  9453. if (chunk_remaining == 0) {
  9454. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9455. if (!lr.getline()) { return -1; }
  9456. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  9457. }
  9458. return n;
  9459. }
  9460. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  9461. const Headers &src_headers) {
  9462. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9463. if (!lr.getline()) { return false; }
  9464. return parse_trailers(lr, dest, src_headers);
  9465. }
  9466. } // namespace detail
  9467. inline void
  9468. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  9469. handle.connection_->sock = socket_.sock;
  9470. #ifdef CPPHTTPLIB_SSL_ENABLED
  9471. handle.connection_->session = socket_.ssl;
  9472. socket_.ssl = nullptr;
  9473. #endif
  9474. socket_.sock = INVALID_SOCKET;
  9475. }
  9476. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  9477. Response &res, bool close_connection,
  9478. Error &error) {
  9479. if (req.path.empty()) {
  9480. error = Error::Connection;
  9481. output_error_log(error, &req);
  9482. return false;
  9483. }
  9484. auto req_save = req;
  9485. bool ret;
  9486. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  9487. auto req2 = req;
  9488. req2.path = "http://" +
  9489. detail::make_host_and_port_string(host_, port_, false) +
  9490. req.path;
  9491. ret = process_request(strm, req2, res, close_connection, error);
  9492. req = std::move(req2);
  9493. req.path = req_save.path;
  9494. } else {
  9495. ret = process_request(strm, req, res, close_connection, error);
  9496. }
  9497. if (!ret) { return false; }
  9498. if (res.get_header_value("Connection") == "close" ||
  9499. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  9500. // TODO this requires a not-entirely-obvious chain of calls to be correct
  9501. // for this to be safe.
  9502. // This is safe to call because handle_request is only called by send_
  9503. // which locks the request mutex during the process. It would be a bug
  9504. // to call it from a different thread since it's a thread-safety issue
  9505. // to do these things to the socket if another thread is using the socket.
  9506. std::lock_guard<std::mutex> guard(socket_mutex_);
  9507. shutdown_ssl(socket_, true);
  9508. shutdown_socket(socket_);
  9509. close_socket(socket_);
  9510. }
  9511. if (300 < res.status && res.status < 400 && follow_location_) {
  9512. req = std::move(req_save);
  9513. ret = redirect(req, res, error);
  9514. }
  9515. #ifdef CPPHTTPLIB_SSL_ENABLED
  9516. if ((res.status == StatusCode::Unauthorized_401 ||
  9517. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  9518. req.authorization_count_ < 5) {
  9519. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  9520. const auto &username =
  9521. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  9522. const auto &password =
  9523. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  9524. if (!username.empty() && !password.empty()) {
  9525. std::map<std::string, std::string> auth;
  9526. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  9527. Request new_req = req;
  9528. new_req.authorization_count_ += 1;
  9529. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  9530. : "Authorization");
  9531. new_req.headers.insert(detail::make_digest_authentication_header(
  9532. req, auth, new_req.authorization_count_, detail::random_string(10),
  9533. username, password, is_proxy));
  9534. Response new_res;
  9535. ret = send(new_req, new_res, error);
  9536. if (ret) { res = std::move(new_res); }
  9537. }
  9538. }
  9539. }
  9540. #endif
  9541. return ret;
  9542. }
  9543. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  9544. if (req.redirect_count_ == 0) {
  9545. error = Error::ExceedRedirectCount;
  9546. output_error_log(error, &req);
  9547. return false;
  9548. }
  9549. auto location = res.get_header_value("location");
  9550. if (location.empty()) { return false; }
  9551. thread_local const std::regex re(
  9552. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  9553. std::smatch m;
  9554. if (!std::regex_match(location, m, re)) { return false; }
  9555. auto scheme = is_ssl() ? "https" : "http";
  9556. auto next_scheme = m[1].str();
  9557. auto next_host = m[2].str();
  9558. if (next_host.empty()) { next_host = m[3].str(); }
  9559. auto port_str = m[4].str();
  9560. auto next_path = m[5].str();
  9561. auto next_query = m[6].str();
  9562. auto next_port = port_;
  9563. if (!port_str.empty()) {
  9564. next_port = std::stoi(port_str);
  9565. } else if (!next_scheme.empty()) {
  9566. next_port = next_scheme == "https" ? 443 : 80;
  9567. }
  9568. if (next_scheme.empty()) { next_scheme = scheme; }
  9569. if (next_host.empty()) { next_host = host_; }
  9570. if (next_path.empty()) { next_path = "/"; }
  9571. auto path = decode_query_component(next_path, true) + next_query;
  9572. // Same host redirect - use current client
  9573. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  9574. return detail::redirect(*this, req, res, path, location, error);
  9575. }
  9576. // Cross-host/scheme redirect - create new client with robust setup
  9577. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  9578. path, location, error);
  9579. }
  9580. // New method for robust redirect client creation
  9581. inline bool ClientImpl::create_redirect_client(
  9582. const std::string &scheme, const std::string &host, int port, Request &req,
  9583. Response &res, const std::string &path, const std::string &location,
  9584. Error &error) {
  9585. // Determine if we need SSL
  9586. auto need_ssl = (scheme == "https");
  9587. // Clean up request headers that are host/client specific
  9588. // Remove headers that should not be carried over to new host
  9589. auto headers_to_remove =
  9590. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  9591. for (const auto &header_name : headers_to_remove) {
  9592. auto it = req.headers.find(header_name);
  9593. while (it != req.headers.end()) {
  9594. it = req.headers.erase(it);
  9595. it = req.headers.find(header_name);
  9596. }
  9597. }
  9598. // Create appropriate client type and handle redirect
  9599. if (need_ssl) {
  9600. #ifdef CPPHTTPLIB_SSL_ENABLED
  9601. // Create SSL client for HTTPS redirect
  9602. SSLClient redirect_client(host, port);
  9603. // Setup basic client configuration first
  9604. setup_redirect_client(redirect_client);
  9605. // SSL-specific configuration for proxy environments
  9606. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9607. // Critical: Disable SSL verification for proxy environments
  9608. redirect_client.enable_server_certificate_verification(false);
  9609. redirect_client.enable_server_hostname_verification(false);
  9610. } else {
  9611. // For direct SSL connections, copy SSL verification settings
  9612. redirect_client.enable_server_certificate_verification(
  9613. server_certificate_verification_);
  9614. redirect_client.enable_server_hostname_verification(
  9615. server_hostname_verification_);
  9616. }
  9617. // Transfer CA certificate to redirect client
  9618. if (!ca_cert_pem_.empty()) {
  9619. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  9620. ca_cert_pem_.size());
  9621. }
  9622. if (!ca_cert_file_path_.empty()) {
  9623. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  9624. }
  9625. // Client certificates are set through constructor for SSLClient
  9626. // NOTE: SSLClient constructor already takes client_cert_path and
  9627. // client_key_path so we need to create it properly if client certs are
  9628. // needed
  9629. // Execute the redirect
  9630. return detail::redirect(redirect_client, req, res, path, location, error);
  9631. #else
  9632. // SSL not supported - set appropriate error
  9633. error = Error::SSLConnection;
  9634. output_error_log(error, &req);
  9635. return false;
  9636. #endif
  9637. } else {
  9638. // HTTP redirect
  9639. ClientImpl redirect_client(host, port);
  9640. // Setup client with robust configuration
  9641. setup_redirect_client(redirect_client);
  9642. // Execute the redirect
  9643. return detail::redirect(redirect_client, req, res, path, location, error);
  9644. }
  9645. }
  9646. // New method for robust client setup (based on basic_manual_redirect.cpp
  9647. // logic)
  9648. template <typename ClientType>
  9649. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  9650. // Copy basic settings first
  9651. client.set_connection_timeout(connection_timeout_sec_);
  9652. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  9653. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  9654. client.set_keep_alive(keep_alive_);
  9655. client.set_follow_location(
  9656. true); // Enable redirects to handle multi-step redirects
  9657. client.set_path_encode(path_encode_);
  9658. client.set_compress(compress_);
  9659. client.set_decompress(decompress_);
  9660. // Copy authentication settings BEFORE proxy setup
  9661. if (!basic_auth_username_.empty()) {
  9662. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  9663. }
  9664. if (!bearer_token_auth_token_.empty()) {
  9665. client.set_bearer_token_auth(bearer_token_auth_token_);
  9666. }
  9667. #ifdef CPPHTTPLIB_SSL_ENABLED
  9668. if (!digest_auth_username_.empty()) {
  9669. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  9670. }
  9671. #endif
  9672. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  9673. // before proxy auth)
  9674. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9675. // First set proxy host and port
  9676. client.set_proxy(proxy_host_, proxy_port_);
  9677. // Then set proxy authentication (order matters!)
  9678. if (!proxy_basic_auth_username_.empty()) {
  9679. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  9680. proxy_basic_auth_password_);
  9681. }
  9682. if (!proxy_bearer_token_auth_token_.empty()) {
  9683. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  9684. }
  9685. #ifdef CPPHTTPLIB_SSL_ENABLED
  9686. if (!proxy_digest_auth_username_.empty()) {
  9687. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  9688. proxy_digest_auth_password_);
  9689. }
  9690. #endif
  9691. }
  9692. // Copy network and socket settings
  9693. client.set_address_family(address_family_);
  9694. client.set_tcp_nodelay(tcp_nodelay_);
  9695. client.set_ipv6_v6only(ipv6_v6only_);
  9696. if (socket_options_) { client.set_socket_options(socket_options_); }
  9697. if (!interface_.empty()) { client.set_interface(interface_); }
  9698. // Copy logging and headers
  9699. if (logger_) { client.set_logger(logger_); }
  9700. if (error_logger_) { client.set_error_logger(error_logger_); }
  9701. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  9702. // Each new client should generate its own headers based on its target host
  9703. }
  9704. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  9705. const Request &req,
  9706. Error &error) const {
  9707. auto is_shutting_down = []() { return false; };
  9708. if (req.is_chunked_content_provider_) {
  9709. // TODO: Brotli support
  9710. std::unique_ptr<detail::compressor> compressor;
  9711. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9712. if (compress_) {
  9713. compressor = detail::make_unique<detail::gzip_compressor>();
  9714. } else
  9715. #endif
  9716. {
  9717. compressor = detail::make_unique<detail::nocompressor>();
  9718. }
  9719. return detail::write_content_chunked(strm, req.content_provider_,
  9720. is_shutting_down, *compressor, error);
  9721. } else {
  9722. return detail::write_content_with_progress(
  9723. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  9724. req.upload_progress, error);
  9725. }
  9726. }
  9727. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  9728. bool close_connection, Error &error,
  9729. bool skip_body) {
  9730. // Prepare additional headers
  9731. if (close_connection) {
  9732. if (!req.has_header("Connection")) {
  9733. req.set_header("Connection", "close");
  9734. }
  9735. }
  9736. std::string ct_for_defaults;
  9737. if (!req.has_header("Content-Type") && !req.body.empty()) {
  9738. ct_for_defaults = "text/plain";
  9739. }
  9740. prepare_default_headers(req, false, ct_for_defaults);
  9741. if (req.body.empty()) {
  9742. if (req.content_provider_) {
  9743. if (!req.is_chunked_content_provider_) {
  9744. if (!req.has_header("Content-Length")) {
  9745. auto length = std::to_string(req.content_length_);
  9746. req.set_header("Content-Length", length);
  9747. }
  9748. }
  9749. } else {
  9750. if (req.method == "POST" || req.method == "PUT" ||
  9751. req.method == "PATCH") {
  9752. req.set_header("Content-Length", "0");
  9753. }
  9754. }
  9755. }
  9756. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  9757. if (!req.has_header("Authorization")) {
  9758. req.headers.insert(make_basic_authentication_header(
  9759. basic_auth_username_, basic_auth_password_, false));
  9760. }
  9761. }
  9762. if (!proxy_basic_auth_username_.empty() &&
  9763. !proxy_basic_auth_password_.empty()) {
  9764. if (!req.has_header("Proxy-Authorization")) {
  9765. req.headers.insert(make_basic_authentication_header(
  9766. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  9767. }
  9768. }
  9769. if (!bearer_token_auth_token_.empty()) {
  9770. if (!req.has_header("Authorization")) {
  9771. req.headers.insert(make_bearer_token_authentication_header(
  9772. bearer_token_auth_token_, false));
  9773. }
  9774. }
  9775. if (!proxy_bearer_token_auth_token_.empty()) {
  9776. if (!req.has_header("Proxy-Authorization")) {
  9777. req.headers.insert(make_bearer_token_authentication_header(
  9778. proxy_bearer_token_auth_token_, true));
  9779. }
  9780. }
  9781. // Request line and headers
  9782. {
  9783. detail::BufferStream bstrm;
  9784. // Extract path and query from req.path
  9785. std::string path_part, query_part;
  9786. auto query_pos = req.path.find('?');
  9787. if (query_pos != std::string::npos) {
  9788. path_part = req.path.substr(0, query_pos);
  9789. query_part = req.path.substr(query_pos + 1);
  9790. } else {
  9791. path_part = req.path;
  9792. query_part = "";
  9793. }
  9794. // Encode path part. If the original `req.path` already contained a
  9795. // query component, preserve its raw query string (including parameter
  9796. // order) instead of reparsing and reassembling it which may reorder
  9797. // parameters due to container ordering (e.g. `Params` uses
  9798. // `std::multimap`). When there is no query in `req.path`, fall back to
  9799. // building a query from `req.params` so existing callers that pass
  9800. // `Params` continue to work.
  9801. auto path_with_query =
  9802. path_encode_ ? detail::encode_path(path_part) : path_part;
  9803. if (!query_part.empty()) {
  9804. // Normalize the query string (decode then re-encode) while preserving
  9805. // the original parameter order.
  9806. auto normalized = detail::normalize_query_string(query_part);
  9807. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  9808. // Still populate req.params for handlers/users who read them.
  9809. detail::parse_query_text(query_part, req.params);
  9810. } else {
  9811. // No query in path; parse any query_part (empty) and append params
  9812. // from `req.params` when present (preserves prior behavior for
  9813. // callers who provide Params separately).
  9814. detail::parse_query_text(query_part, req.params);
  9815. if (!req.params.empty()) {
  9816. path_with_query = append_query_params(path_with_query, req.params);
  9817. }
  9818. }
  9819. // Write request line and headers
  9820. detail::write_request_line(bstrm, req.method, path_with_query);
  9821. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  9822. error)) {
  9823. output_error_log(error, &req);
  9824. return false;
  9825. }
  9826. // Flush buffer
  9827. auto &data = bstrm.get_buffer();
  9828. if (!detail::write_data(strm, data.data(), data.size())) {
  9829. error = Error::Write;
  9830. output_error_log(error, &req);
  9831. return false;
  9832. }
  9833. }
  9834. // After sending request line and headers, wait briefly for an early server
  9835. // response (e.g. 4xx) and avoid sending a potentially large request body
  9836. // unnecessarily. This workaround is only enabled on Windows because Unix
  9837. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  9838. // buffering can accept large writes even when the peer already responded.
  9839. // Check the stream first (which covers SSL via `is_readable()`), then
  9840. // fall back to select on the socket. Only perform the wait for very large
  9841. // request bodies to avoid interfering with normal small requests and
  9842. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  9843. // response. Skip this check when using Expect: 100-continue, as the protocol
  9844. // handles early responses properly.
  9845. #if defined(_WIN32)
  9846. if (!skip_body &&
  9847. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  9848. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  9849. auto start = std::chrono::high_resolution_clock::now();
  9850. for (;;) {
  9851. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  9852. // from SSL internals. If the underlying socket is readable, assume an
  9853. // early response may be present.
  9854. auto sock = strm.socket();
  9855. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  9856. return false;
  9857. }
  9858. // Fallback to stream-level check for non-socket streams or when the
  9859. // socket isn't reporting readable. Avoid using `is_readable()` for
  9860. // SSL, since `SSL_pending()` may report buffered records that do not
  9861. // indicate a complete application-level response yet.
  9862. if (!is_ssl() && strm.is_readable()) { return false; }
  9863. auto now = std::chrono::high_resolution_clock::now();
  9864. auto elapsed =
  9865. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  9866. .count();
  9867. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  9868. break;
  9869. }
  9870. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  9871. }
  9872. }
  9873. #endif
  9874. // Body
  9875. if (skip_body) { return true; }
  9876. return write_request_body(strm, req, error);
  9877. }
  9878. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  9879. Error &error) {
  9880. if (req.body.empty()) {
  9881. return write_content_with_provider(strm, req, error);
  9882. }
  9883. if (req.upload_progress) {
  9884. auto body_size = req.body.size();
  9885. size_t written = 0;
  9886. auto data = req.body.data();
  9887. while (written < body_size) {
  9888. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  9889. if (!detail::write_data(strm, data + written, to_write)) {
  9890. error = Error::Write;
  9891. output_error_log(error, &req);
  9892. return false;
  9893. }
  9894. written += to_write;
  9895. if (!req.upload_progress(written, body_size)) {
  9896. error = Error::Canceled;
  9897. output_error_log(error, &req);
  9898. return false;
  9899. }
  9900. }
  9901. } else {
  9902. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  9903. error = Error::Write;
  9904. output_error_log(error, &req);
  9905. return false;
  9906. }
  9907. }
  9908. return true;
  9909. }
  9910. inline std::unique_ptr<Response>
  9911. ClientImpl::send_with_content_provider_and_receiver(
  9912. Request &req, const char *body, size_t content_length,
  9913. ContentProvider content_provider,
  9914. ContentProviderWithoutLength content_provider_without_length,
  9915. const std::string &content_type, ContentReceiver content_receiver,
  9916. Error &error) {
  9917. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9918. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9919. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  9920. #endif
  9921. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9922. if (compress_ && !content_provider_without_length) {
  9923. // TODO: Brotli support
  9924. detail::gzip_compressor compressor;
  9925. if (content_provider) {
  9926. auto ok = true;
  9927. size_t offset = 0;
  9928. DataSink data_sink;
  9929. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  9930. if (ok) {
  9931. auto last = offset + data_len == content_length;
  9932. auto ret = compressor.compress(
  9933. data, data_len, last,
  9934. [&](const char *compressed_data, size_t compressed_data_len) {
  9935. req.body.append(compressed_data, compressed_data_len);
  9936. return true;
  9937. });
  9938. if (ret) {
  9939. offset += data_len;
  9940. } else {
  9941. ok = false;
  9942. }
  9943. }
  9944. return ok;
  9945. };
  9946. while (ok && offset < content_length) {
  9947. if (!content_provider(offset, content_length - offset, data_sink)) {
  9948. error = Error::Canceled;
  9949. output_error_log(error, &req);
  9950. return nullptr;
  9951. }
  9952. }
  9953. } else {
  9954. if (!compressor.compress(body, content_length, true,
  9955. [&](const char *data, size_t data_len) {
  9956. req.body.append(data, data_len);
  9957. return true;
  9958. })) {
  9959. error = Error::Compression;
  9960. output_error_log(error, &req);
  9961. return nullptr;
  9962. }
  9963. }
  9964. } else
  9965. #endif
  9966. {
  9967. if (content_provider) {
  9968. req.content_length_ = content_length;
  9969. req.content_provider_ = std::move(content_provider);
  9970. req.is_chunked_content_provider_ = false;
  9971. } else if (content_provider_without_length) {
  9972. req.content_length_ = 0;
  9973. req.content_provider_ = detail::ContentProviderAdapter(
  9974. std::move(content_provider_without_length));
  9975. req.is_chunked_content_provider_ = true;
  9976. req.set_header("Transfer-Encoding", "chunked");
  9977. } else {
  9978. req.body.assign(body, content_length);
  9979. }
  9980. }
  9981. if (content_receiver) {
  9982. req.content_receiver =
  9983. [content_receiver](const char *data, size_t data_length,
  9984. size_t /*offset*/, size_t /*total_length*/) {
  9985. return content_receiver(data, data_length);
  9986. };
  9987. }
  9988. auto res = detail::make_unique<Response>();
  9989. return send(req, *res, error) ? std::move(res) : nullptr;
  9990. }
  9991. inline Result ClientImpl::send_with_content_provider_and_receiver(
  9992. const std::string &method, const std::string &path, const Headers &headers,
  9993. const char *body, size_t content_length, ContentProvider content_provider,
  9994. ContentProviderWithoutLength content_provider_without_length,
  9995. const std::string &content_type, ContentReceiver content_receiver,
  9996. UploadProgress progress) {
  9997. Request req;
  9998. req.method = method;
  9999. req.headers = headers;
  10000. req.path = path;
  10001. req.upload_progress = std::move(progress);
  10002. if (max_timeout_msec_ > 0) {
  10003. req.start_time_ = std::chrono::steady_clock::now();
  10004. }
  10005. auto error = Error::Success;
  10006. auto res = send_with_content_provider_and_receiver(
  10007. req, body, content_length, std::move(content_provider),
  10008. std::move(content_provider_without_length), content_type,
  10009. std::move(content_receiver), error);
  10010. #ifdef CPPHTTPLIB_SSL_ENABLED
  10011. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  10012. last_backend_error_};
  10013. #else
  10014. return Result{std::move(res), error, std::move(req.headers)};
  10015. #endif
  10016. }
  10017. inline void ClientImpl::output_log(const Request &req,
  10018. const Response &res) const {
  10019. if (logger_) {
  10020. std::lock_guard<std::mutex> guard(logger_mutex_);
  10021. logger_(req, res);
  10022. }
  10023. }
  10024. inline void ClientImpl::output_error_log(const Error &err,
  10025. const Request *req) const {
  10026. if (error_logger_) {
  10027. std::lock_guard<std::mutex> guard(logger_mutex_);
  10028. error_logger_(err, req);
  10029. }
  10030. }
  10031. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  10032. Response &res, bool close_connection,
  10033. Error &error) {
  10034. // Auto-add Expect: 100-continue for large bodies
  10035. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  10036. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  10037. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  10038. req.set_header("Expect", "100-continue");
  10039. }
  10040. }
  10041. // Check for Expect: 100-continue
  10042. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  10043. // Send request (skip body if using Expect: 100-continue)
  10044. auto write_request_success =
  10045. write_request(strm, req, close_connection, error, expect_100_continue);
  10046. #ifdef CPPHTTPLIB_SSL_ENABLED
  10047. if (is_ssl() && !expect_100_continue) {
  10048. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  10049. if (!is_proxy_enabled) {
  10050. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10051. error = Error::SSLPeerCouldBeClosed_;
  10052. output_error_log(error, &req);
  10053. return false;
  10054. }
  10055. }
  10056. }
  10057. #endif
  10058. // Handle Expect: 100-continue with timeout
  10059. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  10060. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  10061. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  10062. auto ret = detail::select_read(strm.socket(), sec, usec);
  10063. if (ret <= 0) {
  10064. // Timeout or error: send body anyway (server didn't respond in time)
  10065. if (!write_request_body(strm, req, error)) { return false; }
  10066. expect_100_continue = false; // Switch to normal response handling
  10067. }
  10068. }
  10069. // Receive response and headers
  10070. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  10071. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  10072. !detail::read_headers(strm, res.headers)) {
  10073. if (write_request_success) { error = Error::Read; }
  10074. output_error_log(error, &req);
  10075. return false;
  10076. }
  10077. if (!write_request_success) { return false; }
  10078. // Handle Expect: 100-continue response
  10079. if (expect_100_continue) {
  10080. if (res.status == StatusCode::Continue_100) {
  10081. // Server accepted, send the body
  10082. if (!write_request_body(strm, req, error)) { return false; }
  10083. // Read the actual response
  10084. res.headers.clear();
  10085. res.body.clear();
  10086. if (!read_response_line(strm, req, res) ||
  10087. !detail::read_headers(strm, res.headers)) {
  10088. error = Error::Read;
  10089. output_error_log(error, &req);
  10090. return false;
  10091. }
  10092. }
  10093. // If not 100 Continue, server returned an error; proceed with that response
  10094. }
  10095. // Body
  10096. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  10097. req.method != "CONNECT") {
  10098. auto redirect = 300 < res.status && res.status < 400 &&
  10099. res.status != StatusCode::NotModified_304 &&
  10100. follow_location_;
  10101. if (req.response_handler && !redirect) {
  10102. if (!req.response_handler(res)) {
  10103. error = Error::Canceled;
  10104. output_error_log(error, &req);
  10105. return false;
  10106. }
  10107. }
  10108. auto out =
  10109. req.content_receiver
  10110. ? static_cast<ContentReceiverWithProgress>(
  10111. [&](const char *buf, size_t n, size_t off, size_t len) {
  10112. if (redirect) { return true; }
  10113. auto ret = req.content_receiver(buf, n, off, len);
  10114. if (!ret) {
  10115. error = Error::Canceled;
  10116. output_error_log(error, &req);
  10117. }
  10118. return ret;
  10119. })
  10120. : static_cast<ContentReceiverWithProgress>(
  10121. [&](const char *buf, size_t n, size_t /*off*/,
  10122. size_t /*len*/) {
  10123. assert(res.body.size() + n <= res.body.max_size());
  10124. if (payload_max_length_ > 0 &&
  10125. (res.body.size() >= payload_max_length_ ||
  10126. n > payload_max_length_ - res.body.size())) {
  10127. return false;
  10128. }
  10129. res.body.append(buf, n);
  10130. return true;
  10131. });
  10132. auto progress = [&](size_t current, size_t total) {
  10133. if (!req.download_progress || redirect) { return true; }
  10134. auto ret = req.download_progress(current, total);
  10135. if (!ret) {
  10136. error = Error::Canceled;
  10137. output_error_log(error, &req);
  10138. }
  10139. return ret;
  10140. };
  10141. if (res.has_header("Content-Length")) {
  10142. if (!req.content_receiver) {
  10143. auto len = res.get_header_value_u64("Content-Length");
  10144. if (len > res.body.max_size()) {
  10145. error = Error::Read;
  10146. output_error_log(error, &req);
  10147. return false;
  10148. }
  10149. res.body.reserve(static_cast<size_t>(len));
  10150. }
  10151. }
  10152. if (res.status != StatusCode::NotModified_304) {
  10153. int dummy_status;
  10154. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  10155. ? (std::numeric_limits<size_t>::max)()
  10156. : payload_max_length_;
  10157. if (!detail::read_content(strm, res, max_length, dummy_status,
  10158. std::move(progress), std::move(out),
  10159. decompress_)) {
  10160. if (error != Error::Canceled) { error = Error::Read; }
  10161. output_error_log(error, &req);
  10162. return false;
  10163. }
  10164. }
  10165. }
  10166. // Log
  10167. output_log(req, res);
  10168. return true;
  10169. }
  10170. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  10171. const std::string &boundary, const UploadFormDataItems &items,
  10172. const FormDataProviderItems &provider_items) const {
  10173. size_t cur_item = 0;
  10174. size_t cur_start = 0;
  10175. // cur_item and cur_start are copied to within the std::function and
  10176. // maintain state between successive calls
  10177. return [&, cur_item, cur_start](size_t offset,
  10178. DataSink &sink) mutable -> bool {
  10179. if (!offset && !items.empty()) {
  10180. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  10181. return true;
  10182. } else if (cur_item < provider_items.size()) {
  10183. if (!cur_start) {
  10184. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  10185. provider_items[cur_item], boundary);
  10186. offset += begin.size();
  10187. cur_start = offset;
  10188. sink.os << begin;
  10189. }
  10190. DataSink cur_sink;
  10191. auto has_data = true;
  10192. cur_sink.write = sink.write;
  10193. cur_sink.done = [&]() { has_data = false; };
  10194. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  10195. return false;
  10196. }
  10197. if (!has_data) {
  10198. sink.os << detail::serialize_multipart_formdata_item_end();
  10199. cur_item++;
  10200. cur_start = 0;
  10201. }
  10202. return true;
  10203. } else {
  10204. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  10205. sink.done();
  10206. return true;
  10207. }
  10208. };
  10209. }
  10210. inline bool ClientImpl::process_socket(
  10211. const Socket &socket,
  10212. std::chrono::time_point<std::chrono::steady_clock> start_time,
  10213. std::function<bool(Stream &strm)> callback) {
  10214. return detail::process_client_socket(
  10215. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10216. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  10217. }
  10218. inline bool ClientImpl::is_ssl() const { return false; }
  10219. inline Result ClientImpl::Get(const std::string &path,
  10220. DownloadProgress progress) {
  10221. return Get(path, Headers(), std::move(progress));
  10222. }
  10223. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  10224. const Headers &headers,
  10225. DownloadProgress progress) {
  10226. if (params.empty()) { return Get(path, headers); }
  10227. std::string path_with_query = append_query_params(path, params);
  10228. return Get(path_with_query, headers, std::move(progress));
  10229. }
  10230. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  10231. DownloadProgress progress) {
  10232. Request req;
  10233. req.method = "GET";
  10234. req.path = path;
  10235. req.headers = headers;
  10236. req.download_progress = std::move(progress);
  10237. if (max_timeout_msec_ > 0) {
  10238. req.start_time_ = std::chrono::steady_clock::now();
  10239. }
  10240. return send_(std::move(req));
  10241. }
  10242. inline Result ClientImpl::Get(const std::string &path,
  10243. ContentReceiver content_receiver,
  10244. DownloadProgress progress) {
  10245. return Get(path, Headers(), nullptr, std::move(content_receiver),
  10246. std::move(progress));
  10247. }
  10248. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  10249. ContentReceiver content_receiver,
  10250. DownloadProgress progress) {
  10251. return Get(path, headers, nullptr, std::move(content_receiver),
  10252. std::move(progress));
  10253. }
  10254. inline Result ClientImpl::Get(const std::string &path,
  10255. ResponseHandler response_handler,
  10256. ContentReceiver content_receiver,
  10257. DownloadProgress progress) {
  10258. return Get(path, Headers(), std::move(response_handler),
  10259. std::move(content_receiver), std::move(progress));
  10260. }
  10261. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  10262. ResponseHandler response_handler,
  10263. ContentReceiver content_receiver,
  10264. DownloadProgress progress) {
  10265. Request req;
  10266. req.method = "GET";
  10267. req.path = path;
  10268. req.headers = headers;
  10269. req.response_handler = std::move(response_handler);
  10270. req.content_receiver =
  10271. [content_receiver](const char *data, size_t data_length,
  10272. size_t /*offset*/, size_t /*total_length*/) {
  10273. return content_receiver(data, data_length);
  10274. };
  10275. req.download_progress = std::move(progress);
  10276. if (max_timeout_msec_ > 0) {
  10277. req.start_time_ = std::chrono::steady_clock::now();
  10278. }
  10279. return send_(std::move(req));
  10280. }
  10281. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  10282. const Headers &headers,
  10283. ContentReceiver content_receiver,
  10284. DownloadProgress progress) {
  10285. return Get(path, params, headers, nullptr, std::move(content_receiver),
  10286. std::move(progress));
  10287. }
  10288. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  10289. const Headers &headers,
  10290. ResponseHandler response_handler,
  10291. ContentReceiver content_receiver,
  10292. DownloadProgress progress) {
  10293. if (params.empty()) {
  10294. return Get(path, headers, std::move(response_handler),
  10295. std::move(content_receiver), std::move(progress));
  10296. }
  10297. std::string path_with_query = append_query_params(path, params);
  10298. return Get(path_with_query, headers, std::move(response_handler),
  10299. std::move(content_receiver), std::move(progress));
  10300. }
  10301. inline Result ClientImpl::Head(const std::string &path) {
  10302. return Head(path, Headers());
  10303. }
  10304. inline Result ClientImpl::Head(const std::string &path,
  10305. const Headers &headers) {
  10306. Request req;
  10307. req.method = "HEAD";
  10308. req.headers = headers;
  10309. req.path = path;
  10310. if (max_timeout_msec_ > 0) {
  10311. req.start_time_ = std::chrono::steady_clock::now();
  10312. }
  10313. return send_(std::move(req));
  10314. }
  10315. inline Result ClientImpl::Post(const std::string &path) {
  10316. return Post(path, std::string(), std::string());
  10317. }
  10318. inline Result ClientImpl::Post(const std::string &path,
  10319. const Headers &headers) {
  10320. return Post(path, headers, nullptr, 0, std::string());
  10321. }
  10322. inline Result ClientImpl::Post(const std::string &path, const char *body,
  10323. size_t content_length,
  10324. const std::string &content_type,
  10325. UploadProgress progress) {
  10326. return Post(path, Headers(), body, content_length, content_type, progress);
  10327. }
  10328. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  10329. const std::string &content_type,
  10330. UploadProgress progress) {
  10331. return Post(path, Headers(), body, content_type, progress);
  10332. }
  10333. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  10334. return Post(path, Headers(), params);
  10335. }
  10336. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  10337. ContentProvider content_provider,
  10338. const std::string &content_type,
  10339. UploadProgress progress) {
  10340. return Post(path, Headers(), content_length, std::move(content_provider),
  10341. content_type, progress);
  10342. }
  10343. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  10344. ContentProvider content_provider,
  10345. const std::string &content_type,
  10346. ContentReceiver content_receiver,
  10347. UploadProgress progress) {
  10348. return Post(path, Headers(), content_length, std::move(content_provider),
  10349. content_type, std::move(content_receiver), progress);
  10350. }
  10351. inline Result ClientImpl::Post(const std::string &path,
  10352. ContentProviderWithoutLength content_provider,
  10353. const std::string &content_type,
  10354. UploadProgress progress) {
  10355. return Post(path, Headers(), std::move(content_provider), content_type,
  10356. progress);
  10357. }
  10358. inline Result ClientImpl::Post(const std::string &path,
  10359. ContentProviderWithoutLength content_provider,
  10360. const std::string &content_type,
  10361. ContentReceiver content_receiver,
  10362. UploadProgress progress) {
  10363. return Post(path, Headers(), std::move(content_provider), content_type,
  10364. std::move(content_receiver), progress);
  10365. }
  10366. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10367. const Params &params) {
  10368. auto query = detail::params_to_query_str(params);
  10369. return Post(path, headers, query, "application/x-www-form-urlencoded");
  10370. }
  10371. inline Result ClientImpl::Post(const std::string &path,
  10372. const UploadFormDataItems &items,
  10373. UploadProgress progress) {
  10374. return Post(path, Headers(), items, progress);
  10375. }
  10376. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10377. const UploadFormDataItems &items,
  10378. UploadProgress progress) {
  10379. const auto &boundary = detail::make_multipart_data_boundary();
  10380. const auto &content_type =
  10381. detail::serialize_multipart_formdata_get_content_type(boundary);
  10382. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10383. return Post(path, headers, body, content_type, progress);
  10384. }
  10385. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10386. const UploadFormDataItems &items,
  10387. const std::string &boundary,
  10388. UploadProgress progress) {
  10389. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10390. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10391. }
  10392. const auto &content_type =
  10393. detail::serialize_multipart_formdata_get_content_type(boundary);
  10394. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10395. return Post(path, headers, body, content_type, progress);
  10396. }
  10397. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10398. const char *body, size_t content_length,
  10399. const std::string &content_type,
  10400. UploadProgress progress) {
  10401. return send_with_content_provider_and_receiver(
  10402. "POST", path, headers, body, content_length, nullptr, nullptr,
  10403. content_type, nullptr, progress);
  10404. }
  10405. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10406. const std::string &body,
  10407. const std::string &content_type,
  10408. UploadProgress progress) {
  10409. return send_with_content_provider_and_receiver(
  10410. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  10411. content_type, nullptr, progress);
  10412. }
  10413. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10414. size_t content_length,
  10415. ContentProvider content_provider,
  10416. const std::string &content_type,
  10417. UploadProgress progress) {
  10418. return send_with_content_provider_and_receiver(
  10419. "POST", path, headers, nullptr, content_length,
  10420. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10421. }
  10422. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10423. size_t content_length,
  10424. ContentProvider content_provider,
  10425. const std::string &content_type,
  10426. ContentReceiver content_receiver,
  10427. DownloadProgress progress) {
  10428. return send_with_content_provider_and_receiver(
  10429. "POST", path, headers, nullptr, content_length,
  10430. std::move(content_provider), nullptr, content_type,
  10431. std::move(content_receiver), std::move(progress));
  10432. }
  10433. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10434. ContentProviderWithoutLength content_provider,
  10435. const std::string &content_type,
  10436. UploadProgress progress) {
  10437. return send_with_content_provider_and_receiver(
  10438. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10439. content_type, nullptr, progress);
  10440. }
  10441. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10442. ContentProviderWithoutLength content_provider,
  10443. const std::string &content_type,
  10444. ContentReceiver content_receiver,
  10445. DownloadProgress progress) {
  10446. return send_with_content_provider_and_receiver(
  10447. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10448. content_type, std::move(content_receiver), std::move(progress));
  10449. }
  10450. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10451. const UploadFormDataItems &items,
  10452. const FormDataProviderItems &provider_items,
  10453. UploadProgress progress) {
  10454. const auto &boundary = detail::make_multipart_data_boundary();
  10455. const auto &content_type =
  10456. detail::serialize_multipart_formdata_get_content_type(boundary);
  10457. return send_with_content_provider_and_receiver(
  10458. "POST", path, headers, nullptr, 0, nullptr,
  10459. get_multipart_content_provider(boundary, items, provider_items),
  10460. content_type, nullptr, progress);
  10461. }
  10462. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10463. const std::string &body,
  10464. const std::string &content_type,
  10465. ContentReceiver content_receiver,
  10466. DownloadProgress progress) {
  10467. Request req;
  10468. req.method = "POST";
  10469. req.path = path;
  10470. req.headers = headers;
  10471. req.body = body;
  10472. req.content_receiver =
  10473. [content_receiver](const char *data, size_t data_length,
  10474. size_t /*offset*/, size_t /*total_length*/) {
  10475. return content_receiver(data, data_length);
  10476. };
  10477. req.download_progress = std::move(progress);
  10478. if (max_timeout_msec_ > 0) {
  10479. req.start_time_ = std::chrono::steady_clock::now();
  10480. }
  10481. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10482. return send_(std::move(req));
  10483. }
  10484. inline Result ClientImpl::Put(const std::string &path) {
  10485. return Put(path, std::string(), std::string());
  10486. }
  10487. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  10488. return Put(path, headers, nullptr, 0, std::string());
  10489. }
  10490. inline Result ClientImpl::Put(const std::string &path, const char *body,
  10491. size_t content_length,
  10492. const std::string &content_type,
  10493. UploadProgress progress) {
  10494. return Put(path, Headers(), body, content_length, content_type, progress);
  10495. }
  10496. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  10497. const std::string &content_type,
  10498. UploadProgress progress) {
  10499. return Put(path, Headers(), body, content_type, progress);
  10500. }
  10501. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  10502. return Put(path, Headers(), params);
  10503. }
  10504. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10505. ContentProvider content_provider,
  10506. const std::string &content_type,
  10507. UploadProgress progress) {
  10508. return Put(path, Headers(), content_length, std::move(content_provider),
  10509. content_type, progress);
  10510. }
  10511. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10512. ContentProvider content_provider,
  10513. const std::string &content_type,
  10514. ContentReceiver content_receiver,
  10515. UploadProgress progress) {
  10516. return Put(path, Headers(), content_length, std::move(content_provider),
  10517. content_type, std::move(content_receiver), progress);
  10518. }
  10519. inline Result ClientImpl::Put(const std::string &path,
  10520. ContentProviderWithoutLength content_provider,
  10521. const std::string &content_type,
  10522. UploadProgress progress) {
  10523. return Put(path, Headers(), std::move(content_provider), content_type,
  10524. progress);
  10525. }
  10526. inline Result ClientImpl::Put(const std::string &path,
  10527. ContentProviderWithoutLength content_provider,
  10528. const std::string &content_type,
  10529. ContentReceiver content_receiver,
  10530. UploadProgress progress) {
  10531. return Put(path, Headers(), std::move(content_provider), content_type,
  10532. std::move(content_receiver), progress);
  10533. }
  10534. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10535. const Params &params) {
  10536. auto query = detail::params_to_query_str(params);
  10537. return Put(path, headers, query, "application/x-www-form-urlencoded");
  10538. }
  10539. inline Result ClientImpl::Put(const std::string &path,
  10540. const UploadFormDataItems &items,
  10541. UploadProgress progress) {
  10542. return Put(path, Headers(), items, progress);
  10543. }
  10544. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10545. const UploadFormDataItems &items,
  10546. UploadProgress progress) {
  10547. const auto &boundary = detail::make_multipart_data_boundary();
  10548. const auto &content_type =
  10549. detail::serialize_multipart_formdata_get_content_type(boundary);
  10550. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10551. return Put(path, headers, body, content_type, progress);
  10552. }
  10553. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10554. const UploadFormDataItems &items,
  10555. const std::string &boundary,
  10556. UploadProgress progress) {
  10557. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10558. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10559. }
  10560. const auto &content_type =
  10561. detail::serialize_multipart_formdata_get_content_type(boundary);
  10562. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10563. return Put(path, headers, body, content_type, progress);
  10564. }
  10565. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10566. const char *body, size_t content_length,
  10567. const std::string &content_type,
  10568. UploadProgress progress) {
  10569. return send_with_content_provider_and_receiver(
  10570. "PUT", path, headers, body, content_length, nullptr, nullptr,
  10571. content_type, nullptr, progress);
  10572. }
  10573. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10574. const std::string &body,
  10575. const std::string &content_type,
  10576. UploadProgress progress) {
  10577. return send_with_content_provider_and_receiver(
  10578. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  10579. content_type, nullptr, progress);
  10580. }
  10581. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10582. size_t content_length,
  10583. ContentProvider content_provider,
  10584. const std::string &content_type,
  10585. UploadProgress progress) {
  10586. return send_with_content_provider_and_receiver(
  10587. "PUT", path, headers, nullptr, content_length,
  10588. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10589. }
  10590. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10591. size_t content_length,
  10592. ContentProvider content_provider,
  10593. const std::string &content_type,
  10594. ContentReceiver content_receiver,
  10595. UploadProgress progress) {
  10596. return send_with_content_provider_and_receiver(
  10597. "PUT", path, headers, nullptr, content_length,
  10598. std::move(content_provider), nullptr, content_type,
  10599. std::move(content_receiver), progress);
  10600. }
  10601. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10602. ContentProviderWithoutLength content_provider,
  10603. const std::string &content_type,
  10604. UploadProgress progress) {
  10605. return send_with_content_provider_and_receiver(
  10606. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10607. content_type, nullptr, progress);
  10608. }
  10609. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10610. ContentProviderWithoutLength content_provider,
  10611. const std::string &content_type,
  10612. ContentReceiver content_receiver,
  10613. UploadProgress progress) {
  10614. return send_with_content_provider_and_receiver(
  10615. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10616. content_type, std::move(content_receiver), progress);
  10617. }
  10618. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10619. const UploadFormDataItems &items,
  10620. const FormDataProviderItems &provider_items,
  10621. UploadProgress progress) {
  10622. const auto &boundary = detail::make_multipart_data_boundary();
  10623. const auto &content_type =
  10624. detail::serialize_multipart_formdata_get_content_type(boundary);
  10625. return send_with_content_provider_and_receiver(
  10626. "PUT", path, headers, nullptr, 0, nullptr,
  10627. get_multipart_content_provider(boundary, items, provider_items),
  10628. content_type, nullptr, progress);
  10629. }
  10630. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10631. const std::string &body,
  10632. const std::string &content_type,
  10633. ContentReceiver content_receiver,
  10634. DownloadProgress progress) {
  10635. Request req;
  10636. req.method = "PUT";
  10637. req.path = path;
  10638. req.headers = headers;
  10639. req.body = body;
  10640. req.content_receiver =
  10641. [content_receiver](const char *data, size_t data_length,
  10642. size_t /*offset*/, size_t /*total_length*/) {
  10643. return content_receiver(data, data_length);
  10644. };
  10645. req.download_progress = std::move(progress);
  10646. if (max_timeout_msec_ > 0) {
  10647. req.start_time_ = std::chrono::steady_clock::now();
  10648. }
  10649. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10650. return send_(std::move(req));
  10651. }
  10652. inline Result ClientImpl::Patch(const std::string &path) {
  10653. return Patch(path, std::string(), std::string());
  10654. }
  10655. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10656. UploadProgress progress) {
  10657. return Patch(path, headers, nullptr, 0, std::string(), progress);
  10658. }
  10659. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  10660. size_t content_length,
  10661. const std::string &content_type,
  10662. UploadProgress progress) {
  10663. return Patch(path, Headers(), body, content_length, content_type, progress);
  10664. }
  10665. inline Result ClientImpl::Patch(const std::string &path,
  10666. const std::string &body,
  10667. const std::string &content_type,
  10668. UploadProgress progress) {
  10669. return Patch(path, Headers(), body, content_type, progress);
  10670. }
  10671. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  10672. return Patch(path, Headers(), params);
  10673. }
  10674. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10675. ContentProvider content_provider,
  10676. const std::string &content_type,
  10677. UploadProgress progress) {
  10678. return Patch(path, Headers(), content_length, std::move(content_provider),
  10679. content_type, progress);
  10680. }
  10681. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10682. ContentProvider content_provider,
  10683. const std::string &content_type,
  10684. ContentReceiver content_receiver,
  10685. UploadProgress progress) {
  10686. return Patch(path, Headers(), content_length, std::move(content_provider),
  10687. content_type, std::move(content_receiver), progress);
  10688. }
  10689. inline Result ClientImpl::Patch(const std::string &path,
  10690. ContentProviderWithoutLength content_provider,
  10691. const std::string &content_type,
  10692. UploadProgress progress) {
  10693. return Patch(path, Headers(), std::move(content_provider), content_type,
  10694. progress);
  10695. }
  10696. inline Result ClientImpl::Patch(const std::string &path,
  10697. ContentProviderWithoutLength content_provider,
  10698. const std::string &content_type,
  10699. ContentReceiver content_receiver,
  10700. UploadProgress progress) {
  10701. return Patch(path, Headers(), std::move(content_provider), content_type,
  10702. std::move(content_receiver), progress);
  10703. }
  10704. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10705. const Params &params) {
  10706. auto query = detail::params_to_query_str(params);
  10707. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  10708. }
  10709. inline Result ClientImpl::Patch(const std::string &path,
  10710. const UploadFormDataItems &items,
  10711. UploadProgress progress) {
  10712. return Patch(path, Headers(), items, progress);
  10713. }
  10714. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10715. const UploadFormDataItems &items,
  10716. UploadProgress progress) {
  10717. const auto &boundary = detail::make_multipart_data_boundary();
  10718. const auto &content_type =
  10719. detail::serialize_multipart_formdata_get_content_type(boundary);
  10720. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10721. return Patch(path, headers, body, content_type, progress);
  10722. }
  10723. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10724. const UploadFormDataItems &items,
  10725. const std::string &boundary,
  10726. UploadProgress progress) {
  10727. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10728. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10729. }
  10730. const auto &content_type =
  10731. detail::serialize_multipart_formdata_get_content_type(boundary);
  10732. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10733. return Patch(path, headers, body, content_type, progress);
  10734. }
  10735. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10736. const char *body, size_t content_length,
  10737. const std::string &content_type,
  10738. UploadProgress progress) {
  10739. return send_with_content_provider_and_receiver(
  10740. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  10741. content_type, nullptr, progress);
  10742. }
  10743. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10744. const std::string &body,
  10745. const std::string &content_type,
  10746. UploadProgress progress) {
  10747. return send_with_content_provider_and_receiver(
  10748. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  10749. content_type, nullptr, progress);
  10750. }
  10751. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10752. size_t content_length,
  10753. ContentProvider content_provider,
  10754. const std::string &content_type,
  10755. UploadProgress progress) {
  10756. return send_with_content_provider_and_receiver(
  10757. "PATCH", path, headers, nullptr, content_length,
  10758. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10759. }
  10760. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10761. size_t content_length,
  10762. ContentProvider content_provider,
  10763. const std::string &content_type,
  10764. ContentReceiver content_receiver,
  10765. UploadProgress progress) {
  10766. return send_with_content_provider_and_receiver(
  10767. "PATCH", path, headers, nullptr, content_length,
  10768. std::move(content_provider), nullptr, content_type,
  10769. std::move(content_receiver), progress);
  10770. }
  10771. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10772. ContentProviderWithoutLength content_provider,
  10773. const std::string &content_type,
  10774. UploadProgress progress) {
  10775. return send_with_content_provider_and_receiver(
  10776. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10777. content_type, nullptr, progress);
  10778. }
  10779. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10780. ContentProviderWithoutLength content_provider,
  10781. const std::string &content_type,
  10782. ContentReceiver content_receiver,
  10783. UploadProgress progress) {
  10784. return send_with_content_provider_and_receiver(
  10785. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10786. content_type, std::move(content_receiver), progress);
  10787. }
  10788. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10789. const UploadFormDataItems &items,
  10790. const FormDataProviderItems &provider_items,
  10791. UploadProgress progress) {
  10792. const auto &boundary = detail::make_multipart_data_boundary();
  10793. const auto &content_type =
  10794. detail::serialize_multipart_formdata_get_content_type(boundary);
  10795. return send_with_content_provider_and_receiver(
  10796. "PATCH", path, headers, nullptr, 0, nullptr,
  10797. get_multipart_content_provider(boundary, items, provider_items),
  10798. content_type, nullptr, progress);
  10799. }
  10800. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10801. const std::string &body,
  10802. const std::string &content_type,
  10803. ContentReceiver content_receiver,
  10804. DownloadProgress progress) {
  10805. Request req;
  10806. req.method = "PATCH";
  10807. req.path = path;
  10808. req.headers = headers;
  10809. req.body = body;
  10810. req.content_receiver =
  10811. [content_receiver](const char *data, size_t data_length,
  10812. size_t /*offset*/, size_t /*total_length*/) {
  10813. return content_receiver(data, data_length);
  10814. };
  10815. req.download_progress = std::move(progress);
  10816. if (max_timeout_msec_ > 0) {
  10817. req.start_time_ = std::chrono::steady_clock::now();
  10818. }
  10819. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10820. return send_(std::move(req));
  10821. }
  10822. inline Result ClientImpl::Delete(const std::string &path,
  10823. DownloadProgress progress) {
  10824. return Delete(path, Headers(), std::string(), std::string(), progress);
  10825. }
  10826. inline Result ClientImpl::Delete(const std::string &path,
  10827. const Headers &headers,
  10828. DownloadProgress progress) {
  10829. return Delete(path, headers, std::string(), std::string(), progress);
  10830. }
  10831. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  10832. size_t content_length,
  10833. const std::string &content_type,
  10834. DownloadProgress progress) {
  10835. return Delete(path, Headers(), body, content_length, content_type, progress);
  10836. }
  10837. inline Result ClientImpl::Delete(const std::string &path,
  10838. const std::string &body,
  10839. const std::string &content_type,
  10840. DownloadProgress progress) {
  10841. return Delete(path, Headers(), body.data(), body.size(), content_type,
  10842. progress);
  10843. }
  10844. inline Result ClientImpl::Delete(const std::string &path,
  10845. const Headers &headers,
  10846. const std::string &body,
  10847. const std::string &content_type,
  10848. DownloadProgress progress) {
  10849. return Delete(path, headers, body.data(), body.size(), content_type,
  10850. progress);
  10851. }
  10852. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  10853. DownloadProgress progress) {
  10854. return Delete(path, Headers(), params, progress);
  10855. }
  10856. inline Result ClientImpl::Delete(const std::string &path,
  10857. const Headers &headers, const Params &params,
  10858. DownloadProgress progress) {
  10859. auto query = detail::params_to_query_str(params);
  10860. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  10861. progress);
  10862. }
  10863. inline Result ClientImpl::Delete(const std::string &path,
  10864. const Headers &headers, const char *body,
  10865. size_t content_length,
  10866. const std::string &content_type,
  10867. DownloadProgress progress) {
  10868. Request req;
  10869. req.method = "DELETE";
  10870. req.headers = headers;
  10871. req.path = path;
  10872. req.download_progress = std::move(progress);
  10873. if (max_timeout_msec_ > 0) {
  10874. req.start_time_ = std::chrono::steady_clock::now();
  10875. }
  10876. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10877. req.body.assign(body, content_length);
  10878. return send_(std::move(req));
  10879. }
  10880. inline Result ClientImpl::Options(const std::string &path) {
  10881. return Options(path, Headers());
  10882. }
  10883. inline Result ClientImpl::Options(const std::string &path,
  10884. const Headers &headers) {
  10885. Request req;
  10886. req.method = "OPTIONS";
  10887. req.headers = headers;
  10888. req.path = path;
  10889. if (max_timeout_msec_ > 0) {
  10890. req.start_time_ = std::chrono::steady_clock::now();
  10891. }
  10892. return send_(std::move(req));
  10893. }
  10894. inline void ClientImpl::stop() {
  10895. std::lock_guard<std::mutex> guard(socket_mutex_);
  10896. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  10897. // do is to shutdown_socket, so that threads using this socket suddenly
  10898. // discover they can't read/write any more and error out. Everything else
  10899. // (closing the socket, shutting ssl down) is unsafe because these actions
  10900. // are not thread-safe.
  10901. if (socket_requests_in_flight_ > 0) {
  10902. shutdown_socket(socket_);
  10903. // Aside from that, we set a flag for the socket to be closed when we're
  10904. // done.
  10905. socket_should_be_closed_when_request_is_done_ = true;
  10906. return;
  10907. }
  10908. // Otherwise, still holding the mutex, we can shut everything down ourselves
  10909. shutdown_ssl(socket_, true);
  10910. shutdown_socket(socket_);
  10911. close_socket(socket_);
  10912. }
  10913. inline std::string ClientImpl::host() const { return host_; }
  10914. inline int ClientImpl::port() const { return port_; }
  10915. inline size_t ClientImpl::is_socket_open() const {
  10916. std::lock_guard<std::mutex> guard(socket_mutex_);
  10917. return socket_.is_open();
  10918. }
  10919. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  10920. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  10921. connection_timeout_sec_ = sec;
  10922. connection_timeout_usec_ = usec;
  10923. }
  10924. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  10925. read_timeout_sec_ = sec;
  10926. read_timeout_usec_ = usec;
  10927. }
  10928. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  10929. write_timeout_sec_ = sec;
  10930. write_timeout_usec_ = usec;
  10931. }
  10932. inline void ClientImpl::set_max_timeout(time_t msec) {
  10933. max_timeout_msec_ = msec;
  10934. }
  10935. inline void ClientImpl::set_basic_auth(const std::string &username,
  10936. const std::string &password) {
  10937. basic_auth_username_ = username;
  10938. basic_auth_password_ = password;
  10939. }
  10940. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  10941. bearer_token_auth_token_ = token;
  10942. }
  10943. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  10944. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  10945. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  10946. inline void
  10947. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  10948. addr_map_ = std::move(addr_map);
  10949. }
  10950. inline void ClientImpl::set_default_headers(Headers headers) {
  10951. default_headers_ = std::move(headers);
  10952. }
  10953. inline void ClientImpl::set_header_writer(
  10954. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  10955. header_writer_ = writer;
  10956. }
  10957. inline void ClientImpl::set_address_family(int family) {
  10958. address_family_ = family;
  10959. }
  10960. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  10961. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  10962. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  10963. socket_options_ = std::move(socket_options);
  10964. }
  10965. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  10966. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  10967. inline void ClientImpl::set_payload_max_length(size_t length) {
  10968. payload_max_length_ = length;
  10969. has_payload_max_length_ = true;
  10970. }
  10971. inline void ClientImpl::set_interface(const std::string &intf) {
  10972. interface_ = intf;
  10973. }
  10974. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  10975. proxy_host_ = host;
  10976. proxy_port_ = port;
  10977. }
  10978. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  10979. const std::string &password) {
  10980. proxy_basic_auth_username_ = username;
  10981. proxy_basic_auth_password_ = password;
  10982. }
  10983. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  10984. proxy_bearer_token_auth_token_ = token;
  10985. }
  10986. #ifdef CPPHTTPLIB_SSL_ENABLED
  10987. inline void ClientImpl::set_digest_auth(const std::string &username,
  10988. const std::string &password) {
  10989. digest_auth_username_ = username;
  10990. digest_auth_password_ = password;
  10991. }
  10992. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  10993. const std::string &ca_cert_dir_path) {
  10994. ca_cert_file_path_ = ca_cert_file_path;
  10995. ca_cert_dir_path_ = ca_cert_dir_path;
  10996. }
  10997. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  10998. const std::string &password) {
  10999. proxy_digest_auth_username_ = username;
  11000. proxy_digest_auth_password_ = password;
  11001. }
  11002. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  11003. server_certificate_verification_ = enabled;
  11004. }
  11005. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  11006. server_hostname_verification_ = enabled;
  11007. }
  11008. #endif
  11009. // ClientImpl::set_ca_cert_store is defined after TLS namespace (uses helpers)
  11010. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11011. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  11012. std::size_t size) const {
  11013. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  11014. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  11015. if (!mem) { return nullptr; }
  11016. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  11017. if (!inf) { return nullptr; }
  11018. auto cts = X509_STORE_new();
  11019. if (cts) {
  11020. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  11021. auto itmp = sk_X509_INFO_value(inf, i);
  11022. if (!itmp) { continue; }
  11023. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  11024. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  11025. }
  11026. }
  11027. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  11028. return cts;
  11029. }
  11030. inline void ClientImpl::set_server_certificate_verifier(
  11031. std::function<SSLVerifierResponse(SSL *ssl)> /*verifier*/) {
  11032. // Base implementation does nothing - SSLClient overrides this
  11033. }
  11034. #endif
  11035. inline void ClientImpl::set_logger(Logger logger) {
  11036. logger_ = std::move(logger);
  11037. }
  11038. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  11039. error_logger_ = std::move(error_logger);
  11040. }
  11041. /*
  11042. * SSL/TLS Common Implementation
  11043. */
  11044. inline ClientConnection::~ClientConnection() {
  11045. #ifdef CPPHTTPLIB_SSL_ENABLED
  11046. if (session) {
  11047. tls::shutdown(session, true);
  11048. tls::free_session(session);
  11049. session = nullptr;
  11050. }
  11051. #endif
  11052. if (sock != INVALID_SOCKET) {
  11053. detail::close_socket(sock);
  11054. sock = INVALID_SOCKET;
  11055. }
  11056. }
  11057. // Universal client implementation
  11058. inline Client::Client(const std::string &scheme_host_port)
  11059. : Client(scheme_host_port, std::string(), std::string()) {}
  11060. inline Client::Client(const std::string &scheme_host_port,
  11061. const std::string &client_cert_path,
  11062. const std::string &client_key_path) {
  11063. const static std::regex re(
  11064. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  11065. std::smatch m;
  11066. if (std::regex_match(scheme_host_port, m, re)) {
  11067. auto scheme = m[1].str();
  11068. #ifdef CPPHTTPLIB_SSL_ENABLED
  11069. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  11070. #else
  11071. if (!scheme.empty() && scheme != "http") {
  11072. #endif
  11073. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11074. std::string msg = "'" + scheme + "' scheme is not supported.";
  11075. throw std::invalid_argument(msg);
  11076. #endif
  11077. return;
  11078. }
  11079. auto is_ssl = scheme == "https";
  11080. auto host = m[2].str();
  11081. if (host.empty()) { host = m[3].str(); }
  11082. auto port_str = m[4].str();
  11083. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  11084. if (is_ssl) {
  11085. #ifdef CPPHTTPLIB_SSL_ENABLED
  11086. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  11087. client_key_path);
  11088. is_ssl_ = is_ssl;
  11089. #endif
  11090. } else {
  11091. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  11092. client_key_path);
  11093. }
  11094. } else {
  11095. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  11096. // if port param below changes.
  11097. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  11098. client_cert_path, client_key_path);
  11099. }
  11100. } // namespace detail
  11101. inline Client::Client(const std::string &host, int port)
  11102. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  11103. inline Client::Client(const std::string &host, int port,
  11104. const std::string &client_cert_path,
  11105. const std::string &client_key_path)
  11106. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  11107. client_key_path)) {}
  11108. inline Client::~Client() = default;
  11109. inline bool Client::is_valid() const {
  11110. return cli_ != nullptr && cli_->is_valid();
  11111. }
  11112. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  11113. return cli_->Get(path, std::move(progress));
  11114. }
  11115. inline Result Client::Get(const std::string &path, const Headers &headers,
  11116. DownloadProgress progress) {
  11117. return cli_->Get(path, headers, std::move(progress));
  11118. }
  11119. inline Result Client::Get(const std::string &path,
  11120. ContentReceiver content_receiver,
  11121. DownloadProgress progress) {
  11122. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  11123. }
  11124. inline Result Client::Get(const std::string &path, const Headers &headers,
  11125. ContentReceiver content_receiver,
  11126. DownloadProgress progress) {
  11127. return cli_->Get(path, headers, std::move(content_receiver),
  11128. std::move(progress));
  11129. }
  11130. inline Result Client::Get(const std::string &path,
  11131. ResponseHandler response_handler,
  11132. ContentReceiver content_receiver,
  11133. DownloadProgress progress) {
  11134. return cli_->Get(path, std::move(response_handler),
  11135. std::move(content_receiver), std::move(progress));
  11136. }
  11137. inline Result Client::Get(const std::string &path, const Headers &headers,
  11138. ResponseHandler response_handler,
  11139. ContentReceiver content_receiver,
  11140. DownloadProgress progress) {
  11141. return cli_->Get(path, headers, std::move(response_handler),
  11142. std::move(content_receiver), std::move(progress));
  11143. }
  11144. inline Result Client::Get(const std::string &path, const Params &params,
  11145. const Headers &headers, DownloadProgress progress) {
  11146. return cli_->Get(path, params, headers, std::move(progress));
  11147. }
  11148. inline Result Client::Get(const std::string &path, const Params &params,
  11149. const Headers &headers,
  11150. ContentReceiver content_receiver,
  11151. DownloadProgress progress) {
  11152. return cli_->Get(path, params, headers, std::move(content_receiver),
  11153. std::move(progress));
  11154. }
  11155. inline Result Client::Get(const std::string &path, const Params &params,
  11156. const Headers &headers,
  11157. ResponseHandler response_handler,
  11158. ContentReceiver content_receiver,
  11159. DownloadProgress progress) {
  11160. return cli_->Get(path, params, headers, std::move(response_handler),
  11161. std::move(content_receiver), std::move(progress));
  11162. }
  11163. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  11164. inline Result Client::Head(const std::string &path, const Headers &headers) {
  11165. return cli_->Head(path, headers);
  11166. }
  11167. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  11168. inline Result Client::Post(const std::string &path, const Headers &headers) {
  11169. return cli_->Post(path, headers);
  11170. }
  11171. inline Result Client::Post(const std::string &path, const char *body,
  11172. size_t content_length,
  11173. const std::string &content_type,
  11174. UploadProgress progress) {
  11175. return cli_->Post(path, body, content_length, content_type, progress);
  11176. }
  11177. inline Result Client::Post(const std::string &path, const Headers &headers,
  11178. const char *body, size_t content_length,
  11179. const std::string &content_type,
  11180. UploadProgress progress) {
  11181. return cli_->Post(path, headers, body, content_length, content_type,
  11182. progress);
  11183. }
  11184. inline Result Client::Post(const std::string &path, const std::string &body,
  11185. const std::string &content_type,
  11186. UploadProgress progress) {
  11187. return cli_->Post(path, body, content_type, progress);
  11188. }
  11189. inline Result Client::Post(const std::string &path, const Headers &headers,
  11190. const std::string &body,
  11191. const std::string &content_type,
  11192. UploadProgress progress) {
  11193. return cli_->Post(path, headers, body, content_type, progress);
  11194. }
  11195. inline Result Client::Post(const std::string &path, size_t content_length,
  11196. ContentProvider content_provider,
  11197. const std::string &content_type,
  11198. UploadProgress progress) {
  11199. return cli_->Post(path, content_length, std::move(content_provider),
  11200. content_type, progress);
  11201. }
  11202. inline Result Client::Post(const std::string &path, size_t content_length,
  11203. ContentProvider content_provider,
  11204. const std::string &content_type,
  11205. ContentReceiver content_receiver,
  11206. UploadProgress progress) {
  11207. return cli_->Post(path, content_length, std::move(content_provider),
  11208. content_type, std::move(content_receiver), progress);
  11209. }
  11210. inline Result Client::Post(const std::string &path,
  11211. ContentProviderWithoutLength content_provider,
  11212. const std::string &content_type,
  11213. UploadProgress progress) {
  11214. return cli_->Post(path, std::move(content_provider), content_type, progress);
  11215. }
  11216. inline Result Client::Post(const std::string &path,
  11217. ContentProviderWithoutLength content_provider,
  11218. const std::string &content_type,
  11219. ContentReceiver content_receiver,
  11220. UploadProgress progress) {
  11221. return cli_->Post(path, std::move(content_provider), content_type,
  11222. std::move(content_receiver), progress);
  11223. }
  11224. inline Result Client::Post(const std::string &path, const Headers &headers,
  11225. size_t content_length,
  11226. ContentProvider content_provider,
  11227. const std::string &content_type,
  11228. UploadProgress progress) {
  11229. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11230. content_type, progress);
  11231. }
  11232. inline Result Client::Post(const std::string &path, const Headers &headers,
  11233. size_t content_length,
  11234. ContentProvider content_provider,
  11235. const std::string &content_type,
  11236. ContentReceiver content_receiver,
  11237. DownloadProgress progress) {
  11238. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11239. content_type, std::move(content_receiver), progress);
  11240. }
  11241. inline Result Client::Post(const std::string &path, const Headers &headers,
  11242. ContentProviderWithoutLength content_provider,
  11243. const std::string &content_type,
  11244. UploadProgress progress) {
  11245. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11246. progress);
  11247. }
  11248. inline Result Client::Post(const std::string &path, const Headers &headers,
  11249. ContentProviderWithoutLength content_provider,
  11250. const std::string &content_type,
  11251. ContentReceiver content_receiver,
  11252. DownloadProgress progress) {
  11253. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11254. std::move(content_receiver), progress);
  11255. }
  11256. inline Result Client::Post(const std::string &path, const Params &params) {
  11257. return cli_->Post(path, params);
  11258. }
  11259. inline Result Client::Post(const std::string &path, const Headers &headers,
  11260. const Params &params) {
  11261. return cli_->Post(path, headers, params);
  11262. }
  11263. inline Result Client::Post(const std::string &path,
  11264. const UploadFormDataItems &items,
  11265. UploadProgress progress) {
  11266. return cli_->Post(path, items, progress);
  11267. }
  11268. inline Result Client::Post(const std::string &path, const Headers &headers,
  11269. const UploadFormDataItems &items,
  11270. UploadProgress progress) {
  11271. return cli_->Post(path, headers, items, progress);
  11272. }
  11273. inline Result Client::Post(const std::string &path, const Headers &headers,
  11274. const UploadFormDataItems &items,
  11275. const std::string &boundary,
  11276. UploadProgress progress) {
  11277. return cli_->Post(path, headers, items, boundary, progress);
  11278. }
  11279. inline Result Client::Post(const std::string &path, const Headers &headers,
  11280. const UploadFormDataItems &items,
  11281. const FormDataProviderItems &provider_items,
  11282. UploadProgress progress) {
  11283. return cli_->Post(path, headers, items, provider_items, progress);
  11284. }
  11285. inline Result Client::Post(const std::string &path, const Headers &headers,
  11286. const std::string &body,
  11287. const std::string &content_type,
  11288. ContentReceiver content_receiver,
  11289. DownloadProgress progress) {
  11290. return cli_->Post(path, headers, body, content_type,
  11291. std::move(content_receiver), progress);
  11292. }
  11293. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  11294. inline Result Client::Put(const std::string &path, const Headers &headers) {
  11295. return cli_->Put(path, headers);
  11296. }
  11297. inline Result Client::Put(const std::string &path, const char *body,
  11298. size_t content_length,
  11299. const std::string &content_type,
  11300. UploadProgress progress) {
  11301. return cli_->Put(path, body, content_length, content_type, progress);
  11302. }
  11303. inline Result Client::Put(const std::string &path, const Headers &headers,
  11304. const char *body, size_t content_length,
  11305. const std::string &content_type,
  11306. UploadProgress progress) {
  11307. return cli_->Put(path, headers, body, content_length, content_type, progress);
  11308. }
  11309. inline Result Client::Put(const std::string &path, const std::string &body,
  11310. const std::string &content_type,
  11311. UploadProgress progress) {
  11312. return cli_->Put(path, body, content_type, progress);
  11313. }
  11314. inline Result Client::Put(const std::string &path, const Headers &headers,
  11315. const std::string &body,
  11316. const std::string &content_type,
  11317. UploadProgress progress) {
  11318. return cli_->Put(path, headers, body, content_type, progress);
  11319. }
  11320. inline Result Client::Put(const std::string &path, size_t content_length,
  11321. ContentProvider content_provider,
  11322. const std::string &content_type,
  11323. UploadProgress progress) {
  11324. return cli_->Put(path, content_length, std::move(content_provider),
  11325. content_type, progress);
  11326. }
  11327. inline Result Client::Put(const std::string &path, size_t content_length,
  11328. ContentProvider content_provider,
  11329. const std::string &content_type,
  11330. ContentReceiver content_receiver,
  11331. UploadProgress progress) {
  11332. return cli_->Put(path, content_length, std::move(content_provider),
  11333. content_type, std::move(content_receiver), progress);
  11334. }
  11335. inline Result Client::Put(const std::string &path,
  11336. ContentProviderWithoutLength content_provider,
  11337. const std::string &content_type,
  11338. UploadProgress progress) {
  11339. return cli_->Put(path, std::move(content_provider), content_type, progress);
  11340. }
  11341. inline Result Client::Put(const std::string &path,
  11342. ContentProviderWithoutLength content_provider,
  11343. const std::string &content_type,
  11344. ContentReceiver content_receiver,
  11345. UploadProgress progress) {
  11346. return cli_->Put(path, std::move(content_provider), content_type,
  11347. std::move(content_receiver), progress);
  11348. }
  11349. inline Result Client::Put(const std::string &path, const Headers &headers,
  11350. size_t content_length,
  11351. ContentProvider content_provider,
  11352. const std::string &content_type,
  11353. UploadProgress progress) {
  11354. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11355. content_type, progress);
  11356. }
  11357. inline Result Client::Put(const std::string &path, const Headers &headers,
  11358. size_t content_length,
  11359. ContentProvider content_provider,
  11360. const std::string &content_type,
  11361. ContentReceiver content_receiver,
  11362. UploadProgress progress) {
  11363. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11364. content_type, std::move(content_receiver), progress);
  11365. }
  11366. inline Result Client::Put(const std::string &path, const Headers &headers,
  11367. ContentProviderWithoutLength content_provider,
  11368. const std::string &content_type,
  11369. UploadProgress progress) {
  11370. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11371. progress);
  11372. }
  11373. inline Result Client::Put(const std::string &path, const Headers &headers,
  11374. ContentProviderWithoutLength content_provider,
  11375. const std::string &content_type,
  11376. ContentReceiver content_receiver,
  11377. UploadProgress progress) {
  11378. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11379. std::move(content_receiver), progress);
  11380. }
  11381. inline Result Client::Put(const std::string &path, const Params &params) {
  11382. return cli_->Put(path, params);
  11383. }
  11384. inline Result Client::Put(const std::string &path, const Headers &headers,
  11385. const Params &params) {
  11386. return cli_->Put(path, headers, params);
  11387. }
  11388. inline Result Client::Put(const std::string &path,
  11389. const UploadFormDataItems &items,
  11390. UploadProgress progress) {
  11391. return cli_->Put(path, items, progress);
  11392. }
  11393. inline Result Client::Put(const std::string &path, const Headers &headers,
  11394. const UploadFormDataItems &items,
  11395. UploadProgress progress) {
  11396. return cli_->Put(path, headers, items, progress);
  11397. }
  11398. inline Result Client::Put(const std::string &path, const Headers &headers,
  11399. const UploadFormDataItems &items,
  11400. const std::string &boundary,
  11401. UploadProgress progress) {
  11402. return cli_->Put(path, headers, items, boundary, progress);
  11403. }
  11404. inline Result Client::Put(const std::string &path, const Headers &headers,
  11405. const UploadFormDataItems &items,
  11406. const FormDataProviderItems &provider_items,
  11407. UploadProgress progress) {
  11408. return cli_->Put(path, headers, items, provider_items, progress);
  11409. }
  11410. inline Result Client::Put(const std::string &path, const Headers &headers,
  11411. const std::string &body,
  11412. const std::string &content_type,
  11413. ContentReceiver content_receiver,
  11414. DownloadProgress progress) {
  11415. return cli_->Put(path, headers, body, content_type, content_receiver,
  11416. progress);
  11417. }
  11418. inline Result Client::Patch(const std::string &path) {
  11419. return cli_->Patch(path);
  11420. }
  11421. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  11422. return cli_->Patch(path, headers);
  11423. }
  11424. inline Result Client::Patch(const std::string &path, const char *body,
  11425. size_t content_length,
  11426. const std::string &content_type,
  11427. UploadProgress progress) {
  11428. return cli_->Patch(path, body, content_length, content_type, progress);
  11429. }
  11430. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11431. const char *body, size_t content_length,
  11432. const std::string &content_type,
  11433. UploadProgress progress) {
  11434. return cli_->Patch(path, headers, body, content_length, content_type,
  11435. progress);
  11436. }
  11437. inline Result Client::Patch(const std::string &path, const std::string &body,
  11438. const std::string &content_type,
  11439. UploadProgress progress) {
  11440. return cli_->Patch(path, body, content_type, progress);
  11441. }
  11442. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11443. const std::string &body,
  11444. const std::string &content_type,
  11445. UploadProgress progress) {
  11446. return cli_->Patch(path, headers, body, content_type, progress);
  11447. }
  11448. inline Result Client::Patch(const std::string &path, size_t content_length,
  11449. ContentProvider content_provider,
  11450. const std::string &content_type,
  11451. UploadProgress progress) {
  11452. return cli_->Patch(path, content_length, std::move(content_provider),
  11453. content_type, progress);
  11454. }
  11455. inline Result Client::Patch(const std::string &path, size_t content_length,
  11456. ContentProvider content_provider,
  11457. const std::string &content_type,
  11458. ContentReceiver content_receiver,
  11459. UploadProgress progress) {
  11460. return cli_->Patch(path, content_length, std::move(content_provider),
  11461. content_type, std::move(content_receiver), progress);
  11462. }
  11463. inline Result Client::Patch(const std::string &path,
  11464. ContentProviderWithoutLength content_provider,
  11465. const std::string &content_type,
  11466. UploadProgress progress) {
  11467. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  11468. }
  11469. inline Result Client::Patch(const std::string &path,
  11470. ContentProviderWithoutLength content_provider,
  11471. const std::string &content_type,
  11472. ContentReceiver content_receiver,
  11473. UploadProgress progress) {
  11474. return cli_->Patch(path, std::move(content_provider), content_type,
  11475. std::move(content_receiver), progress);
  11476. }
  11477. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11478. size_t content_length,
  11479. ContentProvider content_provider,
  11480. const std::string &content_type,
  11481. UploadProgress progress) {
  11482. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11483. content_type, progress);
  11484. }
  11485. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11486. size_t content_length,
  11487. ContentProvider content_provider,
  11488. const std::string &content_type,
  11489. ContentReceiver content_receiver,
  11490. UploadProgress progress) {
  11491. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11492. content_type, std::move(content_receiver), progress);
  11493. }
  11494. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11495. ContentProviderWithoutLength content_provider,
  11496. const std::string &content_type,
  11497. UploadProgress progress) {
  11498. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11499. progress);
  11500. }
  11501. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11502. ContentProviderWithoutLength content_provider,
  11503. const std::string &content_type,
  11504. ContentReceiver content_receiver,
  11505. UploadProgress progress) {
  11506. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11507. std::move(content_receiver), progress);
  11508. }
  11509. inline Result Client::Patch(const std::string &path, const Params &params) {
  11510. return cli_->Patch(path, params);
  11511. }
  11512. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11513. const Params &params) {
  11514. return cli_->Patch(path, headers, params);
  11515. }
  11516. inline Result Client::Patch(const std::string &path,
  11517. const UploadFormDataItems &items,
  11518. UploadProgress progress) {
  11519. return cli_->Patch(path, items, progress);
  11520. }
  11521. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11522. const UploadFormDataItems &items,
  11523. UploadProgress progress) {
  11524. return cli_->Patch(path, headers, items, progress);
  11525. }
  11526. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11527. const UploadFormDataItems &items,
  11528. const std::string &boundary,
  11529. UploadProgress progress) {
  11530. return cli_->Patch(path, headers, items, boundary, progress);
  11531. }
  11532. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11533. const UploadFormDataItems &items,
  11534. const FormDataProviderItems &provider_items,
  11535. UploadProgress progress) {
  11536. return cli_->Patch(path, headers, items, provider_items, progress);
  11537. }
  11538. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11539. const std::string &body,
  11540. const std::string &content_type,
  11541. ContentReceiver content_receiver,
  11542. DownloadProgress progress) {
  11543. return cli_->Patch(path, headers, body, content_type, content_receiver,
  11544. progress);
  11545. }
  11546. inline Result Client::Delete(const std::string &path,
  11547. DownloadProgress progress) {
  11548. return cli_->Delete(path, progress);
  11549. }
  11550. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11551. DownloadProgress progress) {
  11552. return cli_->Delete(path, headers, progress);
  11553. }
  11554. inline Result Client::Delete(const std::string &path, const char *body,
  11555. size_t content_length,
  11556. const std::string &content_type,
  11557. DownloadProgress progress) {
  11558. return cli_->Delete(path, body, content_length, content_type, progress);
  11559. }
  11560. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11561. const char *body, size_t content_length,
  11562. const std::string &content_type,
  11563. DownloadProgress progress) {
  11564. return cli_->Delete(path, headers, body, content_length, content_type,
  11565. progress);
  11566. }
  11567. inline Result Client::Delete(const std::string &path, const std::string &body,
  11568. const std::string &content_type,
  11569. DownloadProgress progress) {
  11570. return cli_->Delete(path, body, content_type, progress);
  11571. }
  11572. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11573. const std::string &body,
  11574. const std::string &content_type,
  11575. DownloadProgress progress) {
  11576. return cli_->Delete(path, headers, body, content_type, progress);
  11577. }
  11578. inline Result Client::Delete(const std::string &path, const Params &params,
  11579. DownloadProgress progress) {
  11580. return cli_->Delete(path, params, progress);
  11581. }
  11582. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11583. const Params &params, DownloadProgress progress) {
  11584. return cli_->Delete(path, headers, params, progress);
  11585. }
  11586. inline Result Client::Options(const std::string &path) {
  11587. return cli_->Options(path);
  11588. }
  11589. inline Result Client::Options(const std::string &path, const Headers &headers) {
  11590. return cli_->Options(path, headers);
  11591. }
  11592. inline ClientImpl::StreamHandle
  11593. Client::open_stream(const std::string &method, const std::string &path,
  11594. const Params &params, const Headers &headers,
  11595. const std::string &body, const std::string &content_type) {
  11596. return cli_->open_stream(method, path, params, headers, body, content_type);
  11597. }
  11598. inline bool Client::send(Request &req, Response &res, Error &error) {
  11599. return cli_->send(req, res, error);
  11600. }
  11601. inline Result Client::send(const Request &req) { return cli_->send(req); }
  11602. inline void Client::stop() { cli_->stop(); }
  11603. inline std::string Client::host() const { return cli_->host(); }
  11604. inline int Client::port() const { return cli_->port(); }
  11605. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  11606. inline socket_t Client::socket() const { return cli_->socket(); }
  11607. inline void
  11608. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  11609. cli_->set_hostname_addr_map(std::move(addr_map));
  11610. }
  11611. inline void Client::set_default_headers(Headers headers) {
  11612. cli_->set_default_headers(std::move(headers));
  11613. }
  11614. inline void Client::set_header_writer(
  11615. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11616. cli_->set_header_writer(writer);
  11617. }
  11618. inline void Client::set_address_family(int family) {
  11619. cli_->set_address_family(family);
  11620. }
  11621. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  11622. inline void Client::set_socket_options(SocketOptions socket_options) {
  11623. cli_->set_socket_options(std::move(socket_options));
  11624. }
  11625. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  11626. cli_->set_connection_timeout(sec, usec);
  11627. }
  11628. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  11629. cli_->set_read_timeout(sec, usec);
  11630. }
  11631. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  11632. cli_->set_write_timeout(sec, usec);
  11633. }
  11634. inline void Client::set_basic_auth(const std::string &username,
  11635. const std::string &password) {
  11636. cli_->set_basic_auth(username, password);
  11637. }
  11638. inline void Client::set_bearer_token_auth(const std::string &token) {
  11639. cli_->set_bearer_token_auth(token);
  11640. }
  11641. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  11642. inline void Client::set_follow_location(bool on) {
  11643. cli_->set_follow_location(on);
  11644. }
  11645. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  11646. [[deprecated("Use set_path_encode instead")]]
  11647. inline void Client::set_url_encode(bool on) {
  11648. cli_->set_path_encode(on);
  11649. }
  11650. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  11651. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  11652. inline void Client::set_payload_max_length(size_t length) {
  11653. cli_->set_payload_max_length(length);
  11654. }
  11655. inline void Client::set_interface(const std::string &intf) {
  11656. cli_->set_interface(intf);
  11657. }
  11658. inline void Client::set_proxy(const std::string &host, int port) {
  11659. cli_->set_proxy(host, port);
  11660. }
  11661. inline void Client::set_proxy_basic_auth(const std::string &username,
  11662. const std::string &password) {
  11663. cli_->set_proxy_basic_auth(username, password);
  11664. }
  11665. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  11666. cli_->set_proxy_bearer_token_auth(token);
  11667. }
  11668. inline void Client::set_logger(Logger logger) {
  11669. cli_->set_logger(std::move(logger));
  11670. }
  11671. inline void Client::set_error_logger(ErrorLogger error_logger) {
  11672. cli_->set_error_logger(std::move(error_logger));
  11673. }
  11674. /*
  11675. * Group 6: SSL Server and Client implementation
  11676. */
  11677. #ifdef CPPHTTPLIB_SSL_ENABLED
  11678. // SSL HTTP server implementation
  11679. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  11680. const char *client_ca_cert_file_path,
  11681. const char *client_ca_cert_dir_path,
  11682. const char *private_key_password) {
  11683. using namespace tls;
  11684. ctx_ = create_server_context();
  11685. if (!ctx_) { return; }
  11686. // Load server certificate and private key
  11687. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  11688. private_key_password)) {
  11689. last_ssl_error_ = static_cast<int>(get_error());
  11690. free_context(ctx_);
  11691. ctx_ = nullptr;
  11692. return;
  11693. }
  11694. // Load client CA certificates for client authentication
  11695. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  11696. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  11697. client_ca_cert_dir_path)) {
  11698. last_ssl_error_ = static_cast<int>(get_error());
  11699. free_context(ctx_);
  11700. ctx_ = nullptr;
  11701. return;
  11702. }
  11703. // Enable client certificate verification
  11704. set_verify_client(ctx_, true);
  11705. }
  11706. }
  11707. inline SSLServer::SSLServer(const PemMemory &pem) {
  11708. using namespace tls;
  11709. ctx_ = create_server_context();
  11710. if (ctx_) {
  11711. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  11712. pem.private_key_password)) {
  11713. last_ssl_error_ = static_cast<int>(get_error());
  11714. free_context(ctx_);
  11715. ctx_ = nullptr;
  11716. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  11717. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  11718. last_ssl_error_ = static_cast<int>(get_error());
  11719. free_context(ctx_);
  11720. ctx_ = nullptr;
  11721. } else {
  11722. set_verify_client(ctx_, true);
  11723. }
  11724. }
  11725. }
  11726. }
  11727. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  11728. using namespace tls;
  11729. ctx_ = create_server_context();
  11730. if (ctx_) {
  11731. if (!setup_callback(ctx_)) {
  11732. free_context(ctx_);
  11733. ctx_ = nullptr;
  11734. }
  11735. }
  11736. }
  11737. inline SSLServer::~SSLServer() {
  11738. if (ctx_) { tls::free_context(ctx_); }
  11739. }
  11740. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  11741. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  11742. using namespace tls;
  11743. // Create TLS session with mutex protection
  11744. session_t session = nullptr;
  11745. {
  11746. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11747. session = create_session(static_cast<ctx_t>(ctx_), sock);
  11748. }
  11749. if (!session) {
  11750. last_ssl_error_ = static_cast<int>(get_error());
  11751. detail::shutdown_socket(sock);
  11752. detail::close_socket(sock);
  11753. return false;
  11754. }
  11755. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  11756. bool handshake_done = false;
  11757. bool ret = false;
  11758. auto cleanup = detail::scope_exit([&] {
  11759. // Shutdown gracefully if handshake succeeded and processing was successful
  11760. if (handshake_done) { shutdown(session, ret); }
  11761. free_session(session);
  11762. detail::shutdown_socket(sock);
  11763. detail::close_socket(sock);
  11764. });
  11765. // Perform TLS accept handshake with timeout
  11766. TlsError tls_err;
  11767. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  11768. &tls_err)) {
  11769. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11770. // Map TlsError to legacy ssl_error for backward compatibility
  11771. if (tls_err.code == ErrorCode::WantRead) {
  11772. last_ssl_error_ = SSL_ERROR_WANT_READ;
  11773. } else if (tls_err.code == ErrorCode::WantWrite) {
  11774. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  11775. } else {
  11776. last_ssl_error_ = SSL_ERROR_SSL;
  11777. }
  11778. #else
  11779. last_ssl_error_ = static_cast<int>(get_error());
  11780. #endif
  11781. return false;
  11782. }
  11783. handshake_done = true;
  11784. std::string remote_addr;
  11785. int remote_port = 0;
  11786. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  11787. std::string local_addr;
  11788. int local_port = 0;
  11789. detail::get_local_ip_and_port(sock, local_addr, local_port);
  11790. ret = detail::process_server_socket_ssl(
  11791. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  11792. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11793. write_timeout_usec_,
  11794. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  11795. return process_request(strm, remote_addr, remote_port, local_addr,
  11796. local_port, close_connection, connection_closed,
  11797. [&](Request &req) { req.ssl = session; });
  11798. });
  11799. return ret;
  11800. }
  11801. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  11802. const char *key_pem,
  11803. const char *client_ca_pem,
  11804. const char *password) {
  11805. if (!ctx_) { return false; }
  11806. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11807. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  11808. return false;
  11809. }
  11810. if (client_ca_pem) {
  11811. return tls::update_server_client_ca(ctx_, client_ca_pem);
  11812. }
  11813. return true;
  11814. }
  11815. // SSL HTTP client implementation
  11816. inline SSLClient::~SSLClient() {
  11817. if (ctx_) { tls::free_context(ctx_); }
  11818. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  11819. // base function rather than the derived function once we get to the
  11820. // base class destructor, and won't free the SSL (causing a leak).
  11821. shutdown_ssl_impl(socket_, true);
  11822. }
  11823. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  11824. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  11825. shutdown_ssl_impl(socket, shutdown_gracefully);
  11826. }
  11827. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  11828. bool shutdown_gracefully) {
  11829. if (socket.sock == INVALID_SOCKET) {
  11830. assert(socket.ssl == nullptr);
  11831. return;
  11832. }
  11833. if (socket.ssl) {
  11834. tls::shutdown(socket.ssl, shutdown_gracefully);
  11835. {
  11836. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11837. tls::free_session(socket.ssl);
  11838. }
  11839. socket.ssl = nullptr;
  11840. }
  11841. assert(socket.ssl == nullptr);
  11842. }
  11843. inline bool SSLClient::process_socket(
  11844. const Socket &socket,
  11845. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11846. std::function<bool(Stream &strm)> callback) {
  11847. assert(socket.ssl);
  11848. return detail::process_client_socket_ssl(
  11849. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  11850. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  11851. std::move(callback));
  11852. }
  11853. inline bool SSLClient::is_ssl() const { return true; }
  11854. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  11855. if (!is_valid()) {
  11856. error = Error::SSLConnection;
  11857. return false;
  11858. }
  11859. return ClientImpl::create_and_connect_socket(socket, error);
  11860. }
  11861. // Assumes that socket_mutex_ is locked and that there are no requests in
  11862. // flight
  11863. inline bool SSLClient::connect_with_proxy(
  11864. Socket &socket,
  11865. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11866. Response &res, bool &success, Error &error) {
  11867. success = true;
  11868. Response proxy_res;
  11869. if (!detail::process_client_socket(
  11870. socket.sock, read_timeout_sec_, read_timeout_usec_,
  11871. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  11872. start_time, [&](Stream &strm) {
  11873. Request req2;
  11874. req2.method = "CONNECT";
  11875. req2.path =
  11876. detail::make_host_and_port_string_always_port(host_, port_);
  11877. if (max_timeout_msec_ > 0) {
  11878. req2.start_time_ = std::chrono::steady_clock::now();
  11879. }
  11880. return process_request(strm, req2, proxy_res, false, error);
  11881. })) {
  11882. // Thread-safe to close everything because we are assuming there are no
  11883. // requests in flight
  11884. shutdown_ssl(socket, true);
  11885. shutdown_socket(socket);
  11886. close_socket(socket);
  11887. success = false;
  11888. return false;
  11889. }
  11890. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  11891. if (!proxy_digest_auth_username_.empty() &&
  11892. !proxy_digest_auth_password_.empty()) {
  11893. std::map<std::string, std::string> auth;
  11894. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  11895. // Close the current socket and create a new one for the authenticated
  11896. // request
  11897. shutdown_ssl(socket, true);
  11898. shutdown_socket(socket);
  11899. close_socket(socket);
  11900. // Create a new socket for the authenticated CONNECT request
  11901. if (!ensure_socket_connection(socket, error)) {
  11902. success = false;
  11903. output_error_log(error, nullptr);
  11904. return false;
  11905. }
  11906. proxy_res = Response();
  11907. if (!detail::process_client_socket(
  11908. socket.sock, read_timeout_sec_, read_timeout_usec_,
  11909. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  11910. start_time, [&](Stream &strm) {
  11911. Request req3;
  11912. req3.method = "CONNECT";
  11913. req3.path = detail::make_host_and_port_string_always_port(
  11914. host_, port_);
  11915. req3.headers.insert(detail::make_digest_authentication_header(
  11916. req3, auth, 1, detail::random_string(10),
  11917. proxy_digest_auth_username_, proxy_digest_auth_password_,
  11918. true));
  11919. if (max_timeout_msec_ > 0) {
  11920. req3.start_time_ = std::chrono::steady_clock::now();
  11921. }
  11922. return process_request(strm, req3, proxy_res, false, error);
  11923. })) {
  11924. // Thread-safe to close everything because we are assuming there are
  11925. // no requests in flight
  11926. shutdown_ssl(socket, true);
  11927. shutdown_socket(socket);
  11928. close_socket(socket);
  11929. success = false;
  11930. return false;
  11931. }
  11932. }
  11933. }
  11934. }
  11935. // If status code is not 200, proxy request is failed.
  11936. // Set error to ProxyConnection and return proxy response
  11937. // as the response of the request
  11938. if (proxy_res.status != StatusCode::OK_200) {
  11939. error = Error::ProxyConnection;
  11940. output_error_log(error, nullptr);
  11941. res = std::move(proxy_res);
  11942. // Thread-safe to close everything because we are assuming there are
  11943. // no requests in flight
  11944. shutdown_ssl(socket, true);
  11945. shutdown_socket(socket);
  11946. close_socket(socket);
  11947. return false;
  11948. }
  11949. return true;
  11950. }
  11951. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  11952. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  11953. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  11954. if (!initialize_ssl(socket, error)) {
  11955. shutdown_socket(socket);
  11956. close_socket(socket);
  11957. return false;
  11958. }
  11959. return true;
  11960. }
  11961. // SSL HTTP client implementation
  11962. inline SSLClient::SSLClient(const std::string &host)
  11963. : SSLClient(host, 443, std::string(), std::string()) {}
  11964. inline SSLClient::SSLClient(const std::string &host, int port)
  11965. : SSLClient(host, port, std::string(), std::string()) {}
  11966. inline SSLClient::SSLClient(const std::string &host, int port,
  11967. const std::string &client_cert_path,
  11968. const std::string &client_key_path,
  11969. const std::string &private_key_password)
  11970. : ClientImpl(host, port, client_cert_path, client_key_path) {
  11971. ctx_ = tls::create_client_context();
  11972. if (!ctx_) { return; }
  11973. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  11974. if (!client_cert_path.empty() && !client_key_path.empty()) {
  11975. const char *password =
  11976. private_key_password.empty() ? nullptr : private_key_password.c_str();
  11977. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  11978. client_key_path.c_str(), password)) {
  11979. last_backend_error_ = tls::get_error();
  11980. tls::free_context(ctx_);
  11981. ctx_ = nullptr;
  11982. }
  11983. }
  11984. }
  11985. inline SSLClient::SSLClient(const std::string &host, int port,
  11986. const PemMemory &pem)
  11987. : ClientImpl(host, port) {
  11988. ctx_ = tls::create_client_context();
  11989. if (!ctx_) { return; }
  11990. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  11991. if (pem.cert_pem && pem.key_pem) {
  11992. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  11993. pem.private_key_password)) {
  11994. last_backend_error_ = tls::get_error();
  11995. tls::free_context(ctx_);
  11996. ctx_ = nullptr;
  11997. }
  11998. }
  11999. }
  12000. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  12001. if (ca_cert_store && ctx_) {
  12002. // set_ca_store takes ownership of ca_cert_store
  12003. tls::set_ca_store(ctx_, ca_cert_store);
  12004. } else if (ca_cert_store) {
  12005. tls::free_ca_store(ca_cert_store);
  12006. }
  12007. }
  12008. inline void
  12009. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  12010. if (!ctx_) { return; }
  12011. tls::set_verify_callback(ctx_, verifier);
  12012. }
  12013. inline void SSLClient::set_session_verifier(
  12014. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  12015. session_verifier_ = std::move(verifier);
  12016. }
  12017. #if defined(_WIN32) && \
  12018. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12019. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  12020. enable_windows_cert_verification_ = enabled;
  12021. }
  12022. #endif
  12023. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  12024. std::size_t size) {
  12025. if (ctx_ && ca_cert && size > 0) {
  12026. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  12027. tls::load_ca_pem(ctx_, ca_cert, size);
  12028. }
  12029. }
  12030. inline bool SSLClient::load_certs() {
  12031. auto ret = true;
  12032. std::call_once(initialize_cert_, [&]() {
  12033. std::lock_guard<std::mutex> guard(ctx_mutex_);
  12034. if (!ca_cert_file_path_.empty()) {
  12035. if (!tls::load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  12036. last_backend_error_ = tls::get_error();
  12037. ret = false;
  12038. }
  12039. } else if (!ca_cert_dir_path_.empty()) {
  12040. if (!tls::load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  12041. last_backend_error_ = tls::get_error();
  12042. ret = false;
  12043. }
  12044. } else if (ca_cert_pem_.empty()) {
  12045. if (!tls::load_system_certs(ctx_)) {
  12046. last_backend_error_ = tls::get_error();
  12047. }
  12048. }
  12049. });
  12050. return ret;
  12051. }
  12052. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  12053. using namespace tls;
  12054. // Load CA certificates if server verification is enabled
  12055. if (server_certificate_verification_) {
  12056. if (!load_certs()) {
  12057. error = Error::SSLLoadingCerts;
  12058. output_error_log(error, nullptr);
  12059. return false;
  12060. }
  12061. }
  12062. bool is_ip = detail::is_ip_address(host_);
  12063. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  12064. // MbedTLS needs explicit verification mode (OpenSSL uses SSL_VERIFY_NONE
  12065. // by default and performs all verification post-handshake).
  12066. // For IP addresses with verification enabled, use OPTIONAL mode since
  12067. // MbedTLS requires hostname for VERIFY_REQUIRED.
  12068. if (is_ip && server_certificate_verification_) {
  12069. set_verify_client(ctx_, false);
  12070. } else {
  12071. set_verify_client(ctx_, server_certificate_verification_);
  12072. }
  12073. #endif
  12074. // Create TLS session
  12075. session_t session = nullptr;
  12076. {
  12077. std::lock_guard<std::mutex> guard(ctx_mutex_);
  12078. session = create_session(ctx_, socket.sock);
  12079. }
  12080. if (!session) {
  12081. error = Error::SSLConnection;
  12082. last_backend_error_ = get_error();
  12083. return false;
  12084. }
  12085. // Use scope_exit to ensure session is freed on error paths
  12086. bool success = false;
  12087. auto session_guard = detail::scope_exit([&] {
  12088. if (!success) { free_session(session); }
  12089. });
  12090. // Set SNI extension (skip for IP addresses per RFC 6066).
  12091. // On MbedTLS, set_sni also enables hostname verification internally.
  12092. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  12093. if (!is_ip) {
  12094. if (!set_sni(session, host_.c_str())) {
  12095. error = Error::SSLConnection;
  12096. last_backend_error_ = get_error();
  12097. return false;
  12098. }
  12099. }
  12100. // Perform non-blocking TLS handshake with timeout
  12101. TlsError tls_err;
  12102. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  12103. connection_timeout_usec_, &tls_err)) {
  12104. last_ssl_error_ = static_cast<int>(tls_err.code);
  12105. last_backend_error_ = tls_err.backend_code;
  12106. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  12107. error = Error::SSLServerVerification;
  12108. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  12109. error = Error::SSLServerHostnameVerification;
  12110. } else {
  12111. error = Error::SSLConnection;
  12112. }
  12113. output_error_log(error, nullptr);
  12114. return false;
  12115. }
  12116. // Post-handshake session verifier callback
  12117. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  12118. if (session_verifier_) { verification_status = session_verifier_(session); }
  12119. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  12120. last_backend_error_ = get_error();
  12121. error = Error::SSLServerVerification;
  12122. output_error_log(error, nullptr);
  12123. return false;
  12124. }
  12125. // Default server certificate verification
  12126. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  12127. server_certificate_verification_) {
  12128. verify_result_ = tls::get_verify_result(session);
  12129. if (verify_result_ != 0) {
  12130. last_backend_error_ = static_cast<unsigned long>(verify_result_);
  12131. error = Error::SSLServerVerification;
  12132. output_error_log(error, nullptr);
  12133. return false;
  12134. }
  12135. auto server_cert = get_peer_cert(session);
  12136. if (!server_cert) {
  12137. last_backend_error_ = get_error();
  12138. error = Error::SSLServerVerification;
  12139. output_error_log(error, nullptr);
  12140. return false;
  12141. }
  12142. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  12143. // Hostname verification (post-handshake for all cases).
  12144. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  12145. // On MbedTLS, set_sni already enabled hostname verification during
  12146. // handshake for non-IP hosts, but this check is still needed for IP
  12147. // addresses where SNI is not set.
  12148. if (server_hostname_verification_) {
  12149. if (!verify_hostname(server_cert, host_.c_str())) {
  12150. last_backend_error_ = hostname_mismatch_code();
  12151. error = Error::SSLServerHostnameVerification;
  12152. output_error_log(error, nullptr);
  12153. return false;
  12154. }
  12155. }
  12156. #if defined(_WIN32) && \
  12157. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12158. // Additional Windows Schannel verification.
  12159. // This provides real-time certificate validation with Windows Update
  12160. // integration, working with both OpenSSL and MbedTLS backends.
  12161. // Skip when a custom CA cert is specified, as the Windows certificate
  12162. // store would not know about user-provided CA certificates.
  12163. if (enable_windows_cert_verification_ && ca_cert_file_path_.empty() &&
  12164. ca_cert_dir_path_.empty() && ca_cert_pem_.empty()) {
  12165. std::vector<unsigned char> der;
  12166. if (get_cert_der(server_cert, der)) {
  12167. unsigned long wincrypt_error = 0;
  12168. if (!detail::verify_cert_with_windows_schannel(
  12169. der, host_, server_hostname_verification_, wincrypt_error)) {
  12170. last_backend_error_ = wincrypt_error;
  12171. error = Error::SSLServerVerification;
  12172. output_error_log(error, nullptr);
  12173. return false;
  12174. }
  12175. }
  12176. }
  12177. #endif
  12178. }
  12179. success = true;
  12180. socket.ssl = session;
  12181. return true;
  12182. }
  12183. inline void Client::set_digest_auth(const std::string &username,
  12184. const std::string &password) {
  12185. cli_->set_digest_auth(username, password);
  12186. }
  12187. inline void Client::set_proxy_digest_auth(const std::string &username,
  12188. const std::string &password) {
  12189. cli_->set_proxy_digest_auth(username, password);
  12190. }
  12191. inline void Client::enable_server_certificate_verification(bool enabled) {
  12192. cli_->enable_server_certificate_verification(enabled);
  12193. }
  12194. inline void Client::enable_server_hostname_verification(bool enabled) {
  12195. cli_->enable_server_hostname_verification(enabled);
  12196. }
  12197. #if defined(_WIN32) && \
  12198. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12199. inline void Client::enable_windows_certificate_verification(bool enabled) {
  12200. if (is_ssl_) {
  12201. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  12202. enabled);
  12203. }
  12204. }
  12205. #endif
  12206. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  12207. const std::string &ca_cert_dir_path) {
  12208. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  12209. }
  12210. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  12211. if (is_ssl_) {
  12212. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  12213. } else if (ca_cert_store) {
  12214. tls::free_ca_store(ca_cert_store);
  12215. }
  12216. }
  12217. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  12218. set_ca_cert_store(tls::create_ca_store(ca_cert, size));
  12219. }
  12220. inline void
  12221. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  12222. if (is_ssl_) {
  12223. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  12224. std::move(verifier));
  12225. }
  12226. }
  12227. inline void Client::set_session_verifier(
  12228. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  12229. if (is_ssl_) {
  12230. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  12231. }
  12232. }
  12233. inline tls::ctx_t Client::tls_context() const {
  12234. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  12235. return nullptr;
  12236. }
  12237. #endif // CPPHTTPLIB_SSL_ENABLED
  12238. /*
  12239. * Group 7: TLS abstraction layer - Common API
  12240. */
  12241. #ifdef CPPHTTPLIB_SSL_ENABLED
  12242. namespace tls {
  12243. // Helper for PeerCert construction
  12244. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  12245. return PeerCert(get_peer_cert(session));
  12246. }
  12247. namespace impl {
  12248. inline VerifyCallback &get_verify_callback() {
  12249. static thread_local VerifyCallback callback;
  12250. return callback;
  12251. }
  12252. inline VerifyCallback &get_mbedtls_verify_callback() {
  12253. static thread_local VerifyCallback callback;
  12254. return callback;
  12255. }
  12256. } // namespace impl
  12257. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  12258. const char *ca_dir) {
  12259. if (!ctx) { return false; }
  12260. bool success = true;
  12261. if (ca_file && *ca_file) {
  12262. if (!load_ca_file(ctx, ca_file)) { success = false; }
  12263. }
  12264. if (ca_dir && *ca_dir) {
  12265. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  12266. }
  12267. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12268. // Set CA list for client certificate request (CertificateRequest message)
  12269. if (ca_file && *ca_file) {
  12270. auto list = SSL_load_client_CA_file(ca_file);
  12271. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  12272. }
  12273. #endif
  12274. return success;
  12275. }
  12276. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  12277. const char *password) {
  12278. return set_client_cert_pem(ctx, cert, key, password);
  12279. }
  12280. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  12281. const char *key_path, const char *password) {
  12282. return set_client_cert_file(ctx, cert_path, key_path, password);
  12283. }
  12284. // PeerCert implementation
  12285. inline PeerCert::PeerCert() = default;
  12286. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  12287. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  12288. other.cert_ = nullptr;
  12289. }
  12290. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  12291. if (this != &other) {
  12292. if (cert_) { free_cert(cert_); }
  12293. cert_ = other.cert_;
  12294. other.cert_ = nullptr;
  12295. }
  12296. return *this;
  12297. }
  12298. inline PeerCert::~PeerCert() {
  12299. if (cert_) { free_cert(cert_); }
  12300. }
  12301. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  12302. inline std::string PeerCert::subject_cn() const {
  12303. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  12304. }
  12305. inline std::string PeerCert::issuer_name() const {
  12306. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  12307. }
  12308. inline bool PeerCert::check_hostname(const char *hostname) const {
  12309. return cert_ ? verify_hostname(cert_, hostname) : false;
  12310. }
  12311. inline std::vector<SanEntry> PeerCert::sans() const {
  12312. std::vector<SanEntry> result;
  12313. if (cert_) { get_cert_sans(cert_, result); }
  12314. return result;
  12315. }
  12316. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  12317. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  12318. }
  12319. inline std::string PeerCert::serial() const {
  12320. return cert_ ? get_cert_serial(cert_) : std::string();
  12321. }
  12322. // VerifyContext method implementations
  12323. inline std::string VerifyContext::subject_cn() const {
  12324. return cert ? get_cert_subject_cn(cert) : std::string();
  12325. }
  12326. inline std::string VerifyContext::issuer_name() const {
  12327. return cert ? get_cert_issuer_name(cert) : std::string();
  12328. }
  12329. inline bool VerifyContext::check_hostname(const char *hostname) const {
  12330. return cert ? verify_hostname(cert, hostname) : false;
  12331. }
  12332. inline std::vector<SanEntry> VerifyContext::sans() const {
  12333. std::vector<SanEntry> result;
  12334. if (cert) { get_cert_sans(cert, result); }
  12335. return result;
  12336. }
  12337. inline bool VerifyContext::validity(time_t &not_before,
  12338. time_t &not_after) const {
  12339. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  12340. }
  12341. inline std::string VerifyContext::serial() const {
  12342. return cert ? get_cert_serial(cert) : std::string();
  12343. }
  12344. // TlsError static method implementation
  12345. inline std::string TlsError::verify_error_to_string(long error_code) {
  12346. return verify_error_string(error_code);
  12347. }
  12348. } // namespace tls
  12349. // Request::peer_cert() implementation
  12350. inline tls::PeerCert Request::peer_cert() const {
  12351. return tls::get_peer_cert_from_session(ssl);
  12352. }
  12353. // Request::sni() implementation
  12354. inline std::string Request::sni() const {
  12355. if (!ssl) { return std::string(); }
  12356. const char *s = tls::get_sni(ssl);
  12357. return s ? std::string(s) : std::string();
  12358. }
  12359. #endif // CPPHTTPLIB_SSL_ENABLED
  12360. /*
  12361. * Group 8: TLS abstraction layer - OpenSSL backend
  12362. */
  12363. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12364. inline SSL_CTX *Client::ssl_context() const {
  12365. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  12366. return nullptr;
  12367. }
  12368. inline void Client::set_server_certificate_verifier(
  12369. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  12370. cli_->set_server_certificate_verifier(verifier);
  12371. }
  12372. inline long Client::get_verify_result() const {
  12373. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).get_verify_result(); }
  12374. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  12375. }
  12376. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  12377. /*
  12378. * OpenSSL Backend Implementation
  12379. */
  12380. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12381. namespace tls {
  12382. namespace impl {
  12383. // OpenSSL-specific helpers for converting native types to PEM
  12384. inline std::string x509_to_pem(X509 *cert) {
  12385. if (!cert) return {};
  12386. BIO *bio = BIO_new(BIO_s_mem());
  12387. if (!bio) return {};
  12388. if (PEM_write_bio_X509(bio, cert) != 1) {
  12389. BIO_free(bio);
  12390. return {};
  12391. }
  12392. char *data = nullptr;
  12393. long len = BIO_get_mem_data(bio, &data);
  12394. std::string pem(data, static_cast<size_t>(len));
  12395. BIO_free(bio);
  12396. return pem;
  12397. }
  12398. inline std::string evp_pkey_to_pem(EVP_PKEY *key) {
  12399. if (!key) return {};
  12400. BIO *bio = BIO_new(BIO_s_mem());
  12401. if (!bio) return {};
  12402. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr,
  12403. nullptr) != 1) {
  12404. BIO_free(bio);
  12405. return {};
  12406. }
  12407. char *data = nullptr;
  12408. long len = BIO_get_mem_data(bio, &data);
  12409. std::string pem(data, static_cast<size_t>(len));
  12410. BIO_free(bio);
  12411. return pem;
  12412. }
  12413. inline std::string x509_store_to_pem(X509_STORE *store) {
  12414. if (!store) return {};
  12415. std::string pem;
  12416. auto objs = X509_STORE_get0_objects(store);
  12417. if (!objs) return {};
  12418. auto count = sk_X509_OBJECT_num(objs);
  12419. for (decltype(count) i = 0; i < count; i++) {
  12420. auto obj = sk_X509_OBJECT_value(objs, i);
  12421. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  12422. auto cert = X509_OBJECT_get0_X509(obj);
  12423. if (cert) { pem += x509_to_pem(cert); }
  12424. }
  12425. }
  12426. return pem;
  12427. }
  12428. // Helper to map OpenSSL SSL_get_error to ErrorCode
  12429. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  12430. switch (ssl_error) {
  12431. case SSL_ERROR_NONE: return ErrorCode::Success;
  12432. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  12433. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  12434. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  12435. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  12436. case SSL_ERROR_SSL:
  12437. default: return ErrorCode::Fatal;
  12438. }
  12439. }
  12440. // Helper: Create client CA list from PEM string
  12441. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  12442. // Caller takes ownership of returned list
  12443. inline STACK_OF(X509_NAME) *
  12444. create_client_ca_list_from_pem(const char *ca_pem) {
  12445. if (!ca_pem) { return nullptr; }
  12446. auto ca_list = sk_X509_NAME_new_null();
  12447. if (!ca_list) { return nullptr; }
  12448. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  12449. if (!bio) {
  12450. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  12451. return nullptr;
  12452. }
  12453. X509 *cert = nullptr;
  12454. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  12455. nullptr) {
  12456. X509_NAME *name = X509_get_subject_name(cert);
  12457. if (name) { sk_X509_NAME_push(ca_list, X509_NAME_dup(name)); }
  12458. X509_free(cert);
  12459. }
  12460. BIO_free(bio);
  12461. return ca_list;
  12462. }
  12463. // Helper: Extract CA names from X509_STORE
  12464. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  12465. // Caller takes ownership of returned list
  12466. inline STACK_OF(X509_NAME) *
  12467. extract_client_ca_list_from_store(X509_STORE *store) {
  12468. if (!store) { return nullptr; }
  12469. auto ca_list = sk_X509_NAME_new_null();
  12470. if (!ca_list) { return nullptr; }
  12471. auto objs = X509_STORE_get0_objects(store);
  12472. if (!objs) {
  12473. sk_X509_NAME_free(ca_list);
  12474. return nullptr;
  12475. }
  12476. auto count = sk_X509_OBJECT_num(objs);
  12477. for (decltype(count) i = 0; i < count; i++) {
  12478. auto obj = sk_X509_OBJECT_value(objs, i);
  12479. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  12480. auto cert = X509_OBJECT_get0_X509(obj);
  12481. if (cert) {
  12482. auto subject = X509_get_subject_name(cert);
  12483. if (subject) {
  12484. auto name_dup = X509_NAME_dup(subject);
  12485. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  12486. }
  12487. }
  12488. }
  12489. }
  12490. if (sk_X509_NAME_num(ca_list) == 0) {
  12491. sk_X509_NAME_free(ca_list);
  12492. return nullptr;
  12493. }
  12494. return ca_list;
  12495. }
  12496. // OpenSSL verify callback wrapper
  12497. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  12498. auto &callback = get_verify_callback();
  12499. if (!callback) { return preverify_ok; }
  12500. // Get SSL object from X509_STORE_CTX
  12501. auto ssl = static_cast<SSL *>(
  12502. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  12503. if (!ssl) { return preverify_ok; }
  12504. // Get current certificate and depth
  12505. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  12506. int depth = X509_STORE_CTX_get_error_depth(ctx);
  12507. int error = X509_STORE_CTX_get_error(ctx);
  12508. // Build context
  12509. VerifyContext verify_ctx;
  12510. verify_ctx.session = static_cast<session_t>(ssl);
  12511. verify_ctx.cert = static_cast<cert_t>(cert);
  12512. verify_ctx.depth = depth;
  12513. verify_ctx.preverify_ok = (preverify_ok != 0);
  12514. verify_ctx.error_code = error;
  12515. verify_ctx.error_string =
  12516. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  12517. return callback(verify_ctx) ? 1 : 0;
  12518. }
  12519. } // namespace impl
  12520. inline ctx_t create_client_context() {
  12521. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  12522. if (ctx) {
  12523. // Disable auto-retry to properly handle non-blocking I/O
  12524. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  12525. // Set minimum TLS version
  12526. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  12527. }
  12528. return static_cast<ctx_t>(ctx);
  12529. }
  12530. inline void free_context(ctx_t ctx) {
  12531. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  12532. }
  12533. inline bool set_min_version(ctx_t ctx, Version version) {
  12534. if (!ctx) return false;
  12535. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  12536. static_cast<int>(version)) == 1;
  12537. }
  12538. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  12539. if (!ctx || !pem || len == 0) return false;
  12540. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12541. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12542. if (!store) return false;
  12543. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  12544. if (!bio) return false;
  12545. bool ok = true;
  12546. X509 *cert = nullptr;
  12547. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  12548. nullptr) {
  12549. if (X509_STORE_add_cert(store, cert) != 1) {
  12550. // Ignore duplicate errors
  12551. auto err = ERR_peek_last_error();
  12552. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  12553. ok = false;
  12554. }
  12555. }
  12556. X509_free(cert);
  12557. if (!ok) break;
  12558. }
  12559. BIO_free(bio);
  12560. // Clear any "no more certificates" errors
  12561. ERR_clear_error();
  12562. return ok;
  12563. }
  12564. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  12565. if (!ctx || !file_path) return false;
  12566. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  12567. nullptr) == 1;
  12568. }
  12569. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  12570. if (!ctx || !dir_path) return false;
  12571. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  12572. dir_path) == 1;
  12573. }
  12574. inline bool load_system_certs(ctx_t ctx) {
  12575. if (!ctx) return false;
  12576. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12577. #ifdef _WIN32
  12578. // Windows: Load from system certificate store (ROOT and CA)
  12579. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12580. if (!store) return false;
  12581. bool loaded_any = false;
  12582. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  12583. for (auto store_name : store_names) {
  12584. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  12585. if (!hStore) continue;
  12586. PCCERT_CONTEXT pContext = nullptr;
  12587. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  12588. nullptr) {
  12589. const unsigned char *data = pContext->pbCertEncoded;
  12590. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  12591. if (x509) {
  12592. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  12593. X509_free(x509);
  12594. }
  12595. }
  12596. CertCloseStore(hStore, 0);
  12597. }
  12598. return loaded_any;
  12599. #elif defined(__APPLE__)
  12600. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  12601. // macOS: Load from Keychain
  12602. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12603. if (!store) return false;
  12604. CFArrayRef certs = nullptr;
  12605. if (SecTrustCopyAnchorCertificates(&certs) != errSecSuccess || !certs) {
  12606. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12607. }
  12608. bool loaded_any = false;
  12609. auto count = CFArrayGetCount(certs);
  12610. for (CFIndex i = 0; i < count; i++) {
  12611. auto cert = reinterpret_cast<SecCertificateRef>(
  12612. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  12613. CFDataRef der = SecCertificateCopyData(cert);
  12614. if (der) {
  12615. const unsigned char *data = CFDataGetBytePtr(der);
  12616. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  12617. if (x509) {
  12618. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  12619. X509_free(x509);
  12620. }
  12621. CFRelease(der);
  12622. }
  12623. }
  12624. CFRelease(certs);
  12625. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12626. #else
  12627. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12628. #endif
  12629. #else
  12630. // Other Unix: use default verify paths
  12631. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12632. #endif
  12633. }
  12634. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  12635. const char *password) {
  12636. if (!ctx || !cert || !key) return false;
  12637. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12638. // Load certificate
  12639. auto cert_bio = BIO_new_mem_buf(cert, -1);
  12640. if (!cert_bio) return false;
  12641. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  12642. BIO_free(cert_bio);
  12643. if (!x509) return false;
  12644. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  12645. X509_free(x509);
  12646. if (!cert_ok) return false;
  12647. // Load private key
  12648. auto key_bio = BIO_new_mem_buf(key, -1);
  12649. if (!key_bio) return false;
  12650. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  12651. password ? const_cast<char *>(password)
  12652. : nullptr);
  12653. BIO_free(key_bio);
  12654. if (!pkey) return false;
  12655. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  12656. EVP_PKEY_free(pkey);
  12657. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  12658. }
  12659. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  12660. const char *key_path, const char *password) {
  12661. if (!ctx || !cert_path || !key_path) return false;
  12662. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12663. if (password && password[0] != '\0') {
  12664. SSL_CTX_set_default_passwd_cb_userdata(
  12665. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  12666. }
  12667. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  12668. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  12669. }
  12670. inline ctx_t create_server_context() {
  12671. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12672. if (ctx) {
  12673. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  12674. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12675. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  12676. }
  12677. return static_cast<ctx_t>(ctx);
  12678. }
  12679. inline void set_verify_client(ctx_t ctx, bool require) {
  12680. if (!ctx) return;
  12681. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  12682. require
  12683. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  12684. : SSL_VERIFY_NONE,
  12685. nullptr);
  12686. }
  12687. inline session_t create_session(ctx_t ctx, socket_t sock) {
  12688. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  12689. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12690. SSL *ssl = SSL_new(ssl_ctx);
  12691. if (!ssl) return nullptr;
  12692. // Disable auto-retry for proper non-blocking I/O handling
  12693. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  12694. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  12695. if (!bio) {
  12696. SSL_free(ssl);
  12697. return nullptr;
  12698. }
  12699. SSL_set_bio(ssl, bio, bio);
  12700. return static_cast<session_t>(ssl);
  12701. }
  12702. inline void free_session(session_t session) {
  12703. if (session) { SSL_free(static_cast<SSL *>(session)); }
  12704. }
  12705. inline bool set_sni(session_t session, const char *hostname) {
  12706. if (!session || !hostname) return false;
  12707. auto ssl = static_cast<SSL *>(session);
  12708. // Set SNI (Server Name Indication) only - does not enable verification
  12709. #if defined(OPENSSL_IS_BORINGSSL)
  12710. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  12711. #else
  12712. // Direct call instead of macro to suppress -Wold-style-cast warning
  12713. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  12714. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  12715. #endif
  12716. }
  12717. inline bool set_hostname(session_t session, const char *hostname) {
  12718. if (!session || !hostname) return false;
  12719. auto ssl = static_cast<SSL *>(session);
  12720. // Set SNI (Server Name Indication)
  12721. if (!set_sni(session, hostname)) { return false; }
  12722. // Enable hostname verification
  12723. auto param = SSL_get0_param(ssl);
  12724. if (!param) return false;
  12725. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  12726. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  12727. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  12728. return true;
  12729. }
  12730. inline TlsError connect(session_t session) {
  12731. if (!session) { return TlsError(); }
  12732. auto ssl = static_cast<SSL *>(session);
  12733. auto ret = SSL_connect(ssl);
  12734. TlsError err;
  12735. if (ret == 1) {
  12736. err.code = ErrorCode::Success;
  12737. } else {
  12738. auto ssl_err = SSL_get_error(ssl, ret);
  12739. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12740. err.backend_code = ERR_get_error();
  12741. }
  12742. return err;
  12743. }
  12744. inline TlsError accept(session_t session) {
  12745. if (!session) { return TlsError(); }
  12746. auto ssl = static_cast<SSL *>(session);
  12747. auto ret = SSL_accept(ssl);
  12748. TlsError err;
  12749. if (ret == 1) {
  12750. err.code = ErrorCode::Success;
  12751. } else {
  12752. auto ssl_err = SSL_get_error(ssl, ret);
  12753. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12754. err.backend_code = ERR_get_error();
  12755. }
  12756. return err;
  12757. }
  12758. inline bool connect_nonblocking(session_t session, socket_t sock,
  12759. time_t timeout_sec, time_t timeout_usec,
  12760. TlsError *err) {
  12761. if (!session) {
  12762. if (err) { err->code = ErrorCode::Fatal; }
  12763. return false;
  12764. }
  12765. auto ssl = static_cast<SSL *>(session);
  12766. auto bio = SSL_get_rbio(ssl);
  12767. // Set non-blocking mode for handshake
  12768. detail::set_nonblocking(sock, true);
  12769. if (bio) { BIO_set_nbio(bio, 1); }
  12770. auto cleanup = detail::scope_exit([&]() {
  12771. // Restore blocking mode after handshake
  12772. if (bio) { BIO_set_nbio(bio, 0); }
  12773. detail::set_nonblocking(sock, false);
  12774. });
  12775. auto res = 0;
  12776. while ((res = SSL_connect(ssl)) != 1) {
  12777. auto ssl_err = SSL_get_error(ssl, res);
  12778. switch (ssl_err) {
  12779. case SSL_ERROR_WANT_READ:
  12780. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  12781. continue;
  12782. }
  12783. break;
  12784. case SSL_ERROR_WANT_WRITE:
  12785. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  12786. continue;
  12787. }
  12788. break;
  12789. default: break;
  12790. }
  12791. if (err) {
  12792. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  12793. err->backend_code = ERR_get_error();
  12794. }
  12795. return false;
  12796. }
  12797. if (err) { err->code = ErrorCode::Success; }
  12798. return true;
  12799. }
  12800. inline bool accept_nonblocking(session_t session, socket_t sock,
  12801. time_t timeout_sec, time_t timeout_usec,
  12802. TlsError *err) {
  12803. if (!session) {
  12804. if (err) { err->code = ErrorCode::Fatal; }
  12805. return false;
  12806. }
  12807. auto ssl = static_cast<SSL *>(session);
  12808. auto bio = SSL_get_rbio(ssl);
  12809. // Set non-blocking mode for handshake
  12810. detail::set_nonblocking(sock, true);
  12811. if (bio) { BIO_set_nbio(bio, 1); }
  12812. auto cleanup = detail::scope_exit([&]() {
  12813. // Restore blocking mode after handshake
  12814. if (bio) { BIO_set_nbio(bio, 0); }
  12815. detail::set_nonblocking(sock, false);
  12816. });
  12817. auto res = 0;
  12818. while ((res = SSL_accept(ssl)) != 1) {
  12819. auto ssl_err = SSL_get_error(ssl, res);
  12820. switch (ssl_err) {
  12821. case SSL_ERROR_WANT_READ:
  12822. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  12823. continue;
  12824. }
  12825. break;
  12826. case SSL_ERROR_WANT_WRITE:
  12827. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  12828. continue;
  12829. }
  12830. break;
  12831. default: break;
  12832. }
  12833. if (err) {
  12834. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  12835. err->backend_code = ERR_get_error();
  12836. }
  12837. return false;
  12838. }
  12839. if (err) { err->code = ErrorCode::Success; }
  12840. return true;
  12841. }
  12842. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  12843. if (!session || !buf) {
  12844. err.code = ErrorCode::Fatal;
  12845. return -1;
  12846. }
  12847. auto ssl = static_cast<SSL *>(session);
  12848. constexpr auto max_len =
  12849. static_cast<size_t>((std::numeric_limits<int>::max)());
  12850. if (len > max_len) { len = max_len; }
  12851. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  12852. if (ret > 0) {
  12853. err.code = ErrorCode::Success;
  12854. return ret;
  12855. }
  12856. auto ssl_err = SSL_get_error(ssl, ret);
  12857. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12858. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  12859. return -1;
  12860. }
  12861. inline ssize_t write(session_t session, const void *buf, size_t len,
  12862. TlsError &err) {
  12863. if (!session || !buf) {
  12864. err.code = ErrorCode::Fatal;
  12865. return -1;
  12866. }
  12867. auto ssl = static_cast<SSL *>(session);
  12868. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  12869. if (ret > 0) {
  12870. err.code = ErrorCode::Success;
  12871. return ret;
  12872. }
  12873. auto ssl_err = SSL_get_error(ssl, ret);
  12874. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12875. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  12876. return -1;
  12877. }
  12878. inline int pending(const_session_t session) {
  12879. if (!session) return 0;
  12880. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  12881. }
  12882. inline void shutdown(session_t session, bool graceful) {
  12883. if (!session) return;
  12884. auto ssl = static_cast<SSL *>(session);
  12885. if (graceful) {
  12886. // First call sends close_notify
  12887. if (SSL_shutdown(ssl) == 0) {
  12888. // Second call waits for peer's close_notify
  12889. SSL_shutdown(ssl);
  12890. }
  12891. }
  12892. }
  12893. inline bool is_peer_closed(session_t session, socket_t sock) {
  12894. if (!session) return true;
  12895. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  12896. detail::set_nonblocking(sock, true);
  12897. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  12898. auto ssl = static_cast<SSL *>(session);
  12899. char buf;
  12900. auto ret = SSL_peek(ssl, &buf, 1);
  12901. if (ret > 0) return false;
  12902. auto err = SSL_get_error(ssl, ret);
  12903. return err == SSL_ERROR_ZERO_RETURN;
  12904. }
  12905. inline cert_t get_peer_cert(const_session_t session) {
  12906. if (!session) return nullptr;
  12907. return static_cast<cert_t>(SSL_get1_peer_certificate(
  12908. static_cast<SSL *>(const_cast<void *>(session))));
  12909. }
  12910. inline void free_cert(cert_t cert) {
  12911. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  12912. }
  12913. inline bool verify_hostname(cert_t cert, const char *hostname) {
  12914. if (!cert || !hostname) return false;
  12915. auto x509 = static_cast<X509 *>(cert);
  12916. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  12917. if (detail::is_ip_address(hostname)) {
  12918. return X509_check_ip_asc(x509, hostname, 0) == 1;
  12919. }
  12920. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  12921. }
  12922. inline uint64_t hostname_mismatch_code() {
  12923. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  12924. }
  12925. inline long get_verify_result(const_session_t session) {
  12926. if (!session) return X509_V_ERR_UNSPECIFIED;
  12927. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  12928. }
  12929. inline std::string get_cert_subject_cn(cert_t cert) {
  12930. if (!cert) return "";
  12931. auto x509 = static_cast<X509 *>(cert);
  12932. auto subject_name = X509_get_subject_name(x509);
  12933. if (!subject_name) return "";
  12934. char buf[256];
  12935. auto len =
  12936. X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf, sizeof(buf));
  12937. if (len < 0) return "";
  12938. return std::string(buf, static_cast<size_t>(len));
  12939. }
  12940. inline std::string get_cert_issuer_name(cert_t cert) {
  12941. if (!cert) return "";
  12942. auto x509 = static_cast<X509 *>(cert);
  12943. auto issuer_name = X509_get_issuer_name(x509);
  12944. if (!issuer_name) return "";
  12945. char buf[256];
  12946. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  12947. return std::string(buf);
  12948. }
  12949. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  12950. sans.clear();
  12951. if (!cert) return false;
  12952. auto x509 = static_cast<X509 *>(cert);
  12953. auto names = static_cast<GENERAL_NAMES *>(
  12954. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  12955. if (!names) return true; // No SANs is valid
  12956. auto count = sk_GENERAL_NAME_num(names);
  12957. for (int i = 0; i < count; i++) {
  12958. auto gen = sk_GENERAL_NAME_value(names, i);
  12959. if (!gen) continue;
  12960. SanEntry entry;
  12961. switch (gen->type) {
  12962. case GEN_DNS:
  12963. entry.type = SanType::DNS;
  12964. if (gen->d.dNSName) {
  12965. entry.value = std::string(
  12966. reinterpret_cast<const char *>(
  12967. ASN1_STRING_get0_data(gen->d.dNSName)),
  12968. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  12969. }
  12970. break;
  12971. case GEN_IPADD:
  12972. entry.type = SanType::IP;
  12973. if (gen->d.iPAddress) {
  12974. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  12975. auto len = ASN1_STRING_length(gen->d.iPAddress);
  12976. if (len == 4) {
  12977. // IPv4
  12978. char buf[INET_ADDRSTRLEN];
  12979. inet_ntop(AF_INET, data, buf, sizeof(buf));
  12980. entry.value = buf;
  12981. } else if (len == 16) {
  12982. // IPv6
  12983. char buf[INET6_ADDRSTRLEN];
  12984. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  12985. entry.value = buf;
  12986. }
  12987. }
  12988. break;
  12989. case GEN_EMAIL:
  12990. entry.type = SanType::EMAIL;
  12991. if (gen->d.rfc822Name) {
  12992. entry.value = std::string(
  12993. reinterpret_cast<const char *>(
  12994. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  12995. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  12996. }
  12997. break;
  12998. case GEN_URI:
  12999. entry.type = SanType::URI;
  13000. if (gen->d.uniformResourceIdentifier) {
  13001. entry.value = std::string(
  13002. reinterpret_cast<const char *>(
  13003. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  13004. static_cast<size_t>(
  13005. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  13006. }
  13007. break;
  13008. default: entry.type = SanType::OTHER; break;
  13009. }
  13010. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  13011. }
  13012. GENERAL_NAMES_free(names);
  13013. return true;
  13014. }
  13015. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  13016. time_t &not_after) {
  13017. if (!cert) return false;
  13018. auto x509 = static_cast<X509 *>(cert);
  13019. auto nb = X509_get0_notBefore(x509);
  13020. auto na = X509_get0_notAfter(x509);
  13021. if (!nb || !na) return false;
  13022. ASN1_TIME *epoch = ASN1_TIME_new();
  13023. if (!epoch) return false;
  13024. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  13025. if (!ASN1_TIME_set(epoch, 0)) return false;
  13026. int pday, psec;
  13027. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  13028. not_before = 86400 * (time_t)pday + psec;
  13029. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  13030. not_after = 86400 * (time_t)pday + psec;
  13031. return true;
  13032. }
  13033. inline std::string get_cert_serial(cert_t cert) {
  13034. if (!cert) return "";
  13035. auto x509 = static_cast<X509 *>(cert);
  13036. auto serial = X509_get_serialNumber(x509);
  13037. if (!serial) return "";
  13038. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  13039. if (!bn) return "";
  13040. auto hex = BN_bn2hex(bn);
  13041. BN_free(bn);
  13042. if (!hex) return "";
  13043. std::string result(hex);
  13044. OPENSSL_free(hex);
  13045. return result;
  13046. }
  13047. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  13048. if (!cert) return false;
  13049. auto x509 = static_cast<X509 *>(cert);
  13050. auto len = i2d_X509(x509, nullptr);
  13051. if (len < 0) return false;
  13052. der.resize(static_cast<size_t>(len));
  13053. auto p = der.data();
  13054. i2d_X509(x509, &p);
  13055. return true;
  13056. }
  13057. inline const char *get_sni(const_session_t session) {
  13058. if (!session) return nullptr;
  13059. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  13060. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13061. }
  13062. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  13063. inline uint64_t get_error() { return ERR_get_error(); }
  13064. inline std::string error_string(uint64_t code) {
  13065. char buf[256];
  13066. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  13067. return std::string(buf);
  13068. }
  13069. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  13070. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  13071. if (!mem) { return nullptr; }
  13072. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  13073. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  13074. if (!inf) { return nullptr; }
  13075. auto store = X509_STORE_new();
  13076. if (store) {
  13077. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  13078. auto itmp = sk_X509_INFO_value(inf, i);
  13079. if (!itmp) { continue; }
  13080. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  13081. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  13082. }
  13083. }
  13084. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  13085. return static_cast<ca_store_t>(store);
  13086. }
  13087. inline void free_ca_store(ca_store_t store) {
  13088. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  13089. }
  13090. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  13091. if (!ctx || !store) { return false; }
  13092. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13093. auto x509_store = static_cast<X509_STORE *>(store);
  13094. // Check if same store is already set
  13095. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  13096. // SSL_CTX_set_cert_store takes ownership and frees the old store
  13097. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  13098. return true;
  13099. }
  13100. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  13101. certs.clear();
  13102. if (!ctx) { return 0; }
  13103. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13104. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13105. if (!store) { return 0; }
  13106. auto objs = X509_STORE_get0_objects(store);
  13107. if (!objs) { return 0; }
  13108. auto count = sk_X509_OBJECT_num(objs);
  13109. for (decltype(count) i = 0; i < count; i++) {
  13110. auto obj = sk_X509_OBJECT_value(objs, i);
  13111. if (!obj) { continue; }
  13112. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13113. auto x509 = X509_OBJECT_get0_X509(obj);
  13114. if (x509) {
  13115. // Increment reference count so caller can free it
  13116. X509_up_ref(x509);
  13117. certs.push_back(static_cast<cert_t>(x509));
  13118. }
  13119. }
  13120. }
  13121. return certs.size();
  13122. }
  13123. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  13124. std::vector<std::string> names;
  13125. if (!ctx) { return names; }
  13126. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13127. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13128. if (!store) { return names; }
  13129. auto objs = X509_STORE_get0_objects(store);
  13130. if (!objs) { return names; }
  13131. auto count = sk_X509_OBJECT_num(objs);
  13132. for (decltype(count) i = 0; i < count; i++) {
  13133. auto obj = sk_X509_OBJECT_value(objs, i);
  13134. if (!obj) { continue; }
  13135. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13136. auto x509 = X509_OBJECT_get0_X509(obj);
  13137. if (x509) {
  13138. auto subject = X509_get_subject_name(x509);
  13139. if (subject) {
  13140. char buf[512];
  13141. X509_NAME_oneline(subject, buf, sizeof(buf));
  13142. names.push_back(buf);
  13143. }
  13144. }
  13145. }
  13146. }
  13147. return names;
  13148. }
  13149. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  13150. const char *key_pem, const char *password) {
  13151. if (!ctx || !cert_pem || !key_pem) { return false; }
  13152. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13153. // Load certificate from PEM
  13154. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  13155. if (!cert_bio) { return false; }
  13156. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  13157. BIO_free(cert_bio);
  13158. if (!cert) { return false; }
  13159. // Load private key from PEM
  13160. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  13161. if (!key_bio) {
  13162. X509_free(cert);
  13163. return false;
  13164. }
  13165. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  13166. password ? const_cast<char *>(password)
  13167. : nullptr);
  13168. BIO_free(key_bio);
  13169. if (!key) {
  13170. X509_free(cert);
  13171. return false;
  13172. }
  13173. // Update certificate and key
  13174. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  13175. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  13176. X509_free(cert);
  13177. EVP_PKEY_free(key);
  13178. return ret;
  13179. }
  13180. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  13181. if (!ctx || !ca_pem) { return false; }
  13182. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13183. // Create new X509_STORE from PEM
  13184. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  13185. if (!store) { return false; }
  13186. // SSL_CTX_set_cert_store takes ownership
  13187. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  13188. // Set client CA list for client certificate request
  13189. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  13190. if (ca_list) {
  13191. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  13192. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  13193. }
  13194. return true;
  13195. }
  13196. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  13197. if (!ctx) { return false; }
  13198. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13199. impl::get_verify_callback() = std::move(callback);
  13200. if (impl::get_verify_callback()) {
  13201. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  13202. } else {
  13203. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  13204. }
  13205. return true;
  13206. }
  13207. inline long get_verify_error(const_session_t session) {
  13208. if (!session) { return -1; }
  13209. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  13210. return SSL_get_verify_result(ssl);
  13211. }
  13212. inline std::string verify_error_string(long error_code) {
  13213. if (error_code == X509_V_OK) { return ""; }
  13214. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  13215. return str ? str : "unknown error";
  13216. }
  13217. namespace impl {
  13218. // OpenSSL-specific helpers for public API wrappers
  13219. inline ctx_t create_server_context_from_x509(X509 *cert, EVP_PKEY *key,
  13220. X509_STORE *client_ca_store,
  13221. int &out_error) {
  13222. out_error = 0;
  13223. auto cert_pem = x509_to_pem(cert);
  13224. auto key_pem = evp_pkey_to_pem(key);
  13225. if (cert_pem.empty() || key_pem.empty()) {
  13226. out_error = static_cast<int>(ERR_get_error());
  13227. return nullptr;
  13228. }
  13229. auto ctx = create_server_context();
  13230. if (!ctx) {
  13231. out_error = static_cast<int>(get_error());
  13232. return nullptr;
  13233. }
  13234. if (!set_server_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr)) {
  13235. out_error = static_cast<int>(get_error());
  13236. free_context(ctx);
  13237. return nullptr;
  13238. }
  13239. if (client_ca_store) {
  13240. // Set cert store for verification (SSL_CTX_set_cert_store takes ownership)
  13241. SSL_CTX_set_cert_store(static_cast<SSL_CTX *>(ctx), client_ca_store);
  13242. // Extract and set client CA list directly from store (more efficient than
  13243. // PEM conversion)
  13244. auto ca_list = extract_client_ca_list_from_store(client_ca_store);
  13245. if (ca_list) {
  13246. SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), ca_list);
  13247. }
  13248. set_verify_client(ctx, true);
  13249. }
  13250. return ctx;
  13251. }
  13252. inline void update_server_certs_from_x509(ctx_t ctx, X509 *cert, EVP_PKEY *key,
  13253. X509_STORE *client_ca_store) {
  13254. auto cert_pem = x509_to_pem(cert);
  13255. auto key_pem = evp_pkey_to_pem(key);
  13256. if (!cert_pem.empty() && !key_pem.empty()) {
  13257. update_server_cert(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr);
  13258. }
  13259. if (client_ca_store) {
  13260. auto ca_pem = x509_store_to_pem(client_ca_store);
  13261. if (!ca_pem.empty()) { update_server_client_ca(ctx, ca_pem.c_str()); }
  13262. X509_STORE_free(client_ca_store);
  13263. }
  13264. }
  13265. inline ctx_t create_client_context_from_x509(X509 *cert, EVP_PKEY *key,
  13266. const char *password,
  13267. unsigned long &out_error) {
  13268. out_error = 0;
  13269. auto ctx = create_client_context();
  13270. if (!ctx) {
  13271. out_error = static_cast<unsigned long>(get_error());
  13272. return nullptr;
  13273. }
  13274. if (cert && key) {
  13275. auto cert_pem = x509_to_pem(cert);
  13276. auto key_pem = evp_pkey_to_pem(key);
  13277. if (cert_pem.empty() || key_pem.empty()) {
  13278. out_error = ERR_get_error();
  13279. free_context(ctx);
  13280. return nullptr;
  13281. }
  13282. if (!set_client_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  13283. password)) {
  13284. out_error = static_cast<unsigned long>(get_error());
  13285. free_context(ctx);
  13286. return nullptr;
  13287. }
  13288. }
  13289. return ctx;
  13290. }
  13291. } // namespace impl
  13292. } // namespace tls
  13293. // ClientImpl::set_ca_cert_store - defined here to use
  13294. // tls::impl::x509_store_to_pem Deprecated: converts X509_STORE to PEM and
  13295. // stores for redirect transfer
  13296. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  13297. if (ca_cert_store) {
  13298. ca_cert_pem_ = tls::impl::x509_store_to_pem(ca_cert_store);
  13299. }
  13300. }
  13301. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  13302. X509_STORE *client_ca_cert_store) {
  13303. ctx_ = tls::impl::create_server_context_from_x509(
  13304. cert, private_key, client_ca_cert_store, last_ssl_error_);
  13305. }
  13306. inline SSLServer::SSLServer(
  13307. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  13308. // Use abstract API to create context
  13309. ctx_ = tls::create_server_context();
  13310. if (ctx_) {
  13311. // Pass to OpenSSL-specific callback (ctx_ is SSL_CTX* internally)
  13312. auto ssl_ctx = static_cast<SSL_CTX *>(ctx_);
  13313. if (!setup_ssl_ctx_callback(*ssl_ctx)) {
  13314. tls::free_context(ctx_);
  13315. ctx_ = nullptr;
  13316. }
  13317. }
  13318. }
  13319. inline SSL_CTX *SSLServer::ssl_context() const {
  13320. return static_cast<SSL_CTX *>(ctx_);
  13321. }
  13322. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  13323. X509_STORE *client_ca_cert_store) {
  13324. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13325. tls::impl::update_server_certs_from_x509(ctx_, cert, private_key,
  13326. client_ca_cert_store);
  13327. }
  13328. inline SSLClient::SSLClient(const std::string &host, int port,
  13329. X509 *client_cert, EVP_PKEY *client_key,
  13330. const std::string &private_key_password)
  13331. : ClientImpl(host, port) {
  13332. const char *password =
  13333. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13334. ctx_ = tls::impl::create_client_context_from_x509(
  13335. client_cert, client_key, password, last_backend_error_);
  13336. }
  13337. inline long SSLClient::get_verify_result() const { return verify_result_; }
  13338. inline void SSLClient::set_server_certificate_verifier(
  13339. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  13340. // Wrap SSL* callback into backend-independent session_verifier_
  13341. auto v = std::make_shared<std::function<SSLVerifierResponse(SSL *)>>(
  13342. std::move(verifier));
  13343. session_verifier_ = [v](tls::session_t session) {
  13344. return (*v)(static_cast<SSL *>(session));
  13345. };
  13346. }
  13347. inline SSL_CTX *SSLClient::ssl_context() const {
  13348. return static_cast<SSL_CTX *>(ctx_);
  13349. }
  13350. inline bool SSLClient::verify_host(X509 *server_cert) const {
  13351. /* Quote from RFC2818 section 3.1 "Server Identity"
  13352. If a subjectAltName extension of type dNSName is present, that MUST
  13353. be used as the identity. Otherwise, the (most specific) Common Name
  13354. field in the Subject field of the certificate MUST be used. Although
  13355. the use of the Common Name is existing practice, it is deprecated and
  13356. Certification Authorities are encouraged to use the dNSName instead.
  13357. Matching is performed using the matching rules specified by
  13358. [RFC2459]. If more than one identity of a given type is present in
  13359. the certificate (e.g., more than one dNSName name, a match in any one
  13360. of the set is considered acceptable.) Names may contain the wildcard
  13361. character * which is considered to match any single domain name
  13362. component or component fragment. E.g., *.a.com matches foo.a.com but
  13363. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  13364. In some cases, the URI is specified as an IP address rather than a
  13365. hostname. In this case, the iPAddress subjectAltName must be present
  13366. in the certificate and must exactly match the IP in the URI.
  13367. */
  13368. return verify_host_with_subject_alt_name(server_cert) ||
  13369. verify_host_with_common_name(server_cert);
  13370. }
  13371. inline bool
  13372. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  13373. auto ret = false;
  13374. auto type = GEN_DNS;
  13375. struct in6_addr addr6 = {};
  13376. struct in_addr addr = {};
  13377. size_t addr_len = 0;
  13378. #ifndef __MINGW32__
  13379. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  13380. type = GEN_IPADD;
  13381. addr_len = sizeof(struct in6_addr);
  13382. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  13383. type = GEN_IPADD;
  13384. addr_len = sizeof(struct in_addr);
  13385. }
  13386. #endif
  13387. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  13388. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  13389. if (alt_names) {
  13390. auto dsn_matched = false;
  13391. auto ip_matched = false;
  13392. auto count = sk_GENERAL_NAME_num(alt_names);
  13393. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  13394. auto val = sk_GENERAL_NAME_value(alt_names, i);
  13395. if (!val || val->type != type) { continue; }
  13396. auto name =
  13397. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  13398. if (name == nullptr) { continue; }
  13399. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  13400. switch (type) {
  13401. case GEN_DNS:
  13402. dsn_matched =
  13403. detail::match_hostname(std::string(name, name_len), host_);
  13404. break;
  13405. case GEN_IPADD:
  13406. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  13407. ip_matched = true;
  13408. }
  13409. break;
  13410. }
  13411. }
  13412. if (dsn_matched || ip_matched) { ret = true; }
  13413. }
  13414. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  13415. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  13416. return ret;
  13417. }
  13418. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  13419. const auto subject_name = X509_get_subject_name(server_cert);
  13420. if (subject_name != nullptr) {
  13421. char name[BUFSIZ];
  13422. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  13423. name, sizeof(name));
  13424. if (name_len != -1) {
  13425. return detail::match_hostname(
  13426. std::string(name, static_cast<size_t>(name_len)), host_);
  13427. }
  13428. }
  13429. return false;
  13430. }
  13431. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  13432. /*
  13433. * Group 9: TLS abstraction layer - Mbed TLS backend
  13434. */
  13435. /*
  13436. * Mbed TLS Backend Implementation
  13437. */
  13438. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13439. namespace tls {
  13440. namespace impl {
  13441. // Mbed TLS session wrapper
  13442. struct MbedTlsSession {
  13443. mbedtls_ssl_context ssl;
  13444. socket_t sock = INVALID_SOCKET;
  13445. std::string hostname; // For client: set via set_sni
  13446. std::string sni_hostname; // For server: received from client via SNI callback
  13447. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  13448. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  13449. MbedTlsSession(const MbedTlsSession &) = delete;
  13450. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  13451. };
  13452. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  13453. // queue)
  13454. inline int &mbedtls_last_error() {
  13455. static thread_local int err = 0;
  13456. return err;
  13457. }
  13458. // Helper to map Mbed TLS error to ErrorCode
  13459. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  13460. if (ret == 0) { return ErrorCode::Success; }
  13461. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  13462. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  13463. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  13464. return ErrorCode::PeerClosed;
  13465. }
  13466. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  13467. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  13468. out_errno = errno;
  13469. return ErrorCode::SyscallError;
  13470. }
  13471. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  13472. return ErrorCode::CertVerifyFailed;
  13473. }
  13474. return ErrorCode::Fatal;
  13475. }
  13476. // BIO-like send callback for Mbed TLS
  13477. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  13478. size_t len) {
  13479. auto sock = *static_cast<socket_t *>(ctx);
  13480. #ifdef _WIN32
  13481. auto ret =
  13482. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  13483. if (ret == SOCKET_ERROR) {
  13484. int err = WSAGetLastError();
  13485. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  13486. return MBEDTLS_ERR_NET_SEND_FAILED;
  13487. }
  13488. #else
  13489. auto ret = send(sock, buf, len, 0);
  13490. if (ret < 0) {
  13491. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  13492. return MBEDTLS_ERR_SSL_WANT_WRITE;
  13493. }
  13494. return MBEDTLS_ERR_NET_SEND_FAILED;
  13495. }
  13496. #endif
  13497. return static_cast<int>(ret);
  13498. }
  13499. // BIO-like recv callback for Mbed TLS
  13500. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  13501. auto sock = *static_cast<socket_t *>(ctx);
  13502. #ifdef _WIN32
  13503. auto ret =
  13504. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  13505. if (ret == SOCKET_ERROR) {
  13506. int err = WSAGetLastError();
  13507. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  13508. return MBEDTLS_ERR_NET_RECV_FAILED;
  13509. }
  13510. #else
  13511. auto ret = recv(sock, buf, len, 0);
  13512. if (ret < 0) {
  13513. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  13514. return MBEDTLS_ERR_SSL_WANT_READ;
  13515. }
  13516. return MBEDTLS_ERR_NET_RECV_FAILED;
  13517. }
  13518. #endif
  13519. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  13520. return static_cast<int>(ret);
  13521. }
  13522. // MbedTlsContext constructor/destructor implementations
  13523. inline MbedTlsContext::MbedTlsContext() {
  13524. mbedtls_ssl_config_init(&conf);
  13525. mbedtls_entropy_init(&entropy);
  13526. mbedtls_ctr_drbg_init(&ctr_drbg);
  13527. mbedtls_x509_crt_init(&ca_chain);
  13528. mbedtls_x509_crt_init(&own_cert);
  13529. mbedtls_pk_init(&own_key);
  13530. }
  13531. inline MbedTlsContext::~MbedTlsContext() {
  13532. mbedtls_pk_free(&own_key);
  13533. mbedtls_x509_crt_free(&own_cert);
  13534. mbedtls_x509_crt_free(&ca_chain);
  13535. mbedtls_ctr_drbg_free(&ctr_drbg);
  13536. mbedtls_entropy_free(&entropy);
  13537. mbedtls_ssl_config_free(&conf);
  13538. }
  13539. // Thread-local storage for SNI captured during handshake
  13540. // This is needed because the SNI callback doesn't have a way to pass
  13541. // session-specific data before the session is fully set up
  13542. inline std::string &mbedpending_sni() {
  13543. static thread_local std::string sni;
  13544. return sni;
  13545. }
  13546. // SNI callback for Mbed TLS server to capture client's SNI hostname
  13547. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  13548. const unsigned char *name, size_t name_len) {
  13549. (void)p_ctx;
  13550. (void)ssl;
  13551. // Store SNI name in thread-local storage
  13552. // It will be retrieved and stored in the session after handshake
  13553. if (name && name_len > 0) {
  13554. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  13555. } else {
  13556. mbedpending_sni().clear();
  13557. }
  13558. return 0; // Accept any SNI
  13559. }
  13560. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  13561. int cert_depth, uint32_t *flags);
  13562. // Check if a string is an IPv4 address
  13563. inline bool is_ipv4_address(const std::string &str) {
  13564. int dots = 0;
  13565. for (char c : str) {
  13566. if (c == '.') {
  13567. dots++;
  13568. } else if (!isdigit(static_cast<unsigned char>(c))) {
  13569. return false;
  13570. }
  13571. }
  13572. return dots == 3;
  13573. }
  13574. // Parse IPv4 address string to bytes
  13575. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  13576. int parts[4];
  13577. if (sscanf(str.c_str(), "%d.%d.%d.%d", &parts[0], &parts[1], &parts[2],
  13578. &parts[3]) != 4) {
  13579. return false;
  13580. }
  13581. for (int i = 0; i < 4; i++) {
  13582. if (parts[i] < 0 || parts[i] > 255) return false;
  13583. out[i] = static_cast<unsigned char>(parts[i]);
  13584. }
  13585. return true;
  13586. }
  13587. // MbedTLS verify callback wrapper
  13588. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  13589. int cert_depth, uint32_t *flags) {
  13590. auto &callback = get_verify_callback();
  13591. if (!callback) { return 0; } // Continue with default verification
  13592. // data points to the MbedTlsSession
  13593. auto *session = static_cast<MbedTlsSession *>(data);
  13594. // Build context
  13595. VerifyContext verify_ctx;
  13596. verify_ctx.session = static_cast<session_t>(session);
  13597. verify_ctx.cert = static_cast<cert_t>(crt);
  13598. verify_ctx.depth = cert_depth;
  13599. verify_ctx.preverify_ok = (*flags == 0);
  13600. verify_ctx.error_code = static_cast<long>(*flags);
  13601. // Convert Mbed TLS flags to error string
  13602. static thread_local char error_buf[256];
  13603. if (*flags != 0) {
  13604. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  13605. verify_ctx.error_string = error_buf;
  13606. } else {
  13607. verify_ctx.error_string = nullptr;
  13608. }
  13609. bool accepted = callback(verify_ctx);
  13610. if (accepted) {
  13611. *flags = 0; // Clear all error flags
  13612. return 0;
  13613. }
  13614. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  13615. }
  13616. } // namespace impl
  13617. inline ctx_t create_client_context() {
  13618. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  13619. if (!ctx) { return nullptr; }
  13620. ctx->is_server = false;
  13621. // Seed the random number generator
  13622. const char *pers = "httplib_client";
  13623. int ret = mbedtls_ctr_drbg_seed(
  13624. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  13625. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  13626. if (ret != 0) {
  13627. impl::mbedtls_last_error() = ret;
  13628. delete ctx;
  13629. return nullptr;
  13630. }
  13631. // Set up SSL config for client
  13632. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  13633. MBEDTLS_SSL_TRANSPORT_STREAM,
  13634. MBEDTLS_SSL_PRESET_DEFAULT);
  13635. if (ret != 0) {
  13636. impl::mbedtls_last_error() = ret;
  13637. delete ctx;
  13638. return nullptr;
  13639. }
  13640. // Set random number generator
  13641. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  13642. // Default: verify peer certificate
  13643. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13644. // Set minimum TLS version to 1.2
  13645. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13646. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13647. #else
  13648. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13649. MBEDTLS_SSL_MINOR_VERSION_3);
  13650. #endif
  13651. return static_cast<ctx_t>(ctx);
  13652. }
  13653. inline ctx_t create_server_context() {
  13654. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  13655. if (!ctx) { return nullptr; }
  13656. ctx->is_server = true;
  13657. // Seed the random number generator
  13658. const char *pers = "httplib_server";
  13659. int ret = mbedtls_ctr_drbg_seed(
  13660. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  13661. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  13662. if (ret != 0) {
  13663. impl::mbedtls_last_error() = ret;
  13664. delete ctx;
  13665. return nullptr;
  13666. }
  13667. // Set up SSL config for server
  13668. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  13669. MBEDTLS_SSL_TRANSPORT_STREAM,
  13670. MBEDTLS_SSL_PRESET_DEFAULT);
  13671. if (ret != 0) {
  13672. impl::mbedtls_last_error() = ret;
  13673. delete ctx;
  13674. return nullptr;
  13675. }
  13676. // Set random number generator
  13677. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  13678. // Default: don't verify client
  13679. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  13680. // Set minimum TLS version to 1.2
  13681. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13682. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13683. #else
  13684. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13685. MBEDTLS_SSL_MINOR_VERSION_3);
  13686. #endif
  13687. // Set SNI callback to capture client's SNI hostname
  13688. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  13689. return static_cast<ctx_t>(ctx);
  13690. }
  13691. inline void free_context(ctx_t ctx) {
  13692. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  13693. }
  13694. inline bool set_min_version(ctx_t ctx, Version version) {
  13695. if (!ctx) { return false; }
  13696. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13697. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13698. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  13699. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  13700. if (version >= Version::TLS1_3) {
  13701. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  13702. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  13703. #endif
  13704. }
  13705. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  13706. #else
  13707. // Mbed TLS 2.x uses major/minor version numbers
  13708. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  13709. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  13710. if (version >= Version::TLS1_3) {
  13711. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  13712. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  13713. #else
  13714. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  13715. #endif
  13716. }
  13717. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  13718. #endif
  13719. return true;
  13720. }
  13721. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  13722. if (!ctx || !pem) { return false; }
  13723. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13724. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  13725. // Add null terminator if not present
  13726. std::string pem_str(pem, len);
  13727. int ret = mbedtls_x509_crt_parse(
  13728. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  13729. pem_str.size() + 1);
  13730. if (ret != 0) {
  13731. impl::mbedtls_last_error() = ret;
  13732. return false;
  13733. }
  13734. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13735. return true;
  13736. }
  13737. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  13738. if (!ctx || !file_path) { return false; }
  13739. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13740. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  13741. if (ret != 0) {
  13742. impl::mbedtls_last_error() = ret;
  13743. return false;
  13744. }
  13745. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13746. return true;
  13747. }
  13748. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  13749. if (!ctx || !dir_path) { return false; }
  13750. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13751. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  13752. if (ret < 0) { // Returns number of certs on success, negative on error
  13753. impl::mbedtls_last_error() = ret;
  13754. return false;
  13755. }
  13756. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13757. return true;
  13758. }
  13759. inline bool load_system_certs(ctx_t ctx) {
  13760. if (!ctx) { return false; }
  13761. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13762. bool loaded = false;
  13763. #ifdef _WIN32
  13764. // Load from Windows certificate store (ROOT and CA)
  13765. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  13766. for (auto store_name : store_names) {
  13767. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  13768. if (hStore) {
  13769. PCCERT_CONTEXT pContext = nullptr;
  13770. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  13771. nullptr) {
  13772. int ret = mbedtls_x509_crt_parse_der(
  13773. &mctx->ca_chain, pContext->pbCertEncoded, pContext->cbCertEncoded);
  13774. if (ret == 0) { loaded = true; }
  13775. }
  13776. CertCloseStore(hStore, 0);
  13777. }
  13778. }
  13779. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  13780. // Load from macOS Keychain
  13781. CFArrayRef certs = nullptr;
  13782. OSStatus status = SecTrustCopyAnchorCertificates(&certs);
  13783. if (status == errSecSuccess && certs) {
  13784. CFIndex count = CFArrayGetCount(certs);
  13785. for (CFIndex i = 0; i < count; i++) {
  13786. SecCertificateRef cert =
  13787. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  13788. CFDataRef data = SecCertificateCopyData(cert);
  13789. if (data) {
  13790. int ret = mbedtls_x509_crt_parse_der(
  13791. &mctx->ca_chain, CFDataGetBytePtr(data),
  13792. static_cast<size_t>(CFDataGetLength(data)));
  13793. if (ret == 0) { loaded = true; }
  13794. CFRelease(data);
  13795. }
  13796. }
  13797. CFRelease(certs);
  13798. }
  13799. #else
  13800. // Try common CA certificate locations on Linux/Unix
  13801. static const char *ca_paths[] = {
  13802. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  13803. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  13804. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  13805. "/etc/pki/tls/cacert.pem", // OpenELEC
  13806. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  13807. nullptr};
  13808. for (const char **path = ca_paths; *path; ++path) {
  13809. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path);
  13810. if (ret >= 0) {
  13811. loaded = true;
  13812. break;
  13813. }
  13814. }
  13815. // Also try the CA directory
  13816. if (!loaded) {
  13817. static const char *ca_dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  13818. "/etc/pki/tls/certs", // RHEL/CentOS
  13819. "/usr/share/ca-certificates", nullptr};
  13820. for (const char **dir = ca_dirs; *dir; ++dir) {
  13821. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir);
  13822. if (ret >= 0) {
  13823. loaded = true;
  13824. break;
  13825. }
  13826. }
  13827. }
  13828. #endif
  13829. if (loaded) {
  13830. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13831. }
  13832. return loaded;
  13833. }
  13834. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  13835. const char *password) {
  13836. if (!ctx || !cert || !key) { return false; }
  13837. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13838. // Parse certificate
  13839. std::string cert_str(cert);
  13840. int ret = mbedtls_x509_crt_parse(
  13841. &mctx->own_cert,
  13842. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  13843. cert_str.size() + 1);
  13844. if (ret != 0) {
  13845. impl::mbedtls_last_error() = ret;
  13846. return false;
  13847. }
  13848. // Parse private key
  13849. std::string key_str(key);
  13850. const unsigned char *pwd =
  13851. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  13852. size_t pwd_len = password ? strlen(password) : 0;
  13853. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13854. ret = mbedtls_pk_parse_key(
  13855. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  13856. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  13857. &mctx->ctr_drbg);
  13858. #else
  13859. ret = mbedtls_pk_parse_key(
  13860. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  13861. key_str.size() + 1, pwd, pwd_len);
  13862. #endif
  13863. if (ret != 0) {
  13864. impl::mbedtls_last_error() = ret;
  13865. return false;
  13866. }
  13867. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  13868. if (ret != 0) {
  13869. impl::mbedtls_last_error() = ret;
  13870. return false;
  13871. }
  13872. return true;
  13873. }
  13874. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  13875. const char *key_path, const char *password) {
  13876. if (!ctx || !cert_path || !key_path) { return false; }
  13877. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13878. // Parse certificate file
  13879. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  13880. if (ret != 0) {
  13881. impl::mbedtls_last_error() = ret;
  13882. return false;
  13883. }
  13884. // Parse private key file
  13885. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13886. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  13887. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  13888. #else
  13889. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  13890. #endif
  13891. if (ret != 0) {
  13892. impl::mbedtls_last_error() = ret;
  13893. return false;
  13894. }
  13895. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  13896. if (ret != 0) {
  13897. impl::mbedtls_last_error() = ret;
  13898. return false;
  13899. }
  13900. return true;
  13901. }
  13902. inline void set_verify_client(ctx_t ctx, bool require) {
  13903. if (!ctx) { return; }
  13904. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13905. mctx->verify_client = require;
  13906. if (require) {
  13907. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13908. } else {
  13909. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  13910. // is called (matching OpenSSL behavior). Otherwise use NONE.
  13911. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  13912. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  13913. : MBEDTLS_SSL_VERIFY_NONE);
  13914. }
  13915. }
  13916. inline session_t create_session(ctx_t ctx, socket_t sock) {
  13917. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  13918. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13919. auto session = new (std::nothrow) impl::MbedTlsSession();
  13920. if (!session) { return nullptr; }
  13921. session->sock = sock;
  13922. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  13923. if (ret != 0) {
  13924. impl::mbedtls_last_error() = ret;
  13925. delete session;
  13926. return nullptr;
  13927. }
  13928. // Set BIO callbacks
  13929. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  13930. impl::mbedtls_net_recv_cb, nullptr);
  13931. // Set per-session verify callback with session pointer if callback is
  13932. // registered
  13933. if (mctx->has_verify_callback) {
  13934. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  13935. session);
  13936. }
  13937. return static_cast<session_t>(session);
  13938. }
  13939. inline void free_session(session_t session) {
  13940. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  13941. }
  13942. inline bool set_sni(session_t session, const char *hostname) {
  13943. if (!session || !hostname) { return false; }
  13944. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13945. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  13946. if (ret != 0) {
  13947. impl::mbedtls_last_error() = ret;
  13948. return false;
  13949. }
  13950. msession->hostname = hostname;
  13951. return true;
  13952. }
  13953. inline bool set_hostname(session_t session, const char *hostname) {
  13954. // In Mbed TLS, set_hostname also sets up hostname verification
  13955. return set_sni(session, hostname);
  13956. }
  13957. inline TlsError connect(session_t session) {
  13958. TlsError err;
  13959. if (!session) {
  13960. err.code = ErrorCode::Fatal;
  13961. return err;
  13962. }
  13963. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13964. int ret = mbedtls_ssl_handshake(&msession->ssl);
  13965. if (ret == 0) {
  13966. err.code = ErrorCode::Success;
  13967. } else {
  13968. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  13969. err.backend_code = static_cast<uint64_t>(-ret);
  13970. impl::mbedtls_last_error() = ret;
  13971. }
  13972. return err;
  13973. }
  13974. inline TlsError accept(session_t session) {
  13975. // Same as connect for Mbed TLS - handshake works for both client and server
  13976. auto result = connect(session);
  13977. // After successful handshake, capture SNI from thread-local storage
  13978. if (result.code == ErrorCode::Success && session) {
  13979. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13980. msession->sni_hostname = std::move(impl::mbedpending_sni());
  13981. impl::mbedpending_sni().clear();
  13982. }
  13983. return result;
  13984. }
  13985. inline bool connect_nonblocking(session_t session, socket_t sock,
  13986. time_t timeout_sec, time_t timeout_usec,
  13987. TlsError *err) {
  13988. if (!session) {
  13989. if (err) { err->code = ErrorCode::Fatal; }
  13990. return false;
  13991. }
  13992. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13993. // Set socket to non-blocking mode
  13994. detail::set_nonblocking(sock, true);
  13995. auto cleanup =
  13996. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  13997. int ret;
  13998. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  13999. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  14000. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14001. continue;
  14002. }
  14003. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  14004. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14005. continue;
  14006. }
  14007. }
  14008. // TlsError or timeout
  14009. if (err) {
  14010. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  14011. err->backend_code = static_cast<uint64_t>(-ret);
  14012. }
  14013. impl::mbedtls_last_error() = ret;
  14014. return false;
  14015. }
  14016. if (err) { err->code = ErrorCode::Success; }
  14017. return true;
  14018. }
  14019. inline bool accept_nonblocking(session_t session, socket_t sock,
  14020. time_t timeout_sec, time_t timeout_usec,
  14021. TlsError *err) {
  14022. // Same implementation as connect for Mbed TLS
  14023. bool result =
  14024. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  14025. // After successful handshake, capture SNI from thread-local storage
  14026. if (result && session) {
  14027. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14028. msession->sni_hostname = std::move(impl::mbedpending_sni());
  14029. impl::mbedpending_sni().clear();
  14030. }
  14031. return result;
  14032. }
  14033. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14034. if (!session || !buf) {
  14035. err.code = ErrorCode::Fatal;
  14036. return -1;
  14037. }
  14038. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14039. int ret =
  14040. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  14041. if (ret > 0) {
  14042. err.code = ErrorCode::Success;
  14043. return static_cast<ssize_t>(ret);
  14044. }
  14045. if (ret == 0) {
  14046. err.code = ErrorCode::PeerClosed;
  14047. return 0;
  14048. }
  14049. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  14050. err.backend_code = static_cast<uint64_t>(-ret);
  14051. impl::mbedtls_last_error() = ret;
  14052. return -1;
  14053. }
  14054. inline ssize_t write(session_t session, const void *buf, size_t len,
  14055. TlsError &err) {
  14056. if (!session || !buf) {
  14057. err.code = ErrorCode::Fatal;
  14058. return -1;
  14059. }
  14060. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14061. int ret = mbedtls_ssl_write(&msession->ssl,
  14062. static_cast<const unsigned char *>(buf), len);
  14063. if (ret > 0) {
  14064. err.code = ErrorCode::Success;
  14065. return static_cast<ssize_t>(ret);
  14066. }
  14067. if (ret == 0) {
  14068. err.code = ErrorCode::PeerClosed;
  14069. return 0;
  14070. }
  14071. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  14072. err.backend_code = static_cast<uint64_t>(-ret);
  14073. impl::mbedtls_last_error() = ret;
  14074. return -1;
  14075. }
  14076. inline int pending(const_session_t session) {
  14077. if (!session) { return 0; }
  14078. auto msession =
  14079. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  14080. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  14081. }
  14082. inline void shutdown(session_t session, bool graceful) {
  14083. if (!session) { return; }
  14084. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14085. if (graceful) {
  14086. // Try to send close_notify, but don't block forever
  14087. int ret;
  14088. int attempts = 0;
  14089. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  14090. attempts < 3) {
  14091. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  14092. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  14093. break;
  14094. }
  14095. attempts++;
  14096. }
  14097. }
  14098. }
  14099. inline bool is_peer_closed(session_t session, socket_t sock) {
  14100. if (!session || sock == INVALID_SOCKET) { return true; }
  14101. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14102. // Check if there's already decrypted data available in the TLS buffer
  14103. // If so, the connection is definitely alive
  14104. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  14105. // Set socket to non-blocking to avoid blocking on read
  14106. detail::set_nonblocking(sock, true);
  14107. auto cleanup =
  14108. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14109. // Try a 1-byte read to check connection status
  14110. // Note: This will consume the byte if data is available, but for the
  14111. // purpose of checking if peer is closed, this should be acceptable
  14112. // since we're only called when we expect the connection might be closing
  14113. unsigned char buf;
  14114. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  14115. // If we got data or WANT_READ (would block), connection is alive
  14116. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  14117. // If we get a peer close notify or a connection reset, the peer is closed
  14118. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  14119. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  14120. }
  14121. inline cert_t get_peer_cert(const_session_t session) {
  14122. if (!session) { return nullptr; }
  14123. auto msession =
  14124. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  14125. // Mbed TLS returns a pointer to the internal peer cert chain.
  14126. // WARNING: This pointer is only valid while the session is active.
  14127. // Do not use the certificate after calling free_session().
  14128. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  14129. return const_cast<mbedtls_x509_crt *>(cert);
  14130. }
  14131. inline void free_cert(cert_t cert) {
  14132. // Mbed TLS: peer certificate is owned by the SSL context.
  14133. // No-op here, but callers should still call this for cross-backend
  14134. // portability.
  14135. (void)cert;
  14136. }
  14137. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14138. if (!cert || !hostname) { return false; }
  14139. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  14140. std::string host_str(hostname);
  14141. // Check if hostname is an IP address
  14142. bool is_ip = impl::is_ipv4_address(host_str);
  14143. unsigned char ip_bytes[4];
  14144. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  14145. // Check Subject Alternative Names (SAN)
  14146. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  14147. // - DNS names: raw string bytes
  14148. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  14149. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  14150. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  14151. const unsigned char *p = san->buf.p;
  14152. size_t len = san->buf.len;
  14153. if (is_ip) {
  14154. // Check if this SAN is an IPv4 address (4 bytes)
  14155. if (len == 4 && memcmp(p, ip_bytes, 4) == 0) { return true; }
  14156. // Check if this SAN is an IPv6 address (16 bytes) - skip for now
  14157. } else {
  14158. // Check if this SAN is a DNS name (printable ASCII string)
  14159. bool is_dns = len > 0;
  14160. for (size_t i = 0; i < len && is_dns; i++) {
  14161. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  14162. }
  14163. if (is_dns) {
  14164. std::string san_name(reinterpret_cast<const char *>(p), len);
  14165. if (detail::match_hostname(san_name, host_str)) { return true; }
  14166. }
  14167. }
  14168. san = san->next;
  14169. }
  14170. // Fallback: Check Common Name (CN) in subject
  14171. char cn[256];
  14172. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  14173. if (ret > 0) {
  14174. std::string cn_str(cn);
  14175. // Look for "CN=" in the DN string
  14176. size_t cn_pos = cn_str.find("CN=");
  14177. if (cn_pos != std::string::npos) {
  14178. size_t start = cn_pos + 3;
  14179. size_t end = cn_str.find(',', start);
  14180. std::string cn_value =
  14181. cn_str.substr(start, end == std::string::npos ? end : end - start);
  14182. if (detail::match_hostname(cn_value, host_str)) { return true; }
  14183. }
  14184. }
  14185. return false;
  14186. }
  14187. inline uint64_t hostname_mismatch_code() {
  14188. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  14189. }
  14190. inline long get_verify_result(const_session_t session) {
  14191. if (!session) { return -1; }
  14192. auto msession =
  14193. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  14194. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  14195. // Return 0 (X509_V_OK equivalent) if verification passed
  14196. return flags == 0 ? 0 : static_cast<long>(flags);
  14197. }
  14198. inline std::string get_cert_subject_cn(cert_t cert) {
  14199. if (!cert) return "";
  14200. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14201. // Find the CN in the subject
  14202. const mbedtls_x509_name *name = &x509->subject;
  14203. while (name != nullptr) {
  14204. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  14205. return std::string(reinterpret_cast<const char *>(name->val.p),
  14206. name->val.len);
  14207. }
  14208. name = name->next;
  14209. }
  14210. return "";
  14211. }
  14212. inline std::string get_cert_issuer_name(cert_t cert) {
  14213. if (!cert) return "";
  14214. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14215. // Build a human-readable issuer name string
  14216. char buf[512];
  14217. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  14218. if (ret < 0) return "";
  14219. return std::string(buf);
  14220. }
  14221. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14222. sans.clear();
  14223. if (!cert) return false;
  14224. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14225. // Parse the Subject Alternative Name extension
  14226. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  14227. while (cur != nullptr) {
  14228. if (cur->buf.len > 0) {
  14229. // Mbed TLS stores SAN as ASN.1 sequences
  14230. // The tag byte indicates the type
  14231. const unsigned char *p = cur->buf.p;
  14232. size_t len = cur->buf.len;
  14233. // First byte is the tag
  14234. unsigned char tag = *p;
  14235. p++;
  14236. len--;
  14237. // Parse length (simple single-byte length assumed)
  14238. if (len > 0 && *p < 0x80) {
  14239. size_t value_len = *p;
  14240. p++;
  14241. len--;
  14242. if (value_len <= len) {
  14243. SanEntry entry;
  14244. // ASN.1 context tags for GeneralName
  14245. switch (tag & 0x1F) {
  14246. case 2: // dNSName
  14247. entry.type = SanType::DNS;
  14248. entry.value =
  14249. std::string(reinterpret_cast<const char *>(p), value_len);
  14250. break;
  14251. case 7: // iPAddress
  14252. entry.type = SanType::IP;
  14253. if (value_len == 4) {
  14254. // IPv4
  14255. char buf[16];
  14256. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  14257. entry.value = buf;
  14258. } else if (value_len == 16) {
  14259. // IPv6
  14260. char buf[64];
  14261. snprintf(buf, sizeof(buf),
  14262. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  14263. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  14264. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  14265. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  14266. entry.value = buf;
  14267. }
  14268. break;
  14269. case 1: // rfc822Name (email)
  14270. entry.type = SanType::EMAIL;
  14271. entry.value =
  14272. std::string(reinterpret_cast<const char *>(p), value_len);
  14273. break;
  14274. case 6: // uniformResourceIdentifier
  14275. entry.type = SanType::URI;
  14276. entry.value =
  14277. std::string(reinterpret_cast<const char *>(p), value_len);
  14278. break;
  14279. default: entry.type = SanType::OTHER; break;
  14280. }
  14281. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14282. }
  14283. }
  14284. }
  14285. cur = cur->next;
  14286. }
  14287. return true;
  14288. }
  14289. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14290. time_t &not_after) {
  14291. if (!cert) return false;
  14292. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14293. // Convert mbedtls_x509_time to time_t
  14294. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  14295. struct tm tm_time = {};
  14296. tm_time.tm_year = t.year - 1900;
  14297. tm_time.tm_mon = t.mon - 1;
  14298. tm_time.tm_mday = t.day;
  14299. tm_time.tm_hour = t.hour;
  14300. tm_time.tm_min = t.min;
  14301. tm_time.tm_sec = t.sec;
  14302. #ifdef _WIN32
  14303. return _mkgmtime(&tm_time);
  14304. #else
  14305. return timegm(&tm_time);
  14306. #endif
  14307. };
  14308. not_before = to_time_t(x509->valid_from);
  14309. not_after = to_time_t(x509->valid_to);
  14310. return true;
  14311. }
  14312. inline std::string get_cert_serial(cert_t cert) {
  14313. if (!cert) return "";
  14314. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14315. // Convert serial number to hex string
  14316. std::string result;
  14317. result.reserve(x509->serial.len * 2);
  14318. for (size_t i = 0; i < x509->serial.len; i++) {
  14319. char hex[3];
  14320. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  14321. result += hex;
  14322. }
  14323. return result;
  14324. }
  14325. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14326. if (!cert) return false;
  14327. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  14328. if (!crt->raw.p || crt->raw.len == 0) return false;
  14329. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  14330. return true;
  14331. }
  14332. inline const char *get_sni(const_session_t session) {
  14333. if (!session) return nullptr;
  14334. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  14335. // For server: return SNI received from client during handshake
  14336. if (!msession->sni_hostname.empty()) {
  14337. return msession->sni_hostname.c_str();
  14338. }
  14339. // For client: return the hostname set via set_sni
  14340. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  14341. return nullptr;
  14342. }
  14343. inline uint64_t peek_error() {
  14344. // Mbed TLS doesn't have an error queue, return the last error
  14345. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  14346. }
  14347. inline uint64_t get_error() {
  14348. // Mbed TLS doesn't have an error queue, return and clear the last error
  14349. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  14350. impl::mbedtls_last_error() = 0;
  14351. return err;
  14352. }
  14353. inline std::string error_string(uint64_t code) {
  14354. char buf[256];
  14355. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  14356. return std::string(buf);
  14357. }
  14358. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14359. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  14360. if (!ca_chain) { return nullptr; }
  14361. mbedtls_x509_crt_init(ca_chain);
  14362. // mbedtls_x509_crt_parse expects null-terminated PEM
  14363. int ret = mbedtls_x509_crt_parse(ca_chain,
  14364. reinterpret_cast<const unsigned char *>(pem),
  14365. len + 1); // +1 for null terminator
  14366. if (ret != 0) {
  14367. // Try without +1 in case PEM is already null-terminated
  14368. ret = mbedtls_x509_crt_parse(
  14369. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  14370. if (ret != 0) {
  14371. mbedtls_x509_crt_free(ca_chain);
  14372. delete ca_chain;
  14373. return nullptr;
  14374. }
  14375. }
  14376. return static_cast<ca_store_t>(ca_chain);
  14377. }
  14378. inline void free_ca_store(ca_store_t store) {
  14379. if (store) {
  14380. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  14381. mbedtls_x509_crt_free(ca_chain);
  14382. delete ca_chain;
  14383. }
  14384. }
  14385. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  14386. if (!ctx || !store) { return false; }
  14387. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14388. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  14389. // Free existing CA chain
  14390. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  14391. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  14392. // Copy the CA chain (deep copy)
  14393. // Parse from the raw data of the source cert
  14394. mbedtls_x509_crt *src = ca_chain;
  14395. while (src != nullptr) {
  14396. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  14397. src->raw.len);
  14398. if (ret != 0) { return false; }
  14399. src = src->next;
  14400. }
  14401. // Update the SSL config to use the new CA chain
  14402. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  14403. return true;
  14404. }
  14405. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  14406. certs.clear();
  14407. if (!ctx) { return 0; }
  14408. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14409. // Iterate through the CA chain
  14410. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  14411. while (cert != nullptr && cert->raw.len > 0) {
  14412. // Create a copy of the certificate for the caller
  14413. auto *copy = new mbedtls_x509_crt;
  14414. mbedtls_x509_crt_init(copy);
  14415. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  14416. if (ret == 0) {
  14417. certs.push_back(static_cast<cert_t>(copy));
  14418. } else {
  14419. mbedtls_x509_crt_free(copy);
  14420. delete copy;
  14421. }
  14422. cert = cert->next;
  14423. }
  14424. return certs.size();
  14425. }
  14426. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  14427. std::vector<std::string> names;
  14428. if (!ctx) { return names; }
  14429. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14430. // Iterate through the CA chain
  14431. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  14432. while (cert != nullptr && cert->raw.len > 0) {
  14433. char buf[512];
  14434. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  14435. if (ret > 0) { names.push_back(buf); }
  14436. cert = cert->next;
  14437. }
  14438. return names;
  14439. }
  14440. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  14441. const char *key_pem, const char *password) {
  14442. if (!ctx || !cert_pem || !key_pem) { return false; }
  14443. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14444. // Free existing certificate and key
  14445. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  14446. mbedtls_pk_free(&mbed_ctx->own_key);
  14447. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  14448. mbedtls_pk_init(&mbed_ctx->own_key);
  14449. // Parse certificate PEM
  14450. int ret = mbedtls_x509_crt_parse(
  14451. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  14452. strlen(cert_pem) + 1);
  14453. if (ret != 0) {
  14454. impl::mbedtls_last_error() = ret;
  14455. return false;
  14456. }
  14457. // Parse private key PEM
  14458. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14459. ret = mbedtls_pk_parse_key(
  14460. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  14461. strlen(key_pem) + 1,
  14462. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  14463. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  14464. &mbed_ctx->ctr_drbg);
  14465. #else
  14466. ret = mbedtls_pk_parse_key(
  14467. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  14468. strlen(key_pem) + 1,
  14469. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  14470. password ? strlen(password) : 0);
  14471. #endif
  14472. if (ret != 0) {
  14473. impl::mbedtls_last_error() = ret;
  14474. return false;
  14475. }
  14476. // Configure SSL to use the new certificate and key
  14477. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  14478. &mbed_ctx->own_key);
  14479. if (ret != 0) {
  14480. impl::mbedtls_last_error() = ret;
  14481. return false;
  14482. }
  14483. return true;
  14484. }
  14485. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  14486. if (!ctx || !ca_pem) { return false; }
  14487. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14488. // Free existing CA chain
  14489. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  14490. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  14491. // Parse CA PEM
  14492. int ret = mbedtls_x509_crt_parse(
  14493. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  14494. strlen(ca_pem) + 1);
  14495. if (ret != 0) {
  14496. impl::mbedtls_last_error() = ret;
  14497. return false;
  14498. }
  14499. // Update SSL config to use new CA chain
  14500. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  14501. return true;
  14502. }
  14503. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  14504. if (!ctx) { return false; }
  14505. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14506. impl::get_verify_callback() = std::move(callback);
  14507. mbed_ctx->has_verify_callback =
  14508. static_cast<bool>(impl::get_verify_callback());
  14509. if (mbed_ctx->has_verify_callback) {
  14510. // Set OPTIONAL mode to ensure callback is called even when verification
  14511. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  14512. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  14513. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  14514. nullptr);
  14515. } else {
  14516. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  14517. }
  14518. return true;
  14519. }
  14520. inline long get_verify_error(const_session_t session) {
  14521. if (!session) { return -1; }
  14522. auto *msession =
  14523. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  14524. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  14525. }
  14526. inline std::string verify_error_string(long error_code) {
  14527. if (error_code == 0) { return ""; }
  14528. char buf[256];
  14529. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  14530. static_cast<uint32_t>(error_code));
  14531. // Remove trailing newline if present
  14532. std::string result(buf);
  14533. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  14534. result.pop_back();
  14535. }
  14536. return result;
  14537. }
  14538. } // namespace tls
  14539. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  14540. // ----------------------------------------------------------------------------
  14541. } // namespace httplib
  14542. #endif // CPPHTTPLIB_HTTPLIB_H