httplib.h 570 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278
  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. template <bool Read>
  3763. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  3764. #ifdef __APPLE__
  3765. if (sock >= FD_SETSIZE) { return -1; }
  3766. fd_set fds, *rfds, *wfds;
  3767. FD_ZERO(&fds);
  3768. FD_SET(sock, &fds);
  3769. rfds = (Read ? &fds : nullptr);
  3770. wfds = (Read ? nullptr : &fds);
  3771. timeval tv;
  3772. tv.tv_sec = static_cast<long>(sec);
  3773. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3774. return handle_EINTR([&]() {
  3775. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  3776. });
  3777. #else
  3778. struct pollfd pfd;
  3779. pfd.fd = sock;
  3780. pfd.events = (Read ? POLLIN : POLLOUT);
  3781. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3782. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  3783. #endif
  3784. }
  3785. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  3786. return select_impl<true>(sock, sec, usec);
  3787. }
  3788. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  3789. return select_impl<false>(sock, sec, usec);
  3790. }
  3791. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  3792. time_t usec) {
  3793. #ifdef __APPLE__
  3794. if (sock >= FD_SETSIZE) { return Error::Connection; }
  3795. fd_set fdsr, fdsw;
  3796. FD_ZERO(&fdsr);
  3797. FD_ZERO(&fdsw);
  3798. FD_SET(sock, &fdsr);
  3799. FD_SET(sock, &fdsw);
  3800. timeval tv;
  3801. tv.tv_sec = static_cast<long>(sec);
  3802. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3803. auto ret = handle_EINTR([&]() {
  3804. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  3805. });
  3806. if (ret == 0) { return Error::ConnectionTimeout; }
  3807. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  3808. auto error = 0;
  3809. socklen_t len = sizeof(error);
  3810. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3811. reinterpret_cast<char *>(&error), &len);
  3812. auto successful = res >= 0 && !error;
  3813. return successful ? Error::Success : Error::Connection;
  3814. }
  3815. return Error::Connection;
  3816. #else
  3817. struct pollfd pfd_read;
  3818. pfd_read.fd = sock;
  3819. pfd_read.events = POLLIN | POLLOUT;
  3820. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3821. auto poll_res =
  3822. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  3823. if (poll_res == 0) { return Error::ConnectionTimeout; }
  3824. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  3825. auto error = 0;
  3826. socklen_t len = sizeof(error);
  3827. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3828. reinterpret_cast<char *>(&error), &len);
  3829. auto successful = res >= 0 && !error;
  3830. return successful ? Error::Success : Error::Connection;
  3831. }
  3832. return Error::Connection;
  3833. #endif
  3834. }
  3835. inline bool is_socket_alive(socket_t sock) {
  3836. const auto val = detail::select_read(sock, 0, 0);
  3837. if (val == 0) {
  3838. return true;
  3839. } else if (val < 0 && errno == EBADF) {
  3840. return false;
  3841. }
  3842. char buf[1];
  3843. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  3844. }
  3845. class SocketStream final : public Stream {
  3846. public:
  3847. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3848. time_t write_timeout_sec, time_t write_timeout_usec,
  3849. time_t max_timeout_msec = 0,
  3850. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3851. (std::chrono::steady_clock::time_point::min)());
  3852. ~SocketStream() override;
  3853. bool is_readable() const override;
  3854. bool wait_readable() const override;
  3855. bool wait_writable() const override;
  3856. ssize_t read(char *ptr, size_t size) override;
  3857. ssize_t write(const char *ptr, size_t size) override;
  3858. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3859. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3860. socket_t socket() const override;
  3861. time_t duration() const override;
  3862. private:
  3863. socket_t sock_;
  3864. time_t read_timeout_sec_;
  3865. time_t read_timeout_usec_;
  3866. time_t write_timeout_sec_;
  3867. time_t write_timeout_usec_;
  3868. time_t max_timeout_msec_;
  3869. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3870. std::vector<char> read_buff_;
  3871. size_t read_buff_off_ = 0;
  3872. size_t read_buff_content_size_ = 0;
  3873. static const size_t read_buff_size_ = 1024l * 4;
  3874. };
  3875. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3876. time_t keep_alive_timeout_sec) {
  3877. using namespace std::chrono;
  3878. const auto interval_usec =
  3879. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  3880. // Avoid expensive `steady_clock::now()` call for the first time
  3881. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  3882. const auto start = steady_clock::now() - microseconds{interval_usec};
  3883. const auto timeout = seconds{keep_alive_timeout_sec};
  3884. while (true) {
  3885. if (svr_sock == INVALID_SOCKET) {
  3886. break; // Server socket is closed
  3887. }
  3888. auto val = select_read(sock, 0, interval_usec);
  3889. if (val < 0) {
  3890. break; // Ssocket error
  3891. } else if (val == 0) {
  3892. if (steady_clock::now() - start > timeout) {
  3893. break; // Timeout
  3894. }
  3895. } else {
  3896. return true; // Ready for read
  3897. }
  3898. }
  3899. return false;
  3900. }
  3901. template <typename T>
  3902. inline bool
  3903. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3904. size_t keep_alive_max_count,
  3905. time_t keep_alive_timeout_sec, T callback) {
  3906. assert(keep_alive_max_count > 0);
  3907. auto ret = false;
  3908. auto count = keep_alive_max_count;
  3909. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  3910. auto close_connection = count == 1;
  3911. auto connection_closed = false;
  3912. ret = callback(close_connection, connection_closed);
  3913. if (!ret || connection_closed) { break; }
  3914. count--;
  3915. }
  3916. return ret;
  3917. }
  3918. template <typename T>
  3919. inline bool
  3920. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3921. size_t keep_alive_max_count,
  3922. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  3923. time_t read_timeout_usec, time_t write_timeout_sec,
  3924. time_t write_timeout_usec, T callback) {
  3925. return process_server_socket_core(
  3926. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  3927. [&](bool close_connection, bool &connection_closed) {
  3928. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3929. write_timeout_sec, write_timeout_usec);
  3930. return callback(strm, close_connection, connection_closed);
  3931. });
  3932. }
  3933. inline bool process_client_socket(
  3934. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3935. time_t write_timeout_sec, time_t write_timeout_usec,
  3936. time_t max_timeout_msec,
  3937. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3938. std::function<bool(Stream &)> callback) {
  3939. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3940. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  3941. start_time);
  3942. return callback(strm);
  3943. }
  3944. inline int shutdown_socket(socket_t sock) {
  3945. #ifdef _WIN32
  3946. return shutdown(sock, SD_BOTH);
  3947. #else
  3948. return shutdown(sock, SHUT_RDWR);
  3949. #endif
  3950. }
  3951. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  3952. if (s.size() > 1 && s[0] == '\0') {
  3953. auto ret = s;
  3954. ret[0] = '@';
  3955. return ret;
  3956. }
  3957. return s;
  3958. }
  3959. inline std::string
  3960. unescape_abstract_namespace_unix_domain(const std::string &s) {
  3961. if (s.size() > 1 && s[0] == '@') {
  3962. auto ret = s;
  3963. ret[0] = '\0';
  3964. return ret;
  3965. }
  3966. return s;
  3967. }
  3968. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  3969. const struct addrinfo *hints,
  3970. struct addrinfo **res, time_t timeout_sec) {
  3971. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  3972. if (timeout_sec <= 0) {
  3973. // No timeout specified, use standard getaddrinfo
  3974. return getaddrinfo(node, service, hints, res);
  3975. }
  3976. #ifdef _WIN32
  3977. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  3978. OVERLAPPED overlapped = {0};
  3979. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  3980. if (!event) { return EAI_FAIL; }
  3981. overlapped.hEvent = event;
  3982. PADDRINFOEXW result_addrinfo = nullptr;
  3983. HANDLE cancel_handle = nullptr;
  3984. ADDRINFOEXW hints_ex = {0};
  3985. if (hints) {
  3986. hints_ex.ai_flags = hints->ai_flags;
  3987. hints_ex.ai_family = hints->ai_family;
  3988. hints_ex.ai_socktype = hints->ai_socktype;
  3989. hints_ex.ai_protocol = hints->ai_protocol;
  3990. }
  3991. auto wnode = u8string_to_wstring(node);
  3992. auto wservice = u8string_to_wstring(service);
  3993. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  3994. hints ? &hints_ex : nullptr, &result_addrinfo,
  3995. nullptr, &overlapped, nullptr, &cancel_handle);
  3996. if (ret == WSA_IO_PENDING) {
  3997. auto wait_result =
  3998. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  3999. if (wait_result == WAIT_TIMEOUT) {
  4000. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4001. ::CloseHandle(event);
  4002. return EAI_AGAIN;
  4003. }
  4004. DWORD bytes_returned;
  4005. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4006. &bytes_returned, FALSE)) {
  4007. ::CloseHandle(event);
  4008. return ::WSAGetLastError();
  4009. }
  4010. }
  4011. ::CloseHandle(event);
  4012. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4013. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4014. return 0;
  4015. }
  4016. return ret;
  4017. #elif TARGET_OS_MAC
  4018. if (!node) { return EAI_NONAME; }
  4019. // macOS implementation using CFHost API for asynchronous DNS resolution
  4020. CFStringRef hostname_ref = CFStringCreateWithCString(
  4021. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4022. if (!hostname_ref) { return EAI_MEMORY; }
  4023. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4024. CFRelease(hostname_ref);
  4025. if (!host_ref) { return EAI_MEMORY; }
  4026. // Set up context for callback
  4027. struct CFHostContext {
  4028. bool completed = false;
  4029. bool success = false;
  4030. CFArrayRef addresses = nullptr;
  4031. std::mutex mutex;
  4032. std::condition_variable cv;
  4033. } context;
  4034. CFHostClientContext client_context;
  4035. memset(&client_context, 0, sizeof(client_context));
  4036. client_context.info = &context;
  4037. // Set callback
  4038. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4039. const CFStreamError *error, void *info) {
  4040. auto ctx = static_cast<CFHostContext *>(info);
  4041. std::lock_guard<std::mutex> lock(ctx->mutex);
  4042. if (error && error->error != 0) {
  4043. ctx->success = false;
  4044. } else {
  4045. Boolean hasBeenResolved;
  4046. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4047. if (ctx->addresses && hasBeenResolved) {
  4048. CFRetain(ctx->addresses);
  4049. ctx->success = true;
  4050. } else {
  4051. ctx->success = false;
  4052. }
  4053. }
  4054. ctx->completed = true;
  4055. ctx->cv.notify_one();
  4056. };
  4057. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4058. CFRelease(host_ref);
  4059. return EAI_SYSTEM;
  4060. }
  4061. // Schedule on run loop
  4062. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4063. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4064. // Start resolution
  4065. CFStreamError stream_error;
  4066. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4067. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4068. CFRelease(host_ref);
  4069. return EAI_FAIL;
  4070. }
  4071. // Wait for completion with timeout
  4072. auto timeout_time =
  4073. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4074. bool timed_out = false;
  4075. {
  4076. std::unique_lock<std::mutex> lock(context.mutex);
  4077. while (!context.completed) {
  4078. auto now = std::chrono::steady_clock::now();
  4079. if (now >= timeout_time) {
  4080. timed_out = true;
  4081. break;
  4082. }
  4083. // Run the runloop for a short time
  4084. lock.unlock();
  4085. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4086. lock.lock();
  4087. }
  4088. }
  4089. // Clean up
  4090. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4091. CFHostSetClient(host_ref, nullptr, nullptr);
  4092. if (timed_out || !context.completed) {
  4093. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4094. CFRelease(host_ref);
  4095. return EAI_AGAIN;
  4096. }
  4097. if (!context.success || !context.addresses) {
  4098. CFRelease(host_ref);
  4099. return EAI_NODATA;
  4100. }
  4101. // Convert CFArray to addrinfo
  4102. CFIndex count = CFArrayGetCount(context.addresses);
  4103. if (count == 0) {
  4104. CFRelease(context.addresses);
  4105. CFRelease(host_ref);
  4106. return EAI_NODATA;
  4107. }
  4108. struct addrinfo *result_addrinfo = nullptr;
  4109. struct addrinfo **current = &result_addrinfo;
  4110. for (CFIndex i = 0; i < count; i++) {
  4111. CFDataRef addr_data =
  4112. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4113. if (!addr_data) continue;
  4114. const struct sockaddr *sockaddr_ptr =
  4115. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4116. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4117. // Allocate addrinfo structure
  4118. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4119. if (!*current) {
  4120. freeaddrinfo(result_addrinfo);
  4121. CFRelease(context.addresses);
  4122. CFRelease(host_ref);
  4123. return EAI_MEMORY;
  4124. }
  4125. memset(*current, 0, sizeof(struct addrinfo));
  4126. // Set up addrinfo fields
  4127. (*current)->ai_family = sockaddr_ptr->sa_family;
  4128. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4129. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4130. (*current)->ai_addrlen = sockaddr_len;
  4131. // Copy sockaddr
  4132. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4133. if (!(*current)->ai_addr) {
  4134. freeaddrinfo(result_addrinfo);
  4135. CFRelease(context.addresses);
  4136. CFRelease(host_ref);
  4137. return EAI_MEMORY;
  4138. }
  4139. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4140. // Set port if service is specified
  4141. if (service && strlen(service) > 0) {
  4142. int port = atoi(service);
  4143. if (port > 0) {
  4144. if (sockaddr_ptr->sa_family == AF_INET) {
  4145. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4146. ->sin_port = htons(static_cast<uint16_t>(port));
  4147. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4148. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4149. ->sin6_port = htons(static_cast<uint16_t>(port));
  4150. }
  4151. }
  4152. }
  4153. current = &((*current)->ai_next);
  4154. }
  4155. CFRelease(context.addresses);
  4156. CFRelease(host_ref);
  4157. *res = result_addrinfo;
  4158. return 0;
  4159. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  4160. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  4161. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  4162. struct gaicb request;
  4163. struct gaicb *requests[1] = {&request};
  4164. struct sigevent sevp;
  4165. struct timespec timeout;
  4166. // Initialize the request structure
  4167. memset(&request, 0, sizeof(request));
  4168. request.ar_name = node;
  4169. request.ar_service = service;
  4170. request.ar_request = hints;
  4171. // Set up timeout
  4172. timeout.tv_sec = timeout_sec;
  4173. timeout.tv_nsec = 0;
  4174. // Initialize sigevent structure (not used, but required)
  4175. memset(&sevp, 0, sizeof(sevp));
  4176. sevp.sigev_notify = SIGEV_NONE;
  4177. // Start asynchronous resolution
  4178. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  4179. if (start_result != 0) { return start_result; }
  4180. // Wait for completion with timeout
  4181. int wait_result =
  4182. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  4183. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  4184. // Completed successfully, get the result
  4185. int gai_result = gai_error(&request);
  4186. if (gai_result == 0) {
  4187. *res = request.ar_result;
  4188. return 0;
  4189. } else {
  4190. // Clean up on error
  4191. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  4192. return gai_result;
  4193. }
  4194. } else if (wait_result == EAI_AGAIN) {
  4195. // Timeout occurred, cancel the request
  4196. gai_cancel(&request);
  4197. return EAI_AGAIN;
  4198. } else {
  4199. // Other error occurred
  4200. gai_cancel(&request);
  4201. return wait_result;
  4202. }
  4203. #else
  4204. // Fallback implementation using thread-based timeout for other Unix systems
  4205. struct GetAddrInfoState {
  4206. ~GetAddrInfoState() {
  4207. if (info) { freeaddrinfo(info); }
  4208. }
  4209. std::mutex mutex;
  4210. std::condition_variable result_cv;
  4211. bool completed = false;
  4212. int result = EAI_SYSTEM;
  4213. std::string node;
  4214. std::string service;
  4215. struct addrinfo hints;
  4216. struct addrinfo *info = nullptr;
  4217. };
  4218. // Allocate on the heap, so the resolver thread can keep using the data.
  4219. auto state = std::make_shared<GetAddrInfoState>();
  4220. if (node) { state->node = node; }
  4221. state->service = service;
  4222. state->hints = *hints;
  4223. std::thread resolve_thread([state]() {
  4224. auto thread_result =
  4225. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4226. &state->info);
  4227. std::lock_guard<std::mutex> lock(state->mutex);
  4228. state->result = thread_result;
  4229. state->completed = true;
  4230. state->result_cv.notify_one();
  4231. });
  4232. // Wait for completion or timeout
  4233. std::unique_lock<std::mutex> lock(state->mutex);
  4234. auto finished =
  4235. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4236. [&] { return state->completed; });
  4237. if (finished) {
  4238. // Operation completed within timeout
  4239. resolve_thread.join();
  4240. *res = state->info;
  4241. state->info = nullptr; // Pass ownership to caller
  4242. return state->result;
  4243. } else {
  4244. // Timeout occurred
  4245. resolve_thread.detach(); // Let the thread finish in background
  4246. return EAI_AGAIN; // Return timeout error
  4247. }
  4248. #endif
  4249. #else
  4250. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4251. return getaddrinfo(node, service, hints, res);
  4252. #endif
  4253. }
  4254. template <typename BindOrConnect>
  4255. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4256. int address_family, int socket_flags, bool tcp_nodelay,
  4257. bool ipv6_v6only, SocketOptions socket_options,
  4258. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4259. // Get address info
  4260. const char *node = nullptr;
  4261. struct addrinfo hints;
  4262. struct addrinfo *result;
  4263. memset(&hints, 0, sizeof(struct addrinfo));
  4264. hints.ai_socktype = SOCK_STREAM;
  4265. hints.ai_protocol = IPPROTO_IP;
  4266. if (!ip.empty()) {
  4267. node = ip.c_str();
  4268. // Ask getaddrinfo to convert IP in c-string to address
  4269. hints.ai_family = AF_UNSPEC;
  4270. hints.ai_flags = AI_NUMERICHOST;
  4271. } else {
  4272. if (!host.empty()) { node = host.c_str(); }
  4273. hints.ai_family = address_family;
  4274. hints.ai_flags = socket_flags;
  4275. }
  4276. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  4277. if (hints.ai_family == AF_UNIX) {
  4278. const auto addrlen = host.length();
  4279. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  4280. #ifdef SOCK_CLOEXEC
  4281. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  4282. hints.ai_protocol);
  4283. #else
  4284. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4285. #endif
  4286. if (sock != INVALID_SOCKET) {
  4287. sockaddr_un addr{};
  4288. addr.sun_family = AF_UNIX;
  4289. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  4290. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  4291. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  4292. hints.ai_addrlen = static_cast<socklen_t>(
  4293. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  4294. #ifndef SOCK_CLOEXEC
  4295. #ifndef _WIN32
  4296. fcntl(sock, F_SETFD, FD_CLOEXEC);
  4297. #endif
  4298. #endif
  4299. if (socket_options) { socket_options(sock); }
  4300. #ifdef _WIN32
  4301. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  4302. // remove the option.
  4303. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  4304. #endif
  4305. bool dummy;
  4306. if (!bind_or_connect(sock, hints, dummy)) {
  4307. close_socket(sock);
  4308. sock = INVALID_SOCKET;
  4309. }
  4310. }
  4311. return sock;
  4312. }
  4313. #endif
  4314. auto service = std::to_string(port);
  4315. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  4316. timeout_sec)) {
  4317. #if defined __linux__ && !defined __ANDROID__
  4318. res_init();
  4319. #endif
  4320. return INVALID_SOCKET;
  4321. }
  4322. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4323. for (auto rp = result; rp; rp = rp->ai_next) {
  4324. // Create a socket
  4325. #ifdef _WIN32
  4326. auto sock =
  4327. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  4328. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  4329. /**
  4330. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  4331. * and above the socket creation fails on older Windows Systems.
  4332. *
  4333. * Let's try to create a socket the old way in this case.
  4334. *
  4335. * Reference:
  4336. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  4337. *
  4338. * WSA_FLAG_NO_HANDLE_INHERIT:
  4339. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  4340. * SP1, and later
  4341. *
  4342. */
  4343. if (sock == INVALID_SOCKET) {
  4344. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4345. }
  4346. #else
  4347. #ifdef SOCK_CLOEXEC
  4348. auto sock =
  4349. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  4350. #else
  4351. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4352. #endif
  4353. #endif
  4354. if (sock == INVALID_SOCKET) { continue; }
  4355. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  4356. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  4357. close_socket(sock);
  4358. continue;
  4359. }
  4360. #endif
  4361. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  4362. if (rp->ai_family == AF_INET6) {
  4363. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  4364. }
  4365. if (socket_options) { socket_options(sock); }
  4366. // bind or connect
  4367. auto quit = false;
  4368. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  4369. close_socket(sock);
  4370. if (quit) { break; }
  4371. }
  4372. return INVALID_SOCKET;
  4373. }
  4374. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  4375. #ifdef _WIN32
  4376. auto flags = nonblocking ? 1UL : 0UL;
  4377. ioctlsocket(sock, FIONBIO, &flags);
  4378. #else
  4379. auto flags = fcntl(sock, F_GETFL, 0);
  4380. fcntl(sock, F_SETFL,
  4381. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  4382. #endif
  4383. }
  4384. inline bool is_connection_error() {
  4385. #ifdef _WIN32
  4386. return WSAGetLastError() != WSAEWOULDBLOCK;
  4387. #else
  4388. return errno != EINPROGRESS;
  4389. #endif
  4390. }
  4391. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  4392. struct addrinfo hints;
  4393. struct addrinfo *result;
  4394. memset(&hints, 0, sizeof(struct addrinfo));
  4395. hints.ai_family = AF_UNSPEC;
  4396. hints.ai_socktype = SOCK_STREAM;
  4397. hints.ai_protocol = 0;
  4398. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  4399. return false;
  4400. }
  4401. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4402. auto ret = false;
  4403. for (auto rp = result; rp; rp = rp->ai_next) {
  4404. const auto &ai = *rp;
  4405. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4406. ret = true;
  4407. break;
  4408. }
  4409. }
  4410. return ret;
  4411. }
  4412. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  4413. #define USE_IF2IP
  4414. #endif
  4415. #ifdef USE_IF2IP
  4416. inline std::string if2ip(int address_family, const std::string &ifn) {
  4417. struct ifaddrs *ifap;
  4418. getifaddrs(&ifap);
  4419. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  4420. std::string addr_candidate;
  4421. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  4422. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  4423. (AF_UNSPEC == address_family ||
  4424. ifa->ifa_addr->sa_family == address_family)) {
  4425. if (ifa->ifa_addr->sa_family == AF_INET) {
  4426. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  4427. char buf[INET_ADDRSTRLEN];
  4428. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  4429. return std::string(buf, INET_ADDRSTRLEN);
  4430. }
  4431. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  4432. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  4433. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  4434. char buf[INET6_ADDRSTRLEN] = {};
  4435. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  4436. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  4437. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  4438. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  4439. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  4440. } else {
  4441. return std::string(buf, INET6_ADDRSTRLEN);
  4442. }
  4443. }
  4444. }
  4445. }
  4446. }
  4447. }
  4448. return addr_candidate;
  4449. }
  4450. #endif
  4451. inline socket_t create_client_socket(
  4452. const std::string &host, const std::string &ip, int port,
  4453. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  4454. SocketOptions socket_options, time_t connection_timeout_sec,
  4455. time_t connection_timeout_usec, time_t read_timeout_sec,
  4456. time_t read_timeout_usec, time_t write_timeout_sec,
  4457. time_t write_timeout_usec, const std::string &intf, Error &error) {
  4458. auto sock = create_socket(
  4459. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  4460. std::move(socket_options),
  4461. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  4462. if (!intf.empty()) {
  4463. #ifdef USE_IF2IP
  4464. auto ip_from_if = if2ip(address_family, intf);
  4465. if (ip_from_if.empty()) { ip_from_if = intf; }
  4466. if (!bind_ip_address(sock2, ip_from_if)) {
  4467. error = Error::BindIPAddress;
  4468. return false;
  4469. }
  4470. #endif
  4471. }
  4472. set_nonblocking(sock2, true);
  4473. auto ret =
  4474. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  4475. if (ret < 0) {
  4476. if (is_connection_error()) {
  4477. error = Error::Connection;
  4478. return false;
  4479. }
  4480. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  4481. connection_timeout_usec);
  4482. if (error != Error::Success) {
  4483. if (error == Error::ConnectionTimeout) { quit = true; }
  4484. return false;
  4485. }
  4486. }
  4487. set_nonblocking(sock2, false);
  4488. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  4489. read_timeout_usec);
  4490. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  4491. write_timeout_usec);
  4492. error = Error::Success;
  4493. return true;
  4494. },
  4495. connection_timeout_sec); // Pass DNS timeout
  4496. if (sock != INVALID_SOCKET) {
  4497. error = Error::Success;
  4498. } else {
  4499. if (error == Error::Success) { error = Error::Connection; }
  4500. }
  4501. return sock;
  4502. }
  4503. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  4504. socklen_t addr_len, std::string &ip, int &port) {
  4505. if (addr.ss_family == AF_INET) {
  4506. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  4507. } else if (addr.ss_family == AF_INET6) {
  4508. port =
  4509. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  4510. } else {
  4511. return false;
  4512. }
  4513. std::array<char, NI_MAXHOST> ipstr{};
  4514. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  4515. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  4516. 0, NI_NUMERICHOST)) {
  4517. return false;
  4518. }
  4519. ip = ipstr.data();
  4520. return true;
  4521. }
  4522. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4523. struct sockaddr_storage addr;
  4524. socklen_t addr_len = sizeof(addr);
  4525. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4526. &addr_len)) {
  4527. get_ip_and_port(addr, addr_len, ip, port);
  4528. }
  4529. }
  4530. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4531. struct sockaddr_storage addr;
  4532. socklen_t addr_len = sizeof(addr);
  4533. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4534. &addr_len)) {
  4535. #ifndef _WIN32
  4536. if (addr.ss_family == AF_UNIX) {
  4537. #if defined(__linux__)
  4538. struct ucred ucred;
  4539. socklen_t len = sizeof(ucred);
  4540. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  4541. port = ucred.pid;
  4542. }
  4543. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  4544. pid_t pid;
  4545. socklen_t len = sizeof(pid);
  4546. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  4547. port = pid;
  4548. }
  4549. #endif
  4550. return;
  4551. }
  4552. #endif
  4553. get_ip_and_port(addr, addr_len, ip, port);
  4554. }
  4555. }
  4556. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  4557. unsigned int h) {
  4558. return (l == 0)
  4559. ? h
  4560. : str2tag_core(
  4561. s + 1, l - 1,
  4562. // Unsets the 6 high bits of h, therefore no overflow happens
  4563. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  4564. h * 33) ^
  4565. static_cast<unsigned char>(*s));
  4566. }
  4567. inline unsigned int str2tag(const std::string &s) {
  4568. return str2tag_core(s.data(), s.size(), 0);
  4569. }
  4570. namespace udl {
  4571. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  4572. return str2tag_core(s, l, 0);
  4573. }
  4574. } // namespace udl
  4575. inline std::string
  4576. find_content_type(const std::string &path,
  4577. const std::map<std::string, std::string> &user_data,
  4578. const std::string &default_content_type) {
  4579. auto ext = file_extension(path);
  4580. auto it = user_data.find(ext);
  4581. if (it != user_data.end()) { return it->second; }
  4582. using udl::operator""_t;
  4583. switch (str2tag(ext)) {
  4584. default: return default_content_type;
  4585. case "css"_t: return "text/css";
  4586. case "csv"_t: return "text/csv";
  4587. case "htm"_t:
  4588. case "html"_t: return "text/html";
  4589. case "js"_t:
  4590. case "mjs"_t: return "text/javascript";
  4591. case "txt"_t: return "text/plain";
  4592. case "vtt"_t: return "text/vtt";
  4593. case "apng"_t: return "image/apng";
  4594. case "avif"_t: return "image/avif";
  4595. case "bmp"_t: return "image/bmp";
  4596. case "gif"_t: return "image/gif";
  4597. case "png"_t: return "image/png";
  4598. case "svg"_t: return "image/svg+xml";
  4599. case "webp"_t: return "image/webp";
  4600. case "ico"_t: return "image/x-icon";
  4601. case "tif"_t: return "image/tiff";
  4602. case "tiff"_t: return "image/tiff";
  4603. case "jpg"_t:
  4604. case "jpeg"_t: return "image/jpeg";
  4605. case "mp4"_t: return "video/mp4";
  4606. case "mpeg"_t: return "video/mpeg";
  4607. case "webm"_t: return "video/webm";
  4608. case "mp3"_t: return "audio/mp3";
  4609. case "mpga"_t: return "audio/mpeg";
  4610. case "weba"_t: return "audio/webm";
  4611. case "wav"_t: return "audio/wave";
  4612. case "otf"_t: return "font/otf";
  4613. case "ttf"_t: return "font/ttf";
  4614. case "woff"_t: return "font/woff";
  4615. case "woff2"_t: return "font/woff2";
  4616. case "7z"_t: return "application/x-7z-compressed";
  4617. case "atom"_t: return "application/atom+xml";
  4618. case "pdf"_t: return "application/pdf";
  4619. case "json"_t: return "application/json";
  4620. case "rss"_t: return "application/rss+xml";
  4621. case "tar"_t: return "application/x-tar";
  4622. case "xht"_t:
  4623. case "xhtml"_t: return "application/xhtml+xml";
  4624. case "xslt"_t: return "application/xslt+xml";
  4625. case "xml"_t: return "application/xml";
  4626. case "gz"_t: return "application/gzip";
  4627. case "zip"_t: return "application/zip";
  4628. case "wasm"_t: return "application/wasm";
  4629. }
  4630. }
  4631. inline bool can_compress_content_type(const std::string &content_type) {
  4632. using udl::operator""_t;
  4633. auto tag = str2tag(content_type);
  4634. switch (tag) {
  4635. case "image/svg+xml"_t:
  4636. case "application/javascript"_t:
  4637. case "application/json"_t:
  4638. case "application/xml"_t:
  4639. case "application/protobuf"_t:
  4640. case "application/xhtml+xml"_t: return true;
  4641. case "text/event-stream"_t: return false;
  4642. default: return !content_type.rfind("text/", 0);
  4643. }
  4644. }
  4645. inline EncodingType encoding_type(const Request &req, const Response &res) {
  4646. auto ret =
  4647. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  4648. if (!ret) { return EncodingType::None; }
  4649. const auto &s = req.get_header_value("Accept-Encoding");
  4650. (void)(s);
  4651. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4652. // TODO: 'Accept-Encoding' has br, not br;q=0
  4653. ret = s.find("br") != std::string::npos;
  4654. if (ret) { return EncodingType::Brotli; }
  4655. #endif
  4656. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4657. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  4658. ret = s.find("gzip") != std::string::npos;
  4659. if (ret) { return EncodingType::Gzip; }
  4660. #endif
  4661. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4662. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  4663. ret = s.find("zstd") != std::string::npos;
  4664. if (ret) { return EncodingType::Zstd; }
  4665. #endif
  4666. return EncodingType::None;
  4667. }
  4668. inline bool nocompressor::compress(const char *data, size_t data_length,
  4669. bool /*last*/, Callback callback) {
  4670. if (!data_length) { return true; }
  4671. return callback(data, data_length);
  4672. }
  4673. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4674. inline gzip_compressor::gzip_compressor() {
  4675. std::memset(&strm_, 0, sizeof(strm_));
  4676. strm_.zalloc = Z_NULL;
  4677. strm_.zfree = Z_NULL;
  4678. strm_.opaque = Z_NULL;
  4679. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  4680. Z_DEFAULT_STRATEGY) == Z_OK;
  4681. }
  4682. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  4683. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  4684. bool last, Callback callback) {
  4685. assert(is_valid_);
  4686. do {
  4687. constexpr size_t max_avail_in =
  4688. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4689. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4690. (std::min)(data_length, max_avail_in));
  4691. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4692. data_length -= strm_.avail_in;
  4693. data += strm_.avail_in;
  4694. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  4695. auto ret = Z_OK;
  4696. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4697. do {
  4698. strm_.avail_out = static_cast<uInt>(buff.size());
  4699. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4700. ret = deflate(&strm_, flush);
  4701. if (ret == Z_STREAM_ERROR) { return false; }
  4702. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4703. return false;
  4704. }
  4705. } while (strm_.avail_out == 0);
  4706. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  4707. (flush == Z_NO_FLUSH && ret == Z_OK));
  4708. assert(strm_.avail_in == 0);
  4709. } while (data_length > 0);
  4710. return true;
  4711. }
  4712. inline gzip_decompressor::gzip_decompressor() {
  4713. std::memset(&strm_, 0, sizeof(strm_));
  4714. strm_.zalloc = Z_NULL;
  4715. strm_.zfree = Z_NULL;
  4716. strm_.opaque = Z_NULL;
  4717. // 15 is the value of wbits, which should be at the maximum possible value
  4718. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  4719. // that the stream type should be automatically detected either gzip or
  4720. // deflate.
  4721. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  4722. }
  4723. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  4724. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  4725. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  4726. Callback callback) {
  4727. assert(is_valid_);
  4728. auto ret = Z_OK;
  4729. do {
  4730. constexpr size_t max_avail_in =
  4731. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4732. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4733. (std::min)(data_length, max_avail_in));
  4734. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4735. data_length -= strm_.avail_in;
  4736. data += strm_.avail_in;
  4737. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4738. while (strm_.avail_in > 0 && ret == Z_OK) {
  4739. strm_.avail_out = static_cast<uInt>(buff.size());
  4740. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4741. ret = inflate(&strm_, Z_NO_FLUSH);
  4742. assert(ret != Z_STREAM_ERROR);
  4743. switch (ret) {
  4744. case Z_NEED_DICT:
  4745. case Z_DATA_ERROR:
  4746. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  4747. }
  4748. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4749. return false;
  4750. }
  4751. }
  4752. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  4753. } while (data_length > 0);
  4754. return true;
  4755. }
  4756. #endif
  4757. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4758. inline brotli_compressor::brotli_compressor() {
  4759. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  4760. }
  4761. inline brotli_compressor::~brotli_compressor() {
  4762. BrotliEncoderDestroyInstance(state_);
  4763. }
  4764. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  4765. bool last, Callback callback) {
  4766. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4767. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  4768. auto available_in = data_length;
  4769. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4770. for (;;) {
  4771. if (last) {
  4772. if (BrotliEncoderIsFinished(state_)) { break; }
  4773. } else {
  4774. if (!available_in) { break; }
  4775. }
  4776. auto available_out = buff.size();
  4777. auto next_out = buff.data();
  4778. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  4779. &available_out, &next_out, nullptr)) {
  4780. return false;
  4781. }
  4782. auto output_bytes = buff.size() - available_out;
  4783. if (output_bytes) {
  4784. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  4785. }
  4786. }
  4787. return true;
  4788. }
  4789. inline brotli_decompressor::brotli_decompressor() {
  4790. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  4791. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  4792. : BROTLI_DECODER_RESULT_ERROR;
  4793. }
  4794. inline brotli_decompressor::~brotli_decompressor() {
  4795. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  4796. }
  4797. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  4798. inline bool brotli_decompressor::decompress(const char *data,
  4799. size_t data_length,
  4800. Callback callback) {
  4801. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4802. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  4803. return 0;
  4804. }
  4805. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4806. size_t avail_in = data_length;
  4807. size_t total_out;
  4808. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  4809. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4810. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  4811. char *next_out = buff.data();
  4812. size_t avail_out = buff.size();
  4813. decoder_r = BrotliDecoderDecompressStream(
  4814. decoder_s, &avail_in, &next_in, &avail_out,
  4815. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  4816. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  4817. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  4818. }
  4819. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4820. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  4821. }
  4822. #endif
  4823. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4824. inline zstd_compressor::zstd_compressor() {
  4825. ctx_ = ZSTD_createCCtx();
  4826. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  4827. }
  4828. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  4829. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  4830. bool last, Callback callback) {
  4831. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4832. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  4833. ZSTD_inBuffer input = {data, data_length, 0};
  4834. bool finished;
  4835. do {
  4836. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4837. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  4838. if (ZSTD_isError(remaining)) { return false; }
  4839. if (!callback(buff.data(), output.pos)) { return false; }
  4840. finished = last ? (remaining == 0) : (input.pos == input.size);
  4841. } while (!finished);
  4842. return true;
  4843. }
  4844. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  4845. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  4846. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  4847. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  4848. Callback callback) {
  4849. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4850. ZSTD_inBuffer input = {data, data_length, 0};
  4851. while (input.pos < input.size) {
  4852. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4853. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  4854. if (ZSTD_isError(remaining)) { return false; }
  4855. if (!callback(buff.data(), output.pos)) { return false; }
  4856. }
  4857. return true;
  4858. }
  4859. #endif
  4860. inline std::unique_ptr<decompressor>
  4861. create_decompressor(const std::string &encoding) {
  4862. std::unique_ptr<decompressor> decompressor;
  4863. if (encoding == "gzip" || encoding == "deflate") {
  4864. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4865. decompressor = detail::make_unique<gzip_decompressor>();
  4866. #endif
  4867. } else if (encoding.find("br") != std::string::npos) {
  4868. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4869. decompressor = detail::make_unique<brotli_decompressor>();
  4870. #endif
  4871. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  4872. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4873. decompressor = detail::make_unique<zstd_decompressor>();
  4874. #endif
  4875. }
  4876. return decompressor;
  4877. }
  4878. inline bool is_prohibited_header_name(const std::string &name) {
  4879. using udl::operator""_t;
  4880. switch (str2tag(name)) {
  4881. case "REMOTE_ADDR"_t:
  4882. case "REMOTE_PORT"_t:
  4883. case "LOCAL_ADDR"_t:
  4884. case "LOCAL_PORT"_t: return true;
  4885. default: return false;
  4886. }
  4887. }
  4888. inline bool has_header(const Headers &headers, const std::string &key) {
  4889. if (is_prohibited_header_name(key)) { return false; }
  4890. return headers.find(key) != headers.end();
  4891. }
  4892. inline const char *get_header_value(const Headers &headers,
  4893. const std::string &key, const char *def,
  4894. size_t id) {
  4895. if (is_prohibited_header_name(key)) {
  4896. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4897. std::string msg = "Prohibited header name '" + key + "' is specified.";
  4898. throw std::invalid_argument(msg);
  4899. #else
  4900. return "";
  4901. #endif
  4902. }
  4903. auto rng = headers.equal_range(key);
  4904. auto it = rng.first;
  4905. std::advance(it, static_cast<ssize_t>(id));
  4906. if (it != rng.second) { return it->second.c_str(); }
  4907. return def;
  4908. }
  4909. inline bool read_headers(Stream &strm, Headers &headers) {
  4910. const auto bufsiz = 2048;
  4911. char buf[bufsiz];
  4912. stream_line_reader line_reader(strm, buf, bufsiz);
  4913. size_t header_count = 0;
  4914. for (;;) {
  4915. if (!line_reader.getline()) { return false; }
  4916. // Check if the line ends with CRLF.
  4917. auto line_terminator_len = 2;
  4918. if (line_reader.end_with_crlf()) {
  4919. // Blank line indicates end of headers.
  4920. if (line_reader.size() == 2) { break; }
  4921. } else {
  4922. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4923. // Blank line indicates end of headers.
  4924. if (line_reader.size() == 1) { break; }
  4925. line_terminator_len = 1;
  4926. #else
  4927. continue; // Skip invalid line.
  4928. #endif
  4929. }
  4930. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4931. // Check header count limit
  4932. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4933. // Exclude line terminator
  4934. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  4935. if (!parse_header(line_reader.ptr(), end,
  4936. [&](const std::string &key, const std::string &val) {
  4937. headers.emplace(key, val);
  4938. })) {
  4939. return false;
  4940. }
  4941. header_count++;
  4942. }
  4943. return true;
  4944. }
  4945. enum class ReadContentResult {
  4946. Success, // Successfully read the content
  4947. PayloadTooLarge, // The content exceeds the specified payload limit
  4948. Error // An error occurred while reading the content
  4949. };
  4950. inline ReadContentResult read_content_with_length(
  4951. Stream &strm, size_t len, DownloadProgress progress,
  4952. ContentReceiverWithProgress out,
  4953. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  4954. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4955. detail::BodyReader br;
  4956. br.stream = &strm;
  4957. br.has_content_length = true;
  4958. br.content_length = len;
  4959. br.payload_max_length = payload_max_length;
  4960. br.chunked = false;
  4961. br.bytes_read = 0;
  4962. br.last_error = Error::Success;
  4963. size_t r = 0;
  4964. while (r < len) {
  4965. auto read_len = static_cast<size_t>(len - r);
  4966. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  4967. auto n = detail::read_body_content(&strm, br, buf, to_read);
  4968. if (n <= 0) {
  4969. // Check if it was a payload size error
  4970. if (br.last_error == Error::ExceedMaxPayloadSize) {
  4971. return ReadContentResult::PayloadTooLarge;
  4972. }
  4973. return ReadContentResult::Error;
  4974. }
  4975. if (!out(buf, static_cast<size_t>(n), r, len)) {
  4976. return ReadContentResult::Error;
  4977. }
  4978. r += static_cast<size_t>(n);
  4979. if (progress) {
  4980. if (!progress(r, len)) { return ReadContentResult::Error; }
  4981. }
  4982. }
  4983. return ReadContentResult::Success;
  4984. }
  4985. inline ReadContentResult
  4986. read_content_without_length(Stream &strm, size_t payload_max_length,
  4987. ContentReceiverWithProgress out) {
  4988. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4989. size_t r = 0;
  4990. for (;;) {
  4991. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  4992. if (n == 0) { return ReadContentResult::Success; }
  4993. if (n < 0) { return ReadContentResult::Error; }
  4994. // Check if adding this data would exceed the payload limit
  4995. if (r > payload_max_length ||
  4996. payload_max_length - r < static_cast<size_t>(n)) {
  4997. return ReadContentResult::PayloadTooLarge;
  4998. }
  4999. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  5000. return ReadContentResult::Error;
  5001. }
  5002. r += static_cast<size_t>(n);
  5003. }
  5004. return ReadContentResult::Success;
  5005. }
  5006. template <typename T>
  5007. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  5008. size_t payload_max_length,
  5009. ContentReceiverWithProgress out) {
  5010. detail::ChunkedDecoder dec(strm);
  5011. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  5012. size_t total_len = 0;
  5013. for (;;) {
  5014. size_t chunk_offset = 0;
  5015. size_t chunk_total = 0;
  5016. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  5017. if (n < 0) { return ReadContentResult::Error; }
  5018. if (n == 0) {
  5019. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  5020. return ReadContentResult::Error;
  5021. }
  5022. return ReadContentResult::Success;
  5023. }
  5024. if (total_len > payload_max_length ||
  5025. payload_max_length - total_len < static_cast<size_t>(n)) {
  5026. return ReadContentResult::PayloadTooLarge;
  5027. }
  5028. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  5029. return ReadContentResult::Error;
  5030. }
  5031. total_len += static_cast<size_t>(n);
  5032. }
  5033. }
  5034. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  5035. return case_ignore::equal(
  5036. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  5037. }
  5038. template <typename T, typename U>
  5039. bool prepare_content_receiver(T &x, int &status,
  5040. ContentReceiverWithProgress receiver,
  5041. bool decompress, U callback) {
  5042. if (decompress) {
  5043. std::string encoding = x.get_header_value("Content-Encoding");
  5044. std::unique_ptr<decompressor> decompressor;
  5045. if (!encoding.empty()) {
  5046. decompressor = detail::create_decompressor(encoding);
  5047. if (!decompressor) {
  5048. // Unsupported encoding or no support compiled in
  5049. status = StatusCode::UnsupportedMediaType_415;
  5050. return false;
  5051. }
  5052. }
  5053. if (decompressor) {
  5054. if (decompressor->is_valid()) {
  5055. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  5056. size_t off, size_t len) {
  5057. return decompressor->decompress(buf, n,
  5058. [&](const char *buf2, size_t n2) {
  5059. return receiver(buf2, n2, off, len);
  5060. });
  5061. };
  5062. return callback(std::move(out));
  5063. } else {
  5064. status = StatusCode::InternalServerError_500;
  5065. return false;
  5066. }
  5067. }
  5068. }
  5069. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  5070. size_t len) {
  5071. return receiver(buf, n, off, len);
  5072. };
  5073. return callback(std::move(out));
  5074. }
  5075. template <typename T>
  5076. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  5077. DownloadProgress progress,
  5078. ContentReceiverWithProgress receiver, bool decompress) {
  5079. return prepare_content_receiver(
  5080. x, status, std::move(receiver), decompress,
  5081. [&](const ContentReceiverWithProgress &out) {
  5082. auto ret = true;
  5083. auto exceed_payload_max_length = false;
  5084. if (is_chunked_transfer_encoding(x.headers)) {
  5085. auto result = read_content_chunked(strm, x, payload_max_length, out);
  5086. if (result == ReadContentResult::Success) {
  5087. ret = true;
  5088. } else if (result == ReadContentResult::PayloadTooLarge) {
  5089. exceed_payload_max_length = true;
  5090. ret = false;
  5091. } else {
  5092. ret = false;
  5093. }
  5094. } else if (!has_header(x.headers, "Content-Length")) {
  5095. auto result =
  5096. read_content_without_length(strm, payload_max_length, out);
  5097. if (result == ReadContentResult::Success) {
  5098. ret = true;
  5099. } else if (result == ReadContentResult::PayloadTooLarge) {
  5100. exceed_payload_max_length = true;
  5101. ret = false;
  5102. } else {
  5103. ret = false;
  5104. }
  5105. } else {
  5106. auto is_invalid_value = false;
  5107. auto len = get_header_value_u64(x.headers, "Content-Length",
  5108. (std::numeric_limits<size_t>::max)(),
  5109. 0, is_invalid_value);
  5110. if (is_invalid_value) {
  5111. ret = false;
  5112. } else if (len > 0) {
  5113. auto result = read_content_with_length(
  5114. strm, len, std::move(progress), out, payload_max_length);
  5115. ret = (result == ReadContentResult::Success);
  5116. if (result == ReadContentResult::PayloadTooLarge) {
  5117. exceed_payload_max_length = true;
  5118. }
  5119. }
  5120. }
  5121. if (!ret) {
  5122. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  5123. : StatusCode::BadRequest_400;
  5124. }
  5125. return ret;
  5126. });
  5127. }
  5128. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  5129. const std::string &path) {
  5130. std::string s = method;
  5131. s += ' ';
  5132. s += path;
  5133. s += " HTTP/1.1\r\n";
  5134. return strm.write(s.data(), s.size());
  5135. }
  5136. inline ssize_t write_response_line(Stream &strm, int status) {
  5137. std::string s = "HTTP/1.1 ";
  5138. s += std::to_string(status);
  5139. s += ' ';
  5140. s += httplib::status_message(status);
  5141. s += "\r\n";
  5142. return strm.write(s.data(), s.size());
  5143. }
  5144. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  5145. ssize_t write_len = 0;
  5146. for (const auto &x : headers) {
  5147. std::string s;
  5148. s = x.first;
  5149. s += ": ";
  5150. s += x.second;
  5151. s += "\r\n";
  5152. auto len = strm.write(s.data(), s.size());
  5153. if (len < 0) { return len; }
  5154. write_len += len;
  5155. }
  5156. auto len = strm.write("\r\n");
  5157. if (len < 0) { return len; }
  5158. write_len += len;
  5159. return write_len;
  5160. }
  5161. inline bool write_data(Stream &strm, const char *d, size_t l) {
  5162. size_t offset = 0;
  5163. while (offset < l) {
  5164. auto length = strm.write(d + offset, l - offset);
  5165. if (length < 0) { return false; }
  5166. offset += static_cast<size_t>(length);
  5167. }
  5168. return true;
  5169. }
  5170. template <typename T>
  5171. inline bool write_content_with_progress(Stream &strm,
  5172. const ContentProvider &content_provider,
  5173. size_t offset, size_t length,
  5174. T is_shutting_down,
  5175. const UploadProgress &upload_progress,
  5176. Error &error) {
  5177. size_t end_offset = offset + length;
  5178. size_t start_offset = offset;
  5179. auto ok = true;
  5180. DataSink data_sink;
  5181. data_sink.write = [&](const char *d, size_t l) -> bool {
  5182. if (ok) {
  5183. if (write_data(strm, d, l)) {
  5184. offset += l;
  5185. if (upload_progress && length > 0) {
  5186. size_t current_written = offset - start_offset;
  5187. if (!upload_progress(current_written, length)) {
  5188. ok = false;
  5189. return false;
  5190. }
  5191. }
  5192. } else {
  5193. ok = false;
  5194. }
  5195. }
  5196. return ok;
  5197. };
  5198. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5199. while (offset < end_offset && !is_shutting_down()) {
  5200. if (!strm.wait_writable()) {
  5201. error = Error::Write;
  5202. return false;
  5203. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  5204. error = Error::Canceled;
  5205. return false;
  5206. } else if (!ok) {
  5207. error = Error::Write;
  5208. return false;
  5209. }
  5210. }
  5211. error = Error::Success;
  5212. return true;
  5213. }
  5214. template <typename T>
  5215. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5216. size_t offset, size_t length, T is_shutting_down,
  5217. Error &error) {
  5218. return write_content_with_progress<T>(strm, content_provider, offset, length,
  5219. is_shutting_down, nullptr, error);
  5220. }
  5221. template <typename T>
  5222. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5223. size_t offset, size_t length,
  5224. const T &is_shutting_down) {
  5225. auto error = Error::Success;
  5226. return write_content(strm, content_provider, offset, length, is_shutting_down,
  5227. error);
  5228. }
  5229. template <typename T>
  5230. inline bool
  5231. write_content_without_length(Stream &strm,
  5232. const ContentProvider &content_provider,
  5233. const T &is_shutting_down) {
  5234. size_t offset = 0;
  5235. auto data_available = true;
  5236. auto ok = true;
  5237. DataSink data_sink;
  5238. data_sink.write = [&](const char *d, size_t l) -> bool {
  5239. if (ok) {
  5240. offset += l;
  5241. if (!write_data(strm, d, l)) { ok = false; }
  5242. }
  5243. return ok;
  5244. };
  5245. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5246. data_sink.done = [&](void) { data_available = false; };
  5247. while (data_available && !is_shutting_down()) {
  5248. if (!strm.wait_writable()) {
  5249. return false;
  5250. } else if (!content_provider(offset, 0, data_sink)) {
  5251. return false;
  5252. } else if (!ok) {
  5253. return false;
  5254. }
  5255. }
  5256. return true;
  5257. }
  5258. template <typename T, typename U>
  5259. inline bool
  5260. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  5261. const T &is_shutting_down, U &compressor, Error &error) {
  5262. size_t offset = 0;
  5263. auto data_available = true;
  5264. auto ok = true;
  5265. DataSink data_sink;
  5266. data_sink.write = [&](const char *d, size_t l) -> bool {
  5267. if (ok) {
  5268. data_available = l > 0;
  5269. offset += l;
  5270. std::string payload;
  5271. if (compressor.compress(d, l, false,
  5272. [&](const char *data, size_t data_len) {
  5273. payload.append(data, data_len);
  5274. return true;
  5275. })) {
  5276. if (!payload.empty()) {
  5277. // Emit chunked response header and footer for each chunk
  5278. auto chunk =
  5279. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5280. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  5281. }
  5282. } else {
  5283. ok = false;
  5284. }
  5285. }
  5286. return ok;
  5287. };
  5288. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5289. auto done_with_trailer = [&](const Headers *trailer) {
  5290. if (!ok) { return; }
  5291. data_available = false;
  5292. std::string payload;
  5293. if (!compressor.compress(nullptr, 0, true,
  5294. [&](const char *data, size_t data_len) {
  5295. payload.append(data, data_len);
  5296. return true;
  5297. })) {
  5298. ok = false;
  5299. return;
  5300. }
  5301. if (!payload.empty()) {
  5302. // Emit chunked response header and footer for each chunk
  5303. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5304. if (!write_data(strm, chunk.data(), chunk.size())) {
  5305. ok = false;
  5306. return;
  5307. }
  5308. }
  5309. constexpr const char done_marker[] = "0\r\n";
  5310. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  5311. // Trailer
  5312. if (trailer) {
  5313. for (const auto &kv : *trailer) {
  5314. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  5315. if (!write_data(strm, field_line.data(), field_line.size())) {
  5316. ok = false;
  5317. }
  5318. }
  5319. }
  5320. constexpr const char crlf[] = "\r\n";
  5321. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  5322. };
  5323. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  5324. data_sink.done_with_trailer = [&](const Headers &trailer) {
  5325. done_with_trailer(&trailer);
  5326. };
  5327. while (data_available && !is_shutting_down()) {
  5328. if (!strm.wait_writable()) {
  5329. error = Error::Write;
  5330. return false;
  5331. } else if (!content_provider(offset, 0, data_sink)) {
  5332. error = Error::Canceled;
  5333. return false;
  5334. } else if (!ok) {
  5335. error = Error::Write;
  5336. return false;
  5337. }
  5338. }
  5339. error = Error::Success;
  5340. return true;
  5341. }
  5342. template <typename T, typename U>
  5343. inline bool write_content_chunked(Stream &strm,
  5344. const ContentProvider &content_provider,
  5345. const T &is_shutting_down, U &compressor) {
  5346. auto error = Error::Success;
  5347. return write_content_chunked(strm, content_provider, is_shutting_down,
  5348. compressor, error);
  5349. }
  5350. template <typename T>
  5351. inline bool redirect(T &cli, Request &req, Response &res,
  5352. const std::string &path, const std::string &location,
  5353. Error &error) {
  5354. Request new_req = req;
  5355. new_req.path = path;
  5356. new_req.redirect_count_ -= 1;
  5357. if (res.status == StatusCode::SeeOther_303 &&
  5358. (req.method != "GET" && req.method != "HEAD")) {
  5359. new_req.method = "GET";
  5360. new_req.body.clear();
  5361. new_req.headers.clear();
  5362. }
  5363. Response new_res;
  5364. auto ret = cli.send(new_req, new_res, error);
  5365. if (ret) {
  5366. req = std::move(new_req);
  5367. res = std::move(new_res);
  5368. if (res.location.empty()) { res.location = location; }
  5369. }
  5370. return ret;
  5371. }
  5372. inline std::string params_to_query_str(const Params &params) {
  5373. std::string query;
  5374. for (auto it = params.begin(); it != params.end(); ++it) {
  5375. if (it != params.begin()) { query += '&'; }
  5376. query += encode_query_component(it->first);
  5377. query += '=';
  5378. query += encode_query_component(it->second);
  5379. }
  5380. return query;
  5381. }
  5382. inline void parse_query_text(const char *data, std::size_t size,
  5383. Params &params) {
  5384. std::set<std::string> cache;
  5385. split(data, data + size, '&', [&](const char *b, const char *e) {
  5386. std::string kv(b, e);
  5387. if (cache.find(kv) != cache.end()) { return; }
  5388. cache.insert(std::move(kv));
  5389. std::string key;
  5390. std::string val;
  5391. divide(b, static_cast<std::size_t>(e - b), '=',
  5392. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  5393. std::size_t rhs_size) {
  5394. key.assign(lhs_data, lhs_size);
  5395. val.assign(rhs_data, rhs_size);
  5396. });
  5397. if (!key.empty()) {
  5398. params.emplace(decode_query_component(key), decode_query_component(val));
  5399. }
  5400. });
  5401. }
  5402. inline void parse_query_text(const std::string &s, Params &params) {
  5403. parse_query_text(s.data(), s.size(), params);
  5404. }
  5405. // Normalize a query string by decoding and re-encoding each key/value pair
  5406. // while preserving the original parameter order. This avoids double-encoding
  5407. // and ensures consistent encoding without reordering (unlike Params which
  5408. // uses std::multimap and sorts keys).
  5409. inline std::string normalize_query_string(const std::string &query) {
  5410. std::string result;
  5411. split(query.data(), query.data() + query.size(), '&',
  5412. [&](const char *b, const char *e) {
  5413. std::string key;
  5414. std::string val;
  5415. divide(b, static_cast<std::size_t>(e - b), '=',
  5416. [&](const char *lhs_data, std::size_t lhs_size,
  5417. const char *rhs_data, std::size_t rhs_size) {
  5418. key.assign(lhs_data, lhs_size);
  5419. val.assign(rhs_data, rhs_size);
  5420. });
  5421. if (!key.empty()) {
  5422. auto dec_key = decode_query_component(key);
  5423. auto dec_val = decode_query_component(val);
  5424. if (!result.empty()) { result += '&'; }
  5425. result += encode_query_component(dec_key);
  5426. if (!val.empty() || std::find(b, e, '=') != e) {
  5427. result += '=';
  5428. result += encode_query_component(dec_val);
  5429. }
  5430. }
  5431. });
  5432. return result;
  5433. }
  5434. inline bool parse_multipart_boundary(const std::string &content_type,
  5435. std::string &boundary) {
  5436. auto boundary_keyword = "boundary=";
  5437. auto pos = content_type.find(boundary_keyword);
  5438. if (pos == std::string::npos) { return false; }
  5439. auto end = content_type.find(';', pos);
  5440. auto beg = pos + strlen(boundary_keyword);
  5441. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  5442. return !boundary.empty();
  5443. }
  5444. inline void parse_disposition_params(const std::string &s, Params &params) {
  5445. std::set<std::string> cache;
  5446. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  5447. std::string kv(b, e);
  5448. if (cache.find(kv) != cache.end()) { return; }
  5449. cache.insert(kv);
  5450. std::string key;
  5451. std::string val;
  5452. split(b, e, '=', [&](const char *b2, const char *e2) {
  5453. if (key.empty()) {
  5454. key.assign(b2, e2);
  5455. } else {
  5456. val.assign(b2, e2);
  5457. }
  5458. });
  5459. if (!key.empty()) {
  5460. params.emplace(trim_double_quotes_copy((key)),
  5461. trim_double_quotes_copy((val)));
  5462. }
  5463. });
  5464. }
  5465. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5466. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  5467. #else
  5468. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  5469. #endif
  5470. auto is_valid = [](const std::string &str) {
  5471. return std::all_of(str.cbegin(), str.cend(),
  5472. [](unsigned char c) { return std::isdigit(c); });
  5473. };
  5474. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  5475. const auto pos = static_cast<size_t>(6);
  5476. const auto len = static_cast<size_t>(s.size() - 6);
  5477. auto all_valid_ranges = true;
  5478. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  5479. if (!all_valid_ranges) { return; }
  5480. const auto it = std::find(b, e, '-');
  5481. if (it == e) {
  5482. all_valid_ranges = false;
  5483. return;
  5484. }
  5485. const auto lhs = std::string(b, it);
  5486. const auto rhs = std::string(it + 1, e);
  5487. if (!is_valid(lhs) || !is_valid(rhs)) {
  5488. all_valid_ranges = false;
  5489. return;
  5490. }
  5491. ssize_t first = -1;
  5492. if (!lhs.empty()) {
  5493. ssize_t v;
  5494. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  5495. if (res.ec == std::errc{}) { first = v; }
  5496. }
  5497. ssize_t last = -1;
  5498. if (!rhs.empty()) {
  5499. ssize_t v;
  5500. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  5501. if (res.ec == std::errc{}) { last = v; }
  5502. }
  5503. if ((first == -1 && last == -1) ||
  5504. (first != -1 && last != -1 && first > last)) {
  5505. all_valid_ranges = false;
  5506. return;
  5507. }
  5508. ranges.emplace_back(first, last);
  5509. });
  5510. return all_valid_ranges && !ranges.empty();
  5511. }
  5512. return false;
  5513. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5514. }
  5515. #else
  5516. } catch (...) { return false; }
  5517. #endif
  5518. inline bool parse_accept_header(const std::string &s,
  5519. std::vector<std::string> &content_types) {
  5520. content_types.clear();
  5521. // Empty string is considered valid (no preference)
  5522. if (s.empty()) { return true; }
  5523. // Check for invalid patterns: leading/trailing commas or consecutive commas
  5524. if (s.front() == ',' || s.back() == ',' ||
  5525. s.find(",,") != std::string::npos) {
  5526. return false;
  5527. }
  5528. struct AcceptEntry {
  5529. std::string media_type;
  5530. double quality;
  5531. int order; // Original order in header
  5532. };
  5533. std::vector<AcceptEntry> entries;
  5534. int order = 0;
  5535. bool has_invalid_entry = false;
  5536. // Split by comma and parse each entry
  5537. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5538. std::string entry(b, e);
  5539. entry = trim_copy(entry);
  5540. if (entry.empty()) {
  5541. has_invalid_entry = true;
  5542. return;
  5543. }
  5544. AcceptEntry accept_entry;
  5545. accept_entry.quality = 1.0; // Default quality
  5546. accept_entry.order = order++;
  5547. // Find q= parameter
  5548. auto q_pos = entry.find(";q=");
  5549. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  5550. if (q_pos != std::string::npos) {
  5551. // Extract media type (before q parameter)
  5552. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  5553. // Extract quality value
  5554. auto q_start = entry.find('=', q_pos) + 1;
  5555. auto q_end = entry.find(';', q_start);
  5556. if (q_end == std::string::npos) { q_end = entry.length(); }
  5557. std::string quality_str =
  5558. trim_copy(entry.substr(q_start, q_end - q_start));
  5559. if (quality_str.empty()) {
  5560. has_invalid_entry = true;
  5561. return;
  5562. }
  5563. {
  5564. double v = 0.0;
  5565. auto res = detail::from_chars(
  5566. quality_str.data(), quality_str.data() + quality_str.size(), v);
  5567. if (res.ec == std::errc{}) {
  5568. accept_entry.quality = v;
  5569. } else {
  5570. has_invalid_entry = true;
  5571. return;
  5572. }
  5573. }
  5574. // Check if quality is in valid range [0.0, 1.0]
  5575. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  5576. has_invalid_entry = true;
  5577. return;
  5578. }
  5579. } else {
  5580. // No quality parameter, use entire entry as media type
  5581. accept_entry.media_type = entry;
  5582. }
  5583. // Remove additional parameters from media type
  5584. auto param_pos = accept_entry.media_type.find(';');
  5585. if (param_pos != std::string::npos) {
  5586. accept_entry.media_type =
  5587. trim_copy(accept_entry.media_type.substr(0, param_pos));
  5588. }
  5589. // Basic validation of media type format
  5590. if (accept_entry.media_type.empty()) {
  5591. has_invalid_entry = true;
  5592. return;
  5593. }
  5594. // Check for basic media type format (should contain '/' or be '*')
  5595. if (accept_entry.media_type != "*" &&
  5596. accept_entry.media_type.find('/') == std::string::npos) {
  5597. has_invalid_entry = true;
  5598. return;
  5599. }
  5600. entries.push_back(std::move(accept_entry));
  5601. });
  5602. // Return false if any invalid entry was found
  5603. if (has_invalid_entry) { return false; }
  5604. // Sort by quality (descending), then by original order (ascending)
  5605. std::sort(entries.begin(), entries.end(),
  5606. [](const AcceptEntry &a, const AcceptEntry &b) {
  5607. if (a.quality != b.quality) {
  5608. return a.quality > b.quality; // Higher quality first
  5609. }
  5610. return a.order < b.order; // Earlier order first for same quality
  5611. });
  5612. // Extract sorted media types
  5613. content_types.reserve(entries.size());
  5614. for (auto &entry : entries) {
  5615. content_types.push_back(std::move(entry.media_type));
  5616. }
  5617. return true;
  5618. }
  5619. class FormDataParser {
  5620. public:
  5621. FormDataParser() = default;
  5622. void set_boundary(std::string &&boundary) {
  5623. boundary_ = std::move(boundary);
  5624. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  5625. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  5626. }
  5627. bool is_valid() const { return is_valid_; }
  5628. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  5629. const ContentReceiver &content_callback) {
  5630. buf_append(buf, n);
  5631. while (buf_size() > 0) {
  5632. switch (state_) {
  5633. case 0: { // Initial boundary
  5634. auto pos = buf_find(dash_boundary_crlf_);
  5635. if (pos == buf_size()) { return true; }
  5636. buf_erase(pos + dash_boundary_crlf_.size());
  5637. state_ = 1;
  5638. break;
  5639. }
  5640. case 1: { // New entry
  5641. clear_file_info();
  5642. state_ = 2;
  5643. break;
  5644. }
  5645. case 2: { // Headers
  5646. auto pos = buf_find(crlf_);
  5647. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5648. while (pos < buf_size()) {
  5649. // Empty line
  5650. if (pos == 0) {
  5651. if (!header_callback(file_)) {
  5652. is_valid_ = false;
  5653. return false;
  5654. }
  5655. buf_erase(crlf_.size());
  5656. state_ = 3;
  5657. break;
  5658. }
  5659. const auto header = buf_head(pos);
  5660. if (!parse_header(header.data(), header.data() + header.size(),
  5661. [&](const std::string &, const std::string &) {})) {
  5662. is_valid_ = false;
  5663. return false;
  5664. }
  5665. // Parse and emplace space trimmed headers into a map
  5666. if (!parse_header(
  5667. header.data(), header.data() + header.size(),
  5668. [&](const std::string &key, const std::string &val) {
  5669. file_.headers.emplace(key, val);
  5670. })) {
  5671. is_valid_ = false;
  5672. return false;
  5673. }
  5674. constexpr const char header_content_type[] = "Content-Type:";
  5675. if (start_with_case_ignore(header, header_content_type)) {
  5676. file_.content_type =
  5677. trim_copy(header.substr(str_len(header_content_type)));
  5678. } else {
  5679. thread_local const std::regex re_content_disposition(
  5680. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  5681. std::regex_constants::icase);
  5682. std::smatch m;
  5683. if (std::regex_match(header, m, re_content_disposition)) {
  5684. Params params;
  5685. parse_disposition_params(m[1], params);
  5686. auto it = params.find("name");
  5687. if (it != params.end()) {
  5688. file_.name = it->second;
  5689. } else {
  5690. is_valid_ = false;
  5691. return false;
  5692. }
  5693. it = params.find("filename");
  5694. if (it != params.end()) { file_.filename = it->second; }
  5695. it = params.find("filename*");
  5696. if (it != params.end()) {
  5697. // Only allow UTF-8 encoding...
  5698. thread_local const std::regex re_rfc5987_encoding(
  5699. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  5700. std::smatch m2;
  5701. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  5702. file_.filename = decode_path_component(m2[1]); // override...
  5703. } else {
  5704. is_valid_ = false;
  5705. return false;
  5706. }
  5707. }
  5708. }
  5709. }
  5710. buf_erase(pos + crlf_.size());
  5711. pos = buf_find(crlf_);
  5712. }
  5713. if (state_ != 3) { return true; }
  5714. break;
  5715. }
  5716. case 3: { // Body
  5717. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  5718. auto pos = buf_find(crlf_dash_boundary_);
  5719. if (pos < buf_size()) {
  5720. if (!content_callback(buf_data(), pos)) {
  5721. is_valid_ = false;
  5722. return false;
  5723. }
  5724. buf_erase(pos + crlf_dash_boundary_.size());
  5725. state_ = 4;
  5726. } else {
  5727. auto len = buf_size() - crlf_dash_boundary_.size();
  5728. if (len > 0) {
  5729. if (!content_callback(buf_data(), len)) {
  5730. is_valid_ = false;
  5731. return false;
  5732. }
  5733. buf_erase(len);
  5734. }
  5735. return true;
  5736. }
  5737. break;
  5738. }
  5739. case 4: { // Boundary
  5740. if (crlf_.size() > buf_size()) { return true; }
  5741. if (buf_start_with(crlf_)) {
  5742. buf_erase(crlf_.size());
  5743. state_ = 1;
  5744. } else {
  5745. if (dash_.size() > buf_size()) { return true; }
  5746. if (buf_start_with(dash_)) {
  5747. buf_erase(dash_.size());
  5748. is_valid_ = true;
  5749. buf_erase(buf_size()); // Remove epilogue
  5750. } else {
  5751. return true;
  5752. }
  5753. }
  5754. break;
  5755. }
  5756. }
  5757. }
  5758. return true;
  5759. }
  5760. private:
  5761. void clear_file_info() {
  5762. file_.name.clear();
  5763. file_.filename.clear();
  5764. file_.content_type.clear();
  5765. file_.headers.clear();
  5766. }
  5767. bool start_with_case_ignore(const std::string &a, const char *b) const {
  5768. const auto b_len = strlen(b);
  5769. if (a.size() < b_len) { return false; }
  5770. for (size_t i = 0; i < b_len; i++) {
  5771. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  5772. return false;
  5773. }
  5774. }
  5775. return true;
  5776. }
  5777. const std::string dash_ = "--";
  5778. const std::string crlf_ = "\r\n";
  5779. std::string boundary_;
  5780. std::string dash_boundary_crlf_;
  5781. std::string crlf_dash_boundary_;
  5782. size_t state_ = 0;
  5783. bool is_valid_ = false;
  5784. FormData file_;
  5785. // Buffer
  5786. bool start_with(const std::string &a, size_t spos, size_t epos,
  5787. const std::string &b) const {
  5788. if (epos - spos < b.size()) { return false; }
  5789. for (size_t i = 0; i < b.size(); i++) {
  5790. if (a[i + spos] != b[i]) { return false; }
  5791. }
  5792. return true;
  5793. }
  5794. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  5795. const char *buf_data() const { return &buf_[buf_spos_]; }
  5796. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  5797. bool buf_start_with(const std::string &s) const {
  5798. return start_with(buf_, buf_spos_, buf_epos_, s);
  5799. }
  5800. size_t buf_find(const std::string &s) const {
  5801. auto c = s.front();
  5802. size_t off = buf_spos_;
  5803. while (off < buf_epos_) {
  5804. auto pos = off;
  5805. while (true) {
  5806. if (pos == buf_epos_) { return buf_size(); }
  5807. if (buf_[pos] == c) { break; }
  5808. pos++;
  5809. }
  5810. auto remaining_size = buf_epos_ - pos;
  5811. if (s.size() > remaining_size) { return buf_size(); }
  5812. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  5813. off = pos + 1;
  5814. }
  5815. return buf_size();
  5816. }
  5817. void buf_append(const char *data, size_t n) {
  5818. auto remaining_size = buf_size();
  5819. if (remaining_size > 0 && buf_spos_ > 0) {
  5820. for (size_t i = 0; i < remaining_size; i++) {
  5821. buf_[i] = buf_[buf_spos_ + i];
  5822. }
  5823. }
  5824. buf_spos_ = 0;
  5825. buf_epos_ = remaining_size;
  5826. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  5827. for (size_t i = 0; i < n; i++) {
  5828. buf_[buf_epos_ + i] = data[i];
  5829. }
  5830. buf_epos_ += n;
  5831. }
  5832. void buf_erase(size_t size) { buf_spos_ += size; }
  5833. std::string buf_;
  5834. size_t buf_spos_ = 0;
  5835. size_t buf_epos_ = 0;
  5836. };
  5837. inline std::string random_string(size_t length) {
  5838. constexpr const char data[] =
  5839. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  5840. thread_local auto engine([]() {
  5841. // std::random_device might actually be deterministic on some
  5842. // platforms, but due to lack of support in the c++ standard library,
  5843. // doing better requires either some ugly hacks or breaking portability.
  5844. std::random_device seed_gen;
  5845. // Request 128 bits of entropy for initialization
  5846. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  5847. return std::mt19937(seed_sequence);
  5848. }());
  5849. std::string result;
  5850. for (size_t i = 0; i < length; i++) {
  5851. result += data[engine() % (sizeof(data) - 1)];
  5852. }
  5853. return result;
  5854. }
  5855. inline std::string make_multipart_data_boundary() {
  5856. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  5857. }
  5858. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  5859. auto valid = true;
  5860. for (size_t i = 0; i < boundary.size(); i++) {
  5861. auto c = boundary[i];
  5862. if (!std::isalnum(c) && c != '-' && c != '_') {
  5863. valid = false;
  5864. break;
  5865. }
  5866. }
  5867. return valid;
  5868. }
  5869. template <typename T>
  5870. inline std::string
  5871. serialize_multipart_formdata_item_begin(const T &item,
  5872. const std::string &boundary) {
  5873. std::string body = "--" + boundary + "\r\n";
  5874. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5875. if (!item.filename.empty()) {
  5876. body += "; filename=\"" + item.filename + "\"";
  5877. }
  5878. body += "\r\n";
  5879. if (!item.content_type.empty()) {
  5880. body += "Content-Type: " + item.content_type + "\r\n";
  5881. }
  5882. body += "\r\n";
  5883. return body;
  5884. }
  5885. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  5886. inline std::string
  5887. serialize_multipart_formdata_finish(const std::string &boundary) {
  5888. return "--" + boundary + "--\r\n";
  5889. }
  5890. inline std::string
  5891. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  5892. return "multipart/form-data; boundary=" + boundary;
  5893. }
  5894. inline std::string
  5895. serialize_multipart_formdata(const UploadFormDataItems &items,
  5896. const std::string &boundary, bool finish = true) {
  5897. std::string body;
  5898. for (const auto &item : items) {
  5899. body += serialize_multipart_formdata_item_begin(item, boundary);
  5900. body += item.content + serialize_multipart_formdata_item_end();
  5901. }
  5902. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  5903. return body;
  5904. }
  5905. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  5906. if (ranges.size() <= 1) return;
  5907. // Sort ranges by start position
  5908. std::sort(ranges.begin(), ranges.end(),
  5909. [](const Range &a, const Range &b) { return a.first < b.first; });
  5910. Ranges coalesced;
  5911. coalesced.reserve(ranges.size());
  5912. for (auto &r : ranges) {
  5913. auto first_pos = r.first;
  5914. auto last_pos = r.second;
  5915. // Handle special cases like in range_error
  5916. if (first_pos == -1 && last_pos == -1) {
  5917. first_pos = 0;
  5918. last_pos = static_cast<ssize_t>(content_length);
  5919. }
  5920. if (first_pos == -1) {
  5921. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  5922. last_pos = static_cast<ssize_t>(content_length) - 1;
  5923. }
  5924. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  5925. last_pos = static_cast<ssize_t>(content_length) - 1;
  5926. }
  5927. // Skip invalid ranges
  5928. if (!(0 <= first_pos && first_pos <= last_pos &&
  5929. last_pos < static_cast<ssize_t>(content_length))) {
  5930. continue;
  5931. }
  5932. // Coalesce with previous range if overlapping or adjacent (but not
  5933. // identical)
  5934. if (!coalesced.empty()) {
  5935. auto &prev = coalesced.back();
  5936. // Check if current range overlaps or is adjacent to previous range
  5937. // but don't coalesce identical ranges (allow duplicates)
  5938. if (first_pos <= prev.second + 1 &&
  5939. !(first_pos == prev.first && last_pos == prev.second)) {
  5940. // Extend the previous range
  5941. prev.second = (std::max)(prev.second, last_pos);
  5942. continue;
  5943. }
  5944. }
  5945. // Add new range
  5946. coalesced.emplace_back(first_pos, last_pos);
  5947. }
  5948. ranges = std::move(coalesced);
  5949. }
  5950. inline bool range_error(Request &req, Response &res) {
  5951. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  5952. ssize_t content_len = static_cast<ssize_t>(
  5953. res.content_length_ ? res.content_length_ : res.body.size());
  5954. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  5955. size_t overwrapping_count = 0;
  5956. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  5957. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  5958. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  5959. // Too many ranges
  5960. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  5961. for (auto &r : req.ranges) {
  5962. auto &first_pos = r.first;
  5963. auto &last_pos = r.second;
  5964. if (first_pos == -1 && last_pos == -1) {
  5965. first_pos = 0;
  5966. last_pos = content_len;
  5967. }
  5968. if (first_pos == -1) {
  5969. first_pos = content_len - last_pos;
  5970. last_pos = content_len - 1;
  5971. }
  5972. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  5973. // A client can limit the number of bytes requested without knowing the
  5974. // size of the selected representation. If the last-pos value is absent,
  5975. // or if the value is greater than or equal to the current length of the
  5976. // representation data, the byte range is interpreted as the remainder of
  5977. // the representation (i.e., the server replaces the value of last-pos
  5978. // with a value that is one less than the current length of the selected
  5979. // representation).
  5980. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  5981. if (last_pos == -1 || last_pos >= content_len) {
  5982. last_pos = content_len - 1;
  5983. }
  5984. // Range must be within content length
  5985. if (!(0 <= first_pos && first_pos <= last_pos &&
  5986. last_pos <= content_len - 1)) {
  5987. return true;
  5988. }
  5989. // Request must not have more than two overlapping ranges
  5990. for (const auto &processed_range : processed_ranges) {
  5991. if (!(last_pos < processed_range.first ||
  5992. first_pos > processed_range.second)) {
  5993. overwrapping_count++;
  5994. if (overwrapping_count > 2) { return true; }
  5995. break; // Only count once per range
  5996. }
  5997. }
  5998. processed_ranges.emplace_back(first_pos, last_pos);
  5999. }
  6000. // After validation, coalesce overlapping ranges as per RFC 9110
  6001. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  6002. }
  6003. return false;
  6004. }
  6005. inline std::pair<size_t, size_t>
  6006. get_range_offset_and_length(Range r, size_t content_length) {
  6007. assert(r.first != -1 && r.second != -1);
  6008. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  6009. assert(r.first <= r.second &&
  6010. r.second < static_cast<ssize_t>(content_length));
  6011. (void)(content_length);
  6012. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  6013. }
  6014. inline std::string make_content_range_header_field(
  6015. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  6016. auto st = offset_and_length.first;
  6017. auto ed = st + offset_and_length.second - 1;
  6018. std::string field = "bytes ";
  6019. field += std::to_string(st);
  6020. field += '-';
  6021. field += std::to_string(ed);
  6022. field += '/';
  6023. field += std::to_string(content_length);
  6024. return field;
  6025. }
  6026. template <typename SToken, typename CToken, typename Content>
  6027. bool process_multipart_ranges_data(const Request &req,
  6028. const std::string &boundary,
  6029. const std::string &content_type,
  6030. size_t content_length, SToken stoken,
  6031. CToken ctoken, Content content) {
  6032. for (size_t i = 0; i < req.ranges.size(); i++) {
  6033. ctoken("--");
  6034. stoken(boundary);
  6035. ctoken("\r\n");
  6036. if (!content_type.empty()) {
  6037. ctoken("Content-Type: ");
  6038. stoken(content_type);
  6039. ctoken("\r\n");
  6040. }
  6041. auto offset_and_length =
  6042. get_range_offset_and_length(req.ranges[i], content_length);
  6043. ctoken("Content-Range: ");
  6044. stoken(make_content_range_header_field(offset_and_length, content_length));
  6045. ctoken("\r\n");
  6046. ctoken("\r\n");
  6047. if (!content(offset_and_length.first, offset_and_length.second)) {
  6048. return false;
  6049. }
  6050. ctoken("\r\n");
  6051. }
  6052. ctoken("--");
  6053. stoken(boundary);
  6054. ctoken("--");
  6055. return true;
  6056. }
  6057. inline void make_multipart_ranges_data(const Request &req, Response &res,
  6058. const std::string &boundary,
  6059. const std::string &content_type,
  6060. size_t content_length,
  6061. std::string &data) {
  6062. process_multipart_ranges_data(
  6063. req, boundary, content_type, content_length,
  6064. [&](const std::string &token) { data += token; },
  6065. [&](const std::string &token) { data += token; },
  6066. [&](size_t offset, size_t length) {
  6067. assert(offset + length <= content_length);
  6068. data += res.body.substr(offset, length);
  6069. return true;
  6070. });
  6071. }
  6072. inline size_t get_multipart_ranges_data_length(const Request &req,
  6073. const std::string &boundary,
  6074. const std::string &content_type,
  6075. size_t content_length) {
  6076. size_t data_length = 0;
  6077. process_multipart_ranges_data(
  6078. req, boundary, content_type, content_length,
  6079. [&](const std::string &token) { data_length += token.size(); },
  6080. [&](const std::string &token) { data_length += token.size(); },
  6081. [&](size_t /*offset*/, size_t length) {
  6082. data_length += length;
  6083. return true;
  6084. });
  6085. return data_length;
  6086. }
  6087. template <typename T>
  6088. inline bool
  6089. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  6090. const std::string &boundary,
  6091. const std::string &content_type,
  6092. size_t content_length, const T &is_shutting_down) {
  6093. return process_multipart_ranges_data(
  6094. req, boundary, content_type, content_length,
  6095. [&](const std::string &token) { strm.write(token); },
  6096. [&](const std::string &token) { strm.write(token); },
  6097. [&](size_t offset, size_t length) {
  6098. return write_content(strm, res.content_provider_, offset, length,
  6099. is_shutting_down);
  6100. });
  6101. }
  6102. inline bool expect_content(const Request &req) {
  6103. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  6104. req.method == "DELETE") {
  6105. return true;
  6106. }
  6107. if (req.has_header("Content-Length") &&
  6108. req.get_header_value_u64("Content-Length") > 0) {
  6109. return true;
  6110. }
  6111. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  6112. return false;
  6113. }
  6114. inline bool has_crlf(const std::string &s) {
  6115. auto p = s.c_str();
  6116. while (*p) {
  6117. if (*p == '\r' || *p == '\n') { return true; }
  6118. p++;
  6119. }
  6120. return false;
  6121. }
  6122. #ifdef _WIN32
  6123. class WSInit {
  6124. public:
  6125. WSInit() {
  6126. WSADATA wsaData;
  6127. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  6128. }
  6129. ~WSInit() {
  6130. if (is_valid_) WSACleanup();
  6131. }
  6132. bool is_valid_ = false;
  6133. };
  6134. static WSInit wsinit_;
  6135. #endif
  6136. inline bool parse_www_authenticate(const Response &res,
  6137. std::map<std::string, std::string> &auth,
  6138. bool is_proxy) {
  6139. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  6140. if (res.has_header(auth_key)) {
  6141. thread_local auto re =
  6142. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  6143. auto s = res.get_header_value(auth_key);
  6144. auto pos = s.find(' ');
  6145. if (pos != std::string::npos) {
  6146. auto type = s.substr(0, pos);
  6147. if (type == "Basic") {
  6148. return false;
  6149. } else if (type == "Digest") {
  6150. s = s.substr(pos + 1);
  6151. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  6152. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  6153. const auto &m = *i;
  6154. auto key = s.substr(static_cast<size_t>(m.position(1)),
  6155. static_cast<size_t>(m.length(1)));
  6156. auto val = m.length(2) > 0
  6157. ? s.substr(static_cast<size_t>(m.position(2)),
  6158. static_cast<size_t>(m.length(2)))
  6159. : s.substr(static_cast<size_t>(m.position(3)),
  6160. static_cast<size_t>(m.length(3)));
  6161. auth[std::move(key)] = std::move(val);
  6162. }
  6163. return true;
  6164. }
  6165. }
  6166. }
  6167. return false;
  6168. }
  6169. class ContentProviderAdapter {
  6170. public:
  6171. explicit ContentProviderAdapter(
  6172. ContentProviderWithoutLength &&content_provider)
  6173. : content_provider_(std::move(content_provider)) {}
  6174. bool operator()(size_t offset, size_t, DataSink &sink) {
  6175. return content_provider_(offset, sink);
  6176. }
  6177. private:
  6178. ContentProviderWithoutLength content_provider_;
  6179. };
  6180. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  6181. namespace fields {
  6182. inline bool is_token_char(char c) {
  6183. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  6184. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  6185. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  6186. }
  6187. inline bool is_token(const std::string &s) {
  6188. if (s.empty()) { return false; }
  6189. for (auto c : s) {
  6190. if (!is_token_char(c)) { return false; }
  6191. }
  6192. return true;
  6193. }
  6194. inline bool is_field_name(const std::string &s) { return is_token(s); }
  6195. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  6196. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  6197. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  6198. inline bool is_field_content(const std::string &s) {
  6199. if (s.empty()) { return true; }
  6200. if (s.size() == 1) {
  6201. return is_field_vchar(s[0]);
  6202. } else if (s.size() == 2) {
  6203. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  6204. } else {
  6205. size_t i = 0;
  6206. if (!is_field_vchar(s[i])) { return false; }
  6207. i++;
  6208. while (i < s.size() - 1) {
  6209. auto c = s[i++];
  6210. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  6211. } else {
  6212. return false;
  6213. }
  6214. }
  6215. return is_field_vchar(s[i]);
  6216. }
  6217. }
  6218. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  6219. } // namespace fields
  6220. } // namespace detail
  6221. /*
  6222. * Group 2: detail namespace - SSL common utilities
  6223. */
  6224. #ifdef CPPHTTPLIB_SSL_ENABLED
  6225. namespace detail {
  6226. class SSLSocketStream final : public Stream {
  6227. public:
  6228. SSLSocketStream(
  6229. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  6230. time_t read_timeout_usec, time_t write_timeout_sec,
  6231. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  6232. std::chrono::time_point<std::chrono::steady_clock> start_time =
  6233. (std::chrono::steady_clock::time_point::min)());
  6234. ~SSLSocketStream() override;
  6235. bool is_readable() const override;
  6236. bool wait_readable() const override;
  6237. bool wait_writable() const override;
  6238. ssize_t read(char *ptr, size_t size) override;
  6239. ssize_t write(const char *ptr, size_t size) override;
  6240. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  6241. void get_local_ip_and_port(std::string &ip, int &port) const override;
  6242. socket_t socket() const override;
  6243. time_t duration() const override;
  6244. private:
  6245. socket_t sock_;
  6246. tls::session_t session_;
  6247. time_t read_timeout_sec_;
  6248. time_t read_timeout_usec_;
  6249. time_t write_timeout_sec_;
  6250. time_t write_timeout_usec_;
  6251. time_t max_timeout_msec_;
  6252. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  6253. };
  6254. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6255. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  6256. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  6257. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  6258. unsigned int hash_length = 0;
  6259. unsigned char hash[EVP_MAX_MD_SIZE];
  6260. EVP_DigestInit_ex(context.get(), algo, nullptr);
  6261. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  6262. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  6263. std::stringstream ss;
  6264. for (auto i = 0u; i < hash_length; ++i) {
  6265. ss << std::hex << std::setw(2) << std::setfill('0')
  6266. << static_cast<unsigned int>(hash[i]);
  6267. }
  6268. return ss.str();
  6269. }
  6270. inline std::string MD5(const std::string &s) {
  6271. return message_digest(s, EVP_md5());
  6272. }
  6273. inline std::string SHA_256(const std::string &s) {
  6274. return message_digest(s, EVP_sha256());
  6275. }
  6276. inline std::string SHA_512(const std::string &s) {
  6277. return message_digest(s, EVP_sha512());
  6278. }
  6279. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  6280. namespace {
  6281. template <size_t N>
  6282. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  6283. std::stringstream ss;
  6284. for (size_t i = 0; i < N; ++i) {
  6285. ss << std::hex << std::setw(2) << std::setfill('0')
  6286. << static_cast<unsigned int>(hash[i]);
  6287. }
  6288. return ss.str();
  6289. }
  6290. } // namespace
  6291. inline std::string MD5(const std::string &s) {
  6292. unsigned char hash[16];
  6293. #ifdef CPPHTTPLIB_MBEDTLS_V3
  6294. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6295. hash);
  6296. #else
  6297. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6298. hash);
  6299. #endif
  6300. return hash_to_hex(hash);
  6301. }
  6302. inline std::string SHA_256(const std::string &s) {
  6303. unsigned char hash[32];
  6304. #ifdef CPPHTTPLIB_MBEDTLS_V3
  6305. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6306. hash, 0);
  6307. #else
  6308. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6309. s.size(), hash, 0);
  6310. #endif
  6311. return hash_to_hex(hash);
  6312. }
  6313. inline std::string SHA_512(const std::string &s) {
  6314. unsigned char hash[64];
  6315. #ifdef CPPHTTPLIB_MBEDTLS_V3
  6316. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6317. hash, 0);
  6318. #else
  6319. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6320. s.size(), hash, 0);
  6321. #endif
  6322. return hash_to_hex(hash);
  6323. }
  6324. #endif
  6325. inline bool is_ip_address(const std::string &host) {
  6326. struct in_addr addr4;
  6327. struct in6_addr addr6;
  6328. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  6329. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  6330. }
  6331. template <typename T>
  6332. inline bool process_server_socket_ssl(
  6333. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  6334. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  6335. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  6336. time_t write_timeout_usec, T callback) {
  6337. return process_server_socket_core(
  6338. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  6339. [&](bool close_connection, bool &connection_closed) {
  6340. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  6341. write_timeout_sec, write_timeout_usec);
  6342. return callback(strm, close_connection, connection_closed);
  6343. });
  6344. }
  6345. template <typename T>
  6346. inline bool process_client_socket_ssl(
  6347. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  6348. time_t read_timeout_usec, time_t write_timeout_sec,
  6349. time_t write_timeout_usec, time_t max_timeout_msec,
  6350. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  6351. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  6352. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  6353. start_time);
  6354. return callback(strm);
  6355. }
  6356. inline std::pair<std::string, std::string> make_digest_authentication_header(
  6357. const Request &req, const std::map<std::string, std::string> &auth,
  6358. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  6359. const std::string &password, bool is_proxy = false) {
  6360. std::string nc;
  6361. {
  6362. std::stringstream ss;
  6363. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  6364. nc = ss.str();
  6365. }
  6366. std::string qop;
  6367. if (auth.find("qop") != auth.end()) {
  6368. qop = auth.at("qop");
  6369. if (qop.find("auth-int") != std::string::npos) {
  6370. qop = "auth-int";
  6371. } else if (qop.find("auth") != std::string::npos) {
  6372. qop = "auth";
  6373. } else {
  6374. qop.clear();
  6375. }
  6376. }
  6377. std::string algo = "MD5";
  6378. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  6379. std::string response;
  6380. {
  6381. auto H = algo == "SHA-256" ? detail::SHA_256
  6382. : algo == "SHA-512" ? detail::SHA_512
  6383. : detail::MD5;
  6384. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  6385. auto A2 = req.method + ":" + req.path;
  6386. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  6387. if (qop.empty()) {
  6388. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  6389. } else {
  6390. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  6391. ":" + qop + ":" + H(A2));
  6392. }
  6393. }
  6394. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  6395. auto field = "Digest username=\"" + username + "\", realm=\"" +
  6396. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  6397. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  6398. (qop.empty() ? ", response=\""
  6399. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  6400. cnonce + "\", response=\"") +
  6401. response + "\"" +
  6402. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  6403. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6404. return std::make_pair(key, field);
  6405. }
  6406. inline bool match_hostname(const std::string &pattern,
  6407. const std::string &hostname) {
  6408. // Exact match (case-insensitive)
  6409. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  6410. // Split both pattern and hostname into components by '.'
  6411. std::vector<std::string> pattern_components;
  6412. if (!pattern.empty()) {
  6413. split(pattern.data(), pattern.data() + pattern.size(), '.',
  6414. [&](const char *b, const char *e) {
  6415. pattern_components.emplace_back(b, e);
  6416. });
  6417. }
  6418. std::vector<std::string> host_components;
  6419. if (!hostname.empty()) {
  6420. split(hostname.data(), hostname.data() + hostname.size(), '.',
  6421. [&](const char *b, const char *e) {
  6422. host_components.emplace_back(b, e);
  6423. });
  6424. }
  6425. // Component count must match
  6426. if (host_components.size() != pattern_components.size()) { return false; }
  6427. // Compare each component with wildcard support
  6428. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  6429. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  6430. auto itr = pattern_components.begin();
  6431. for (const auto &h : host_components) {
  6432. auto &p = *itr;
  6433. if (!detail::case_ignore::equal(p, h) && p != "*") {
  6434. bool partial_match = false;
  6435. if (!p.empty() && p[p.size() - 1] == '*') {
  6436. const auto prefix_length = p.size() - 1;
  6437. if (prefix_length == 0) {
  6438. partial_match = true;
  6439. } else if (h.size() >= prefix_length) {
  6440. partial_match =
  6441. std::equal(p.begin(),
  6442. p.begin() + static_cast<std::string::difference_type>(
  6443. prefix_length),
  6444. h.begin(), [](const char ca, const char cb) {
  6445. return detail::case_ignore::to_lower(ca) ==
  6446. detail::case_ignore::to_lower(cb);
  6447. });
  6448. }
  6449. }
  6450. if (!partial_match) { return false; }
  6451. }
  6452. ++itr;
  6453. }
  6454. return true;
  6455. }
  6456. #ifdef _WIN32
  6457. // Verify certificate using Windows CertGetCertificateChain API.
  6458. // This provides real-time certificate validation with Windows Update
  6459. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  6460. inline bool verify_cert_with_windows_schannel(
  6461. const std::vector<unsigned char> &der_cert, const std::string &hostname,
  6462. bool verify_hostname, unsigned long &out_error) {
  6463. if (der_cert.empty()) { return false; }
  6464. out_error = 0;
  6465. // Create Windows certificate context from DER data
  6466. auto cert_context = CertCreateCertificateContext(
  6467. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  6468. static_cast<DWORD>(der_cert.size()));
  6469. if (!cert_context) {
  6470. out_error = GetLastError();
  6471. return false;
  6472. }
  6473. auto cert_guard =
  6474. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  6475. // Setup chain parameters
  6476. CERT_CHAIN_PARA chain_para = {};
  6477. chain_para.cbSize = sizeof(chain_para);
  6478. // Build certificate chain with revocation checking
  6479. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  6480. auto chain_result = CertGetCertificateChain(
  6481. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  6482. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  6483. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  6484. nullptr, &chain_context);
  6485. if (!chain_result || !chain_context) {
  6486. out_error = GetLastError();
  6487. return false;
  6488. }
  6489. auto chain_guard =
  6490. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  6491. // Check if chain has errors
  6492. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  6493. out_error = chain_context->TrustStatus.dwErrorStatus;
  6494. return false;
  6495. }
  6496. // Verify SSL policy
  6497. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  6498. extra_policy_para.cbSize = sizeof(extra_policy_para);
  6499. #ifdef AUTHTYPE_SERVER
  6500. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  6501. #endif
  6502. std::wstring whost;
  6503. if (verify_hostname) {
  6504. whost = u8string_to_wstring(hostname.c_str());
  6505. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  6506. }
  6507. CERT_CHAIN_POLICY_PARA policy_para = {};
  6508. policy_para.cbSize = sizeof(policy_para);
  6509. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  6510. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  6511. #else
  6512. policy_para.dwFlags = 0;
  6513. #endif
  6514. policy_para.pvExtraPolicyPara = &extra_policy_para;
  6515. CERT_CHAIN_POLICY_STATUS policy_status = {};
  6516. policy_status.cbSize = sizeof(policy_status);
  6517. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  6518. &policy_para, &policy_status)) {
  6519. out_error = GetLastError();
  6520. return false;
  6521. }
  6522. if (policy_status.dwError != 0) {
  6523. out_error = policy_status.dwError;
  6524. return false;
  6525. }
  6526. return true;
  6527. }
  6528. #endif // _WIN32
  6529. } // namespace detail
  6530. #endif // CPPHTTPLIB_SSL_ENABLED
  6531. /*
  6532. * Group 3: httplib namespace - Non-SSL public API implementations
  6533. */
  6534. inline void default_socket_options(socket_t sock) {
  6535. detail::set_socket_opt(sock, SOL_SOCKET,
  6536. #ifdef SO_REUSEPORT
  6537. SO_REUSEPORT,
  6538. #else
  6539. SO_REUSEADDR,
  6540. #endif
  6541. 1);
  6542. }
  6543. inline std::string get_bearer_token_auth(const Request &req) {
  6544. if (req.has_header("Authorization")) {
  6545. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  6546. return req.get_header_value("Authorization")
  6547. .substr(bearer_header_prefix_len);
  6548. }
  6549. return "";
  6550. }
  6551. inline const char *status_message(int status) {
  6552. switch (status) {
  6553. case StatusCode::Continue_100: return "Continue";
  6554. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  6555. case StatusCode::Processing_102: return "Processing";
  6556. case StatusCode::EarlyHints_103: return "Early Hints";
  6557. case StatusCode::OK_200: return "OK";
  6558. case StatusCode::Created_201: return "Created";
  6559. case StatusCode::Accepted_202: return "Accepted";
  6560. case StatusCode::NonAuthoritativeInformation_203:
  6561. return "Non-Authoritative Information";
  6562. case StatusCode::NoContent_204: return "No Content";
  6563. case StatusCode::ResetContent_205: return "Reset Content";
  6564. case StatusCode::PartialContent_206: return "Partial Content";
  6565. case StatusCode::MultiStatus_207: return "Multi-Status";
  6566. case StatusCode::AlreadyReported_208: return "Already Reported";
  6567. case StatusCode::IMUsed_226: return "IM Used";
  6568. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  6569. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  6570. case StatusCode::Found_302: return "Found";
  6571. case StatusCode::SeeOther_303: return "See Other";
  6572. case StatusCode::NotModified_304: return "Not Modified";
  6573. case StatusCode::UseProxy_305: return "Use Proxy";
  6574. case StatusCode::unused_306: return "unused";
  6575. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  6576. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  6577. case StatusCode::BadRequest_400: return "Bad Request";
  6578. case StatusCode::Unauthorized_401: return "Unauthorized";
  6579. case StatusCode::PaymentRequired_402: return "Payment Required";
  6580. case StatusCode::Forbidden_403: return "Forbidden";
  6581. case StatusCode::NotFound_404: return "Not Found";
  6582. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  6583. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  6584. case StatusCode::ProxyAuthenticationRequired_407:
  6585. return "Proxy Authentication Required";
  6586. case StatusCode::RequestTimeout_408: return "Request Timeout";
  6587. case StatusCode::Conflict_409: return "Conflict";
  6588. case StatusCode::Gone_410: return "Gone";
  6589. case StatusCode::LengthRequired_411: return "Length Required";
  6590. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  6591. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  6592. case StatusCode::UriTooLong_414: return "URI Too Long";
  6593. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  6594. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  6595. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  6596. case StatusCode::ImATeapot_418: return "I'm a teapot";
  6597. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  6598. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  6599. case StatusCode::Locked_423: return "Locked";
  6600. case StatusCode::FailedDependency_424: return "Failed Dependency";
  6601. case StatusCode::TooEarly_425: return "Too Early";
  6602. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  6603. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  6604. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  6605. case StatusCode::RequestHeaderFieldsTooLarge_431:
  6606. return "Request Header Fields Too Large";
  6607. case StatusCode::UnavailableForLegalReasons_451:
  6608. return "Unavailable For Legal Reasons";
  6609. case StatusCode::NotImplemented_501: return "Not Implemented";
  6610. case StatusCode::BadGateway_502: return "Bad Gateway";
  6611. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  6612. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  6613. case StatusCode::HttpVersionNotSupported_505:
  6614. return "HTTP Version Not Supported";
  6615. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  6616. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  6617. case StatusCode::LoopDetected_508: return "Loop Detected";
  6618. case StatusCode::NotExtended_510: return "Not Extended";
  6619. case StatusCode::NetworkAuthenticationRequired_511:
  6620. return "Network Authentication Required";
  6621. default:
  6622. case StatusCode::InternalServerError_500: return "Internal Server Error";
  6623. }
  6624. }
  6625. inline std::string to_string(const Error error) {
  6626. switch (error) {
  6627. case Error::Success: return "Success (no error)";
  6628. case Error::Unknown: return "Unknown";
  6629. case Error::Connection: return "Could not establish connection";
  6630. case Error::BindIPAddress: return "Failed to bind IP address";
  6631. case Error::Read: return "Failed to read connection";
  6632. case Error::Write: return "Failed to write connection";
  6633. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  6634. case Error::Canceled: return "Connection handling canceled";
  6635. case Error::SSLConnection: return "SSL connection failed";
  6636. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  6637. case Error::SSLServerVerification: return "SSL server verification failed";
  6638. case Error::SSLServerHostnameVerification:
  6639. return "SSL server hostname verification failed";
  6640. case Error::UnsupportedMultipartBoundaryChars:
  6641. return "Unsupported HTTP multipart boundary characters";
  6642. case Error::Compression: return "Compression failed";
  6643. case Error::ConnectionTimeout: return "Connection timed out";
  6644. case Error::ProxyConnection: return "Proxy connection failed";
  6645. case Error::ConnectionClosed: return "Connection closed by server";
  6646. case Error::Timeout: return "Read timeout";
  6647. case Error::ResourceExhaustion: return "Resource exhaustion";
  6648. case Error::TooManyFormDataFiles: return "Too many form data files";
  6649. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  6650. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  6651. case Error::ExceedMaxSocketDescriptorCount:
  6652. return "Exceeded maximum socket descriptor count";
  6653. case Error::InvalidRequestLine: return "Invalid request line";
  6654. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  6655. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  6656. case Error::InvalidHeaders: return "Invalid headers";
  6657. case Error::MultipartParsing: return "Multipart parsing failed";
  6658. case Error::OpenFile: return "Failed to open file";
  6659. case Error::Listen: return "Failed to listen on socket";
  6660. case Error::GetSockName: return "Failed to get socket name";
  6661. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  6662. case Error::HTTPParsing: return "HTTP parsing failed";
  6663. case Error::InvalidRangeHeader: return "Invalid Range header";
  6664. default: break;
  6665. }
  6666. return "Invalid";
  6667. }
  6668. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  6669. os << to_string(obj);
  6670. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  6671. return os;
  6672. }
  6673. inline std::string hosted_at(const std::string &hostname) {
  6674. std::vector<std::string> addrs;
  6675. hosted_at(hostname, addrs);
  6676. if (addrs.empty()) { return std::string(); }
  6677. return addrs[0];
  6678. }
  6679. inline void hosted_at(const std::string &hostname,
  6680. std::vector<std::string> &addrs) {
  6681. struct addrinfo hints;
  6682. struct addrinfo *result;
  6683. memset(&hints, 0, sizeof(struct addrinfo));
  6684. hints.ai_family = AF_UNSPEC;
  6685. hints.ai_socktype = SOCK_STREAM;
  6686. hints.ai_protocol = 0;
  6687. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  6688. &result, 0)) {
  6689. #if defined __linux__ && !defined __ANDROID__
  6690. res_init();
  6691. #endif
  6692. return;
  6693. }
  6694. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6695. for (auto rp = result; rp; rp = rp->ai_next) {
  6696. const auto &addr =
  6697. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  6698. std::string ip;
  6699. auto dummy = -1;
  6700. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  6701. dummy)) {
  6702. addrs.emplace_back(std::move(ip));
  6703. }
  6704. }
  6705. }
  6706. inline std::string encode_uri_component(const std::string &value) {
  6707. std::ostringstream escaped;
  6708. escaped.fill('0');
  6709. escaped << std::hex;
  6710. for (auto c : value) {
  6711. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6712. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6713. c == ')') {
  6714. escaped << c;
  6715. } else {
  6716. escaped << std::uppercase;
  6717. escaped << '%' << std::setw(2)
  6718. << static_cast<int>(static_cast<unsigned char>(c));
  6719. escaped << std::nouppercase;
  6720. }
  6721. }
  6722. return escaped.str();
  6723. }
  6724. inline std::string encode_uri(const std::string &value) {
  6725. std::ostringstream escaped;
  6726. escaped.fill('0');
  6727. escaped << std::hex;
  6728. for (auto c : value) {
  6729. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6730. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6731. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  6732. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  6733. escaped << c;
  6734. } else {
  6735. escaped << std::uppercase;
  6736. escaped << '%' << std::setw(2)
  6737. << static_cast<int>(static_cast<unsigned char>(c));
  6738. escaped << std::nouppercase;
  6739. }
  6740. }
  6741. return escaped.str();
  6742. }
  6743. inline std::string decode_uri_component(const std::string &value) {
  6744. std::string result;
  6745. for (size_t i = 0; i < value.size(); i++) {
  6746. if (value[i] == '%' && i + 2 < value.size()) {
  6747. auto val = 0;
  6748. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6749. result += static_cast<char>(val);
  6750. i += 2;
  6751. } else {
  6752. result += value[i];
  6753. }
  6754. } else {
  6755. result += value[i];
  6756. }
  6757. }
  6758. return result;
  6759. }
  6760. inline std::string decode_uri(const std::string &value) {
  6761. std::string result;
  6762. for (size_t i = 0; i < value.size(); i++) {
  6763. if (value[i] == '%' && i + 2 < value.size()) {
  6764. auto val = 0;
  6765. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6766. result += static_cast<char>(val);
  6767. i += 2;
  6768. } else {
  6769. result += value[i];
  6770. }
  6771. } else {
  6772. result += value[i];
  6773. }
  6774. }
  6775. return result;
  6776. }
  6777. inline std::string encode_path_component(const std::string &component) {
  6778. std::string result;
  6779. result.reserve(component.size() * 3);
  6780. for (size_t i = 0; i < component.size(); i++) {
  6781. auto c = static_cast<unsigned char>(component[i]);
  6782. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  6783. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6784. result += static_cast<char>(c);
  6785. }
  6786. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  6787. // "," / ";" / "="
  6788. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  6789. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  6790. c == '=') {
  6791. result += static_cast<char>(c);
  6792. }
  6793. // Colon is allowed in path segments except first segment
  6794. else if (c == ':') {
  6795. result += static_cast<char>(c);
  6796. }
  6797. // @ is allowed in path
  6798. else if (c == '@') {
  6799. result += static_cast<char>(c);
  6800. } else {
  6801. result += '%';
  6802. char hex[3];
  6803. snprintf(hex, sizeof(hex), "%02X", c);
  6804. result.append(hex, 2);
  6805. }
  6806. }
  6807. return result;
  6808. }
  6809. inline std::string decode_path_component(const std::string &component) {
  6810. std::string result;
  6811. result.reserve(component.size());
  6812. for (size_t i = 0; i < component.size(); i++) {
  6813. if (component[i] == '%' && i + 1 < component.size()) {
  6814. if (component[i + 1] == 'u') {
  6815. // Unicode %uXXXX encoding
  6816. auto val = 0;
  6817. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  6818. // 4 digits Unicode codes
  6819. char buff[4];
  6820. size_t len = detail::to_utf8(val, buff);
  6821. if (len > 0) { result.append(buff, len); }
  6822. i += 5; // 'u0000'
  6823. } else {
  6824. result += component[i];
  6825. }
  6826. } else {
  6827. // Standard %XX encoding
  6828. auto val = 0;
  6829. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  6830. // 2 digits hex codes
  6831. result += static_cast<char>(val);
  6832. i += 2; // 'XX'
  6833. } else {
  6834. result += component[i];
  6835. }
  6836. }
  6837. } else {
  6838. result += component[i];
  6839. }
  6840. }
  6841. return result;
  6842. }
  6843. inline std::string encode_query_component(const std::string &component,
  6844. bool space_as_plus) {
  6845. std::string result;
  6846. result.reserve(component.size() * 3);
  6847. for (size_t i = 0; i < component.size(); i++) {
  6848. auto c = static_cast<unsigned char>(component[i]);
  6849. // Unreserved characters per RFC 3986
  6850. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6851. result += static_cast<char>(c);
  6852. }
  6853. // Space handling
  6854. else if (c == ' ') {
  6855. if (space_as_plus) {
  6856. result += '+';
  6857. } else {
  6858. result += "%20";
  6859. }
  6860. }
  6861. // Plus sign handling
  6862. else if (c == '+') {
  6863. if (space_as_plus) {
  6864. result += "%2B";
  6865. } else {
  6866. result += static_cast<char>(c);
  6867. }
  6868. }
  6869. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  6870. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  6871. c == '*' || c == ',' || c == ';') {
  6872. result += static_cast<char>(c);
  6873. }
  6874. // Colon and @ are allowed in query
  6875. else if (c == ':' || c == '@') {
  6876. result += static_cast<char>(c);
  6877. }
  6878. // Forward slash is allowed in query values
  6879. else if (c == '/') {
  6880. result += static_cast<char>(c);
  6881. }
  6882. // Question mark is allowed in query values (after first ?)
  6883. else if (c == '?') {
  6884. result += static_cast<char>(c);
  6885. } else {
  6886. result += '%';
  6887. char hex[3];
  6888. snprintf(hex, sizeof(hex), "%02X", c);
  6889. result.append(hex, 2);
  6890. }
  6891. }
  6892. return result;
  6893. }
  6894. inline std::string decode_query_component(const std::string &component,
  6895. bool plus_as_space) {
  6896. std::string result;
  6897. result.reserve(component.size());
  6898. for (size_t i = 0; i < component.size(); i++) {
  6899. if (component[i] == '%' && i + 2 < component.size()) {
  6900. std::string hex = component.substr(i + 1, 2);
  6901. char *end;
  6902. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  6903. if (end == hex.c_str() + 2) {
  6904. result += static_cast<char>(value);
  6905. i += 2;
  6906. } else {
  6907. result += component[i];
  6908. }
  6909. } else if (component[i] == '+' && plus_as_space) {
  6910. result += ' '; // + becomes space in form-urlencoded
  6911. } else {
  6912. result += component[i];
  6913. }
  6914. }
  6915. return result;
  6916. }
  6917. inline std::string append_query_params(const std::string &path,
  6918. const Params &params) {
  6919. std::string path_with_query = path;
  6920. thread_local const std::regex re("[^?]+\\?.*");
  6921. auto delm = std::regex_match(path, re) ? '&' : '?';
  6922. path_with_query += delm + detail::params_to_query_str(params);
  6923. return path_with_query;
  6924. }
  6925. // Header utilities
  6926. inline std::pair<std::string, std::string>
  6927. make_range_header(const Ranges &ranges) {
  6928. std::string field = "bytes=";
  6929. auto i = 0;
  6930. for (const auto &r : ranges) {
  6931. if (i != 0) { field += ", "; }
  6932. if (r.first != -1) { field += std::to_string(r.first); }
  6933. field += '-';
  6934. if (r.second != -1) { field += std::to_string(r.second); }
  6935. i++;
  6936. }
  6937. return std::make_pair("Range", std::move(field));
  6938. }
  6939. inline std::pair<std::string, std::string>
  6940. make_basic_authentication_header(const std::string &username,
  6941. const std::string &password, bool is_proxy) {
  6942. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  6943. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6944. return std::make_pair(key, std::move(field));
  6945. }
  6946. inline std::pair<std::string, std::string>
  6947. make_bearer_token_authentication_header(const std::string &token,
  6948. bool is_proxy = false) {
  6949. auto field = "Bearer " + token;
  6950. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6951. return std::make_pair(key, std::move(field));
  6952. }
  6953. // Request implementation
  6954. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  6955. size_t id) const {
  6956. return detail::get_header_value_u64(headers, key, def, id);
  6957. }
  6958. inline bool Request::has_header(const std::string &key) const {
  6959. return detail::has_header(headers, key);
  6960. }
  6961. inline std::string Request::get_header_value(const std::string &key,
  6962. const char *def, size_t id) const {
  6963. return detail::get_header_value(headers, key, def, id);
  6964. }
  6965. inline size_t Request::get_header_value_count(const std::string &key) const {
  6966. auto r = headers.equal_range(key);
  6967. return static_cast<size_t>(std::distance(r.first, r.second));
  6968. }
  6969. inline void Request::set_header(const std::string &key,
  6970. const std::string &val) {
  6971. if (detail::fields::is_field_name(key) &&
  6972. detail::fields::is_field_value(val)) {
  6973. headers.emplace(key, val);
  6974. }
  6975. }
  6976. inline bool Request::has_trailer(const std::string &key) const {
  6977. return trailers.find(key) != trailers.end();
  6978. }
  6979. inline std::string Request::get_trailer_value(const std::string &key,
  6980. size_t id) const {
  6981. auto rng = trailers.equal_range(key);
  6982. auto it = rng.first;
  6983. std::advance(it, static_cast<ssize_t>(id));
  6984. if (it != rng.second) { return it->second; }
  6985. return std::string();
  6986. }
  6987. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  6988. auto r = trailers.equal_range(key);
  6989. return static_cast<size_t>(std::distance(r.first, r.second));
  6990. }
  6991. inline bool Request::has_param(const std::string &key) const {
  6992. return params.find(key) != params.end();
  6993. }
  6994. inline std::string Request::get_param_value(const std::string &key,
  6995. size_t id) const {
  6996. auto rng = params.equal_range(key);
  6997. auto it = rng.first;
  6998. std::advance(it, static_cast<ssize_t>(id));
  6999. if (it != rng.second) { return it->second; }
  7000. return std::string();
  7001. }
  7002. inline size_t Request::get_param_value_count(const std::string &key) const {
  7003. auto r = params.equal_range(key);
  7004. return static_cast<size_t>(std::distance(r.first, r.second));
  7005. }
  7006. inline bool Request::is_multipart_form_data() const {
  7007. const auto &content_type = get_header_value("Content-Type");
  7008. return !content_type.rfind("multipart/form-data", 0);
  7009. }
  7010. // Multipart FormData implementation
  7011. inline std::string MultipartFormData::get_field(const std::string &key,
  7012. size_t id) const {
  7013. auto rng = fields.equal_range(key);
  7014. auto it = rng.first;
  7015. std::advance(it, static_cast<ssize_t>(id));
  7016. if (it != rng.second) { return it->second.content; }
  7017. return std::string();
  7018. }
  7019. inline std::vector<std::string>
  7020. MultipartFormData::get_fields(const std::string &key) const {
  7021. std::vector<std::string> values;
  7022. auto rng = fields.equal_range(key);
  7023. for (auto it = rng.first; it != rng.second; it++) {
  7024. values.push_back(it->second.content);
  7025. }
  7026. return values;
  7027. }
  7028. inline bool MultipartFormData::has_field(const std::string &key) const {
  7029. return fields.find(key) != fields.end();
  7030. }
  7031. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  7032. auto r = fields.equal_range(key);
  7033. return static_cast<size_t>(std::distance(r.first, r.second));
  7034. }
  7035. inline FormData MultipartFormData::get_file(const std::string &key,
  7036. size_t id) const {
  7037. auto rng = files.equal_range(key);
  7038. auto it = rng.first;
  7039. std::advance(it, static_cast<ssize_t>(id));
  7040. if (it != rng.second) { return it->second; }
  7041. return FormData();
  7042. }
  7043. inline std::vector<FormData>
  7044. MultipartFormData::get_files(const std::string &key) const {
  7045. std::vector<FormData> values;
  7046. auto rng = files.equal_range(key);
  7047. for (auto it = rng.first; it != rng.second; it++) {
  7048. values.push_back(it->second);
  7049. }
  7050. return values;
  7051. }
  7052. inline bool MultipartFormData::has_file(const std::string &key) const {
  7053. return files.find(key) != files.end();
  7054. }
  7055. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  7056. auto r = files.equal_range(key);
  7057. return static_cast<size_t>(std::distance(r.first, r.second));
  7058. }
  7059. // Response implementation
  7060. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  7061. size_t id) const {
  7062. return detail::get_header_value_u64(headers, key, def, id);
  7063. }
  7064. inline bool Response::has_header(const std::string &key) const {
  7065. return headers.find(key) != headers.end();
  7066. }
  7067. inline std::string Response::get_header_value(const std::string &key,
  7068. const char *def,
  7069. size_t id) const {
  7070. return detail::get_header_value(headers, key, def, id);
  7071. }
  7072. inline size_t Response::get_header_value_count(const std::string &key) const {
  7073. auto r = headers.equal_range(key);
  7074. return static_cast<size_t>(std::distance(r.first, r.second));
  7075. }
  7076. inline void Response::set_header(const std::string &key,
  7077. const std::string &val) {
  7078. if (detail::fields::is_field_name(key) &&
  7079. detail::fields::is_field_value(val)) {
  7080. headers.emplace(key, val);
  7081. }
  7082. }
  7083. inline bool Response::has_trailer(const std::string &key) const {
  7084. return trailers.find(key) != trailers.end();
  7085. }
  7086. inline std::string Response::get_trailer_value(const std::string &key,
  7087. size_t id) const {
  7088. auto rng = trailers.equal_range(key);
  7089. auto it = rng.first;
  7090. std::advance(it, static_cast<ssize_t>(id));
  7091. if (it != rng.second) { return it->second; }
  7092. return std::string();
  7093. }
  7094. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  7095. auto r = trailers.equal_range(key);
  7096. return static_cast<size_t>(std::distance(r.first, r.second));
  7097. }
  7098. inline void Response::set_redirect(const std::string &url, int stat) {
  7099. if (detail::fields::is_field_value(url)) {
  7100. set_header("Location", url);
  7101. if (300 <= stat && stat < 400) {
  7102. this->status = stat;
  7103. } else {
  7104. this->status = StatusCode::Found_302;
  7105. }
  7106. }
  7107. }
  7108. inline void Response::set_content(const char *s, size_t n,
  7109. const std::string &content_type) {
  7110. body.assign(s, n);
  7111. auto rng = headers.equal_range("Content-Type");
  7112. headers.erase(rng.first, rng.second);
  7113. set_header("Content-Type", content_type);
  7114. }
  7115. inline void Response::set_content(const std::string &s,
  7116. const std::string &content_type) {
  7117. set_content(s.data(), s.size(), content_type);
  7118. }
  7119. inline void Response::set_content(std::string &&s,
  7120. const std::string &content_type) {
  7121. body = std::move(s);
  7122. auto rng = headers.equal_range("Content-Type");
  7123. headers.erase(rng.first, rng.second);
  7124. set_header("Content-Type", content_type);
  7125. }
  7126. inline void Response::set_content_provider(
  7127. size_t in_length, const std::string &content_type, ContentProvider provider,
  7128. ContentProviderResourceReleaser resource_releaser) {
  7129. set_header("Content-Type", content_type);
  7130. content_length_ = in_length;
  7131. if (in_length > 0) { content_provider_ = std::move(provider); }
  7132. content_provider_resource_releaser_ = std::move(resource_releaser);
  7133. is_chunked_content_provider_ = false;
  7134. }
  7135. inline void Response::set_content_provider(
  7136. const std::string &content_type, ContentProviderWithoutLength provider,
  7137. ContentProviderResourceReleaser resource_releaser) {
  7138. set_header("Content-Type", content_type);
  7139. content_length_ = 0;
  7140. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  7141. content_provider_resource_releaser_ = std::move(resource_releaser);
  7142. is_chunked_content_provider_ = false;
  7143. }
  7144. inline void Response::set_chunked_content_provider(
  7145. const std::string &content_type, ContentProviderWithoutLength provider,
  7146. ContentProviderResourceReleaser resource_releaser) {
  7147. set_header("Content-Type", content_type);
  7148. content_length_ = 0;
  7149. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  7150. content_provider_resource_releaser_ = std::move(resource_releaser);
  7151. is_chunked_content_provider_ = true;
  7152. }
  7153. inline void Response::set_file_content(const std::string &path,
  7154. const std::string &content_type) {
  7155. file_content_path_ = path;
  7156. file_content_content_type_ = content_type;
  7157. }
  7158. inline void Response::set_file_content(const std::string &path) {
  7159. file_content_path_ = path;
  7160. }
  7161. // Result implementation
  7162. inline size_t Result::get_request_header_value_u64(const std::string &key,
  7163. size_t def,
  7164. size_t id) const {
  7165. return detail::get_header_value_u64(request_headers_, key, def, id);
  7166. }
  7167. inline bool Result::has_request_header(const std::string &key) const {
  7168. return request_headers_.find(key) != request_headers_.end();
  7169. }
  7170. inline std::string Result::get_request_header_value(const std::string &key,
  7171. const char *def,
  7172. size_t id) const {
  7173. return detail::get_header_value(request_headers_, key, def, id);
  7174. }
  7175. inline size_t
  7176. Result::get_request_header_value_count(const std::string &key) const {
  7177. auto r = request_headers_.equal_range(key);
  7178. return static_cast<size_t>(std::distance(r.first, r.second));
  7179. }
  7180. // Stream implementation
  7181. inline ssize_t Stream::write(const char *ptr) {
  7182. return write(ptr, strlen(ptr));
  7183. }
  7184. inline ssize_t Stream::write(const std::string &s) {
  7185. return write(s.data(), s.size());
  7186. }
  7187. // BodyReader implementation
  7188. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  7189. if (!stream) {
  7190. last_error = Error::Connection;
  7191. return -1;
  7192. }
  7193. if (eof) { return 0; }
  7194. if (!chunked) {
  7195. // Content-Length based reading
  7196. if (has_content_length && bytes_read >= content_length) {
  7197. eof = true;
  7198. return 0;
  7199. }
  7200. auto to_read = len;
  7201. if (has_content_length) {
  7202. auto remaining = content_length - bytes_read;
  7203. to_read = (std::min)(len, remaining);
  7204. }
  7205. auto n = stream->read(buf, to_read);
  7206. if (n < 0) {
  7207. last_error = stream->get_error();
  7208. if (last_error == Error::Success) { last_error = Error::Read; }
  7209. eof = true;
  7210. return n;
  7211. }
  7212. if (n == 0) {
  7213. // Unexpected EOF before content_length
  7214. last_error = stream->get_error();
  7215. if (last_error == Error::Success) { last_error = Error::Read; }
  7216. eof = true;
  7217. return 0;
  7218. }
  7219. bytes_read += static_cast<size_t>(n);
  7220. if (has_content_length && bytes_read >= content_length) { eof = true; }
  7221. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  7222. last_error = Error::ExceedMaxPayloadSize;
  7223. eof = true;
  7224. return -1;
  7225. }
  7226. return n;
  7227. }
  7228. // Chunked transfer encoding: delegate to shared decoder instance.
  7229. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  7230. size_t chunk_offset = 0;
  7231. size_t chunk_total = 0;
  7232. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  7233. if (n < 0) {
  7234. last_error = stream->get_error();
  7235. if (last_error == Error::Success) { last_error = Error::Read; }
  7236. eof = true;
  7237. return n;
  7238. }
  7239. if (n == 0) {
  7240. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  7241. eof = true;
  7242. return 0;
  7243. }
  7244. bytes_read += static_cast<size_t>(n);
  7245. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  7246. last_error = Error::ExceedMaxPayloadSize;
  7247. eof = true;
  7248. return -1;
  7249. }
  7250. return n;
  7251. }
  7252. // ThreadPool implementation
  7253. inline ThreadPool::ThreadPool(size_t n, size_t mqr)
  7254. : shutdown_(false), max_queued_requests_(mqr) {
  7255. threads_.reserve(n);
  7256. while (n) {
  7257. threads_.emplace_back(worker(*this));
  7258. n--;
  7259. }
  7260. }
  7261. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  7262. {
  7263. std::unique_lock<std::mutex> lock(mutex_);
  7264. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  7265. return false;
  7266. }
  7267. jobs_.push_back(std::move(fn));
  7268. }
  7269. cond_.notify_one();
  7270. return true;
  7271. }
  7272. inline void ThreadPool::shutdown() {
  7273. // Stop all worker threads...
  7274. {
  7275. std::unique_lock<std::mutex> lock(mutex_);
  7276. shutdown_ = true;
  7277. }
  7278. cond_.notify_all();
  7279. // Join...
  7280. for (auto &t : threads_) {
  7281. t.join();
  7282. }
  7283. }
  7284. inline ThreadPool::worker::worker(ThreadPool &pool) : pool_(pool) {}
  7285. inline void ThreadPool::worker::operator()() {
  7286. for (;;) {
  7287. std::function<void()> fn;
  7288. {
  7289. std::unique_lock<std::mutex> lock(pool_.mutex_);
  7290. pool_.cond_.wait(lock,
  7291. [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  7292. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  7293. fn = pool_.jobs_.front();
  7294. pool_.jobs_.pop_front();
  7295. }
  7296. assert(true == static_cast<bool>(fn));
  7297. fn();
  7298. }
  7299. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  7300. !defined(LIBRESSL_VERSION_NUMBER)
  7301. OPENSSL_thread_stop();
  7302. #endif
  7303. }
  7304. /*
  7305. * Group 1 (continued): detail namespace - Stream implementations
  7306. */
  7307. namespace detail {
  7308. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  7309. time_t timeout_sec, time_t timeout_usec,
  7310. time_t &actual_timeout_sec,
  7311. time_t &actual_timeout_usec) {
  7312. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  7313. auto actual_timeout_msec =
  7314. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  7315. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  7316. actual_timeout_sec = actual_timeout_msec / 1000;
  7317. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  7318. }
  7319. // Socket stream implementation
  7320. inline SocketStream::SocketStream(
  7321. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  7322. time_t write_timeout_sec, time_t write_timeout_usec,
  7323. time_t max_timeout_msec,
  7324. std::chrono::time_point<std::chrono::steady_clock> start_time)
  7325. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  7326. read_timeout_usec_(read_timeout_usec),
  7327. write_timeout_sec_(write_timeout_sec),
  7328. write_timeout_usec_(write_timeout_usec),
  7329. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  7330. read_buff_(read_buff_size_, 0) {}
  7331. inline SocketStream::~SocketStream() = default;
  7332. inline bool SocketStream::is_readable() const {
  7333. return read_buff_off_ < read_buff_content_size_;
  7334. }
  7335. inline bool SocketStream::wait_readable() const {
  7336. if (max_timeout_msec_ <= 0) {
  7337. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  7338. }
  7339. time_t read_timeout_sec;
  7340. time_t read_timeout_usec;
  7341. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  7342. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  7343. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  7344. }
  7345. inline bool SocketStream::wait_writable() const {
  7346. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  7347. is_socket_alive(sock_);
  7348. }
  7349. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  7350. #ifdef _WIN32
  7351. size =
  7352. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7353. #else
  7354. size = (std::min)(size,
  7355. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  7356. #endif
  7357. if (read_buff_off_ < read_buff_content_size_) {
  7358. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  7359. if (size <= remaining_size) {
  7360. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  7361. read_buff_off_ += size;
  7362. return static_cast<ssize_t>(size);
  7363. } else {
  7364. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  7365. read_buff_off_ += remaining_size;
  7366. return static_cast<ssize_t>(remaining_size);
  7367. }
  7368. }
  7369. if (!wait_readable()) {
  7370. error_ = Error::Timeout;
  7371. return -1;
  7372. }
  7373. read_buff_off_ = 0;
  7374. read_buff_content_size_ = 0;
  7375. if (size < read_buff_size_) {
  7376. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  7377. CPPHTTPLIB_RECV_FLAGS);
  7378. if (n <= 0) {
  7379. if (n == 0) {
  7380. error_ = Error::ConnectionClosed;
  7381. } else {
  7382. error_ = Error::Read;
  7383. }
  7384. return n;
  7385. } else if (n <= static_cast<ssize_t>(size)) {
  7386. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  7387. return n;
  7388. } else {
  7389. memcpy(ptr, read_buff_.data(), size);
  7390. read_buff_off_ = size;
  7391. read_buff_content_size_ = static_cast<size_t>(n);
  7392. return static_cast<ssize_t>(size);
  7393. }
  7394. } else {
  7395. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  7396. if (n <= 0) {
  7397. if (n == 0) {
  7398. error_ = Error::ConnectionClosed;
  7399. } else {
  7400. error_ = Error::Read;
  7401. }
  7402. }
  7403. return n;
  7404. }
  7405. }
  7406. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  7407. if (!wait_writable()) { return -1; }
  7408. #if defined(_WIN32) && !defined(_WIN64)
  7409. size =
  7410. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7411. #endif
  7412. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  7413. }
  7414. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  7415. int &port) const {
  7416. return detail::get_remote_ip_and_port(sock_, ip, port);
  7417. }
  7418. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  7419. int &port) const {
  7420. return detail::get_local_ip_and_port(sock_, ip, port);
  7421. }
  7422. inline socket_t SocketStream::socket() const { return sock_; }
  7423. inline time_t SocketStream::duration() const {
  7424. return std::chrono::duration_cast<std::chrono::milliseconds>(
  7425. std::chrono::steady_clock::now() - start_time_)
  7426. .count();
  7427. }
  7428. // Buffer stream implementation
  7429. inline bool BufferStream::is_readable() const { return true; }
  7430. inline bool BufferStream::wait_readable() const { return true; }
  7431. inline bool BufferStream::wait_writable() const { return true; }
  7432. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  7433. #if defined(_MSC_VER) && _MSC_VER < 1910
  7434. auto len_read = buffer._Copy_s(ptr, size, size, position);
  7435. #else
  7436. auto len_read = buffer.copy(ptr, size, position);
  7437. #endif
  7438. position += static_cast<size_t>(len_read);
  7439. return static_cast<ssize_t>(len_read);
  7440. }
  7441. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  7442. buffer.append(ptr, size);
  7443. return static_cast<ssize_t>(size);
  7444. }
  7445. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  7446. int & /*port*/) const {}
  7447. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  7448. int & /*port*/) const {}
  7449. inline socket_t BufferStream::socket() const { return 0; }
  7450. inline time_t BufferStream::duration() const { return 0; }
  7451. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  7452. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  7453. : MatcherBase(pattern) {
  7454. constexpr const char marker[] = "/:";
  7455. // One past the last ending position of a path param substring
  7456. std::size_t last_param_end = 0;
  7457. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7458. // Needed to ensure that parameter names are unique during matcher
  7459. // construction
  7460. // If exceptions are disabled, only last duplicate path
  7461. // parameter will be set
  7462. std::unordered_set<std::string> param_name_set;
  7463. #endif
  7464. while (true) {
  7465. const auto marker_pos = pattern.find(
  7466. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  7467. if (marker_pos == std::string::npos) { break; }
  7468. static_fragments_.push_back(
  7469. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  7470. const auto param_name_start = marker_pos + str_len(marker);
  7471. auto sep_pos = pattern.find(separator, param_name_start);
  7472. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  7473. auto param_name =
  7474. pattern.substr(param_name_start, sep_pos - param_name_start);
  7475. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7476. if (param_name_set.find(param_name) != param_name_set.cend()) {
  7477. std::string msg = "Encountered path parameter '" + param_name +
  7478. "' multiple times in route pattern '" + pattern + "'.";
  7479. throw std::invalid_argument(msg);
  7480. }
  7481. #endif
  7482. param_names_.push_back(std::move(param_name));
  7483. last_param_end = sep_pos + 1;
  7484. }
  7485. if (last_param_end < pattern.length()) {
  7486. static_fragments_.push_back(pattern.substr(last_param_end));
  7487. }
  7488. }
  7489. inline bool PathParamsMatcher::match(Request &request) const {
  7490. request.matches = std::smatch();
  7491. request.path_params.clear();
  7492. request.path_params.reserve(param_names_.size());
  7493. // One past the position at which the path matched the pattern last time
  7494. std::size_t starting_pos = 0;
  7495. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  7496. const auto &fragment = static_fragments_[i];
  7497. if (starting_pos + fragment.length() > request.path.length()) {
  7498. return false;
  7499. }
  7500. // Avoid unnecessary allocation by using strncmp instead of substr +
  7501. // comparison
  7502. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  7503. fragment.length()) != 0) {
  7504. return false;
  7505. }
  7506. starting_pos += fragment.length();
  7507. // Should only happen when we have a static fragment after a param
  7508. // Example: '/users/:id/subscriptions'
  7509. // The 'subscriptions' fragment here does not have a corresponding param
  7510. if (i >= param_names_.size()) { continue; }
  7511. auto sep_pos = request.path.find(separator, starting_pos);
  7512. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  7513. const auto &param_name = param_names_[i];
  7514. request.path_params.emplace(
  7515. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  7516. // Mark everything up to '/' as matched
  7517. starting_pos = sep_pos + 1;
  7518. }
  7519. // Returns false if the path is longer than the pattern
  7520. return starting_pos >= request.path.length();
  7521. }
  7522. inline bool RegexMatcher::match(Request &request) const {
  7523. request.path_params.clear();
  7524. return std::regex_match(request.path, request.matches, regex_);
  7525. }
  7526. // Enclose IPv6 address in brackets if needed
  7527. inline std::string prepare_host_string(const std::string &host) {
  7528. // Enclose IPv6 address in brackets (but not if already enclosed)
  7529. if (host.find(':') == std::string::npos ||
  7530. (!host.empty() && host[0] == '[')) {
  7531. // IPv4, hostname, or already bracketed IPv6
  7532. return host;
  7533. } else {
  7534. // IPv6 address without brackets
  7535. return "[" + host + "]";
  7536. }
  7537. }
  7538. inline std::string make_host_and_port_string(const std::string &host, int port,
  7539. bool is_ssl) {
  7540. auto result = prepare_host_string(host);
  7541. // Append port if not default
  7542. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  7543. ; // do nothing
  7544. } else {
  7545. result += ":" + std::to_string(port);
  7546. }
  7547. return result;
  7548. }
  7549. // Create "host:port" string always including port number (for CONNECT method)
  7550. inline std::string
  7551. make_host_and_port_string_always_port(const std::string &host, int port) {
  7552. return prepare_host_string(host) + ":" + std::to_string(port);
  7553. }
  7554. template <typename T>
  7555. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  7556. T header_writer, Error &error) {
  7557. for (const auto &h : headers) {
  7558. if (!detail::fields::is_field_name(h.first) ||
  7559. !detail::fields::is_field_value(h.second)) {
  7560. error = Error::InvalidHeaders;
  7561. return false;
  7562. }
  7563. }
  7564. if (header_writer(strm, headers) <= 0) {
  7565. error = Error::Write;
  7566. return false;
  7567. }
  7568. return true;
  7569. }
  7570. } // namespace detail
  7571. /*
  7572. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  7573. */
  7574. #ifdef CPPHTTPLIB_SSL_ENABLED
  7575. namespace detail {
  7576. // SSL socket stream implementation
  7577. inline SSLSocketStream::SSLSocketStream(
  7578. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7579. time_t read_timeout_usec, time_t write_timeout_sec,
  7580. time_t write_timeout_usec, time_t max_timeout_msec,
  7581. std::chrono::time_point<std::chrono::steady_clock> start_time)
  7582. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  7583. read_timeout_usec_(read_timeout_usec),
  7584. write_timeout_sec_(write_timeout_sec),
  7585. write_timeout_usec_(write_timeout_usec),
  7586. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  7587. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7588. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  7589. // Note: create_session() also clears this, but SSLClient currently
  7590. // uses ssl_new() which does not. Until full TLS API migration is complete,
  7591. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  7592. // SSL session was created.
  7593. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  7594. #endif
  7595. }
  7596. inline SSLSocketStream::~SSLSocketStream() = default;
  7597. inline bool SSLSocketStream::is_readable() const {
  7598. return tls::pending(session_) > 0;
  7599. }
  7600. inline bool SSLSocketStream::wait_readable() const {
  7601. if (max_timeout_msec_ <= 0) {
  7602. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  7603. }
  7604. time_t read_timeout_sec;
  7605. time_t read_timeout_usec;
  7606. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  7607. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  7608. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  7609. }
  7610. inline bool SSLSocketStream::wait_writable() const {
  7611. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  7612. is_socket_alive(sock_) && !tls::is_peer_closed(session_, sock_);
  7613. }
  7614. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  7615. if (tls::pending(session_) > 0) {
  7616. tls::TlsError err;
  7617. auto ret = tls::read(session_, ptr, size, err);
  7618. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  7619. error_ = Error::ConnectionClosed;
  7620. }
  7621. return ret;
  7622. } else if (wait_readable()) {
  7623. tls::TlsError err;
  7624. auto ret = tls::read(session_, ptr, size, err);
  7625. if (ret < 0) {
  7626. auto n = 1000;
  7627. #ifdef _WIN32
  7628. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  7629. (err.code == tls::ErrorCode::SyscallError &&
  7630. WSAGetLastError() == WSAETIMEDOUT))) {
  7631. #else
  7632. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  7633. #endif
  7634. if (tls::pending(session_) > 0) {
  7635. return tls::read(session_, ptr, size, err);
  7636. } else if (wait_readable()) {
  7637. std::this_thread::sleep_for(std::chrono::microseconds{10});
  7638. ret = tls::read(session_, ptr, size, err);
  7639. if (ret >= 0) { return ret; }
  7640. } else {
  7641. break;
  7642. }
  7643. }
  7644. assert(ret < 0);
  7645. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  7646. error_ = Error::ConnectionClosed;
  7647. }
  7648. return ret;
  7649. } else {
  7650. error_ = Error::Timeout;
  7651. return -1;
  7652. }
  7653. }
  7654. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  7655. if (wait_writable()) {
  7656. auto handle_size =
  7657. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  7658. tls::TlsError err;
  7659. auto ret = tls::write(session_, ptr, handle_size, err);
  7660. if (ret < 0) {
  7661. auto n = 1000;
  7662. #ifdef _WIN32
  7663. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  7664. (err.code == tls::ErrorCode::SyscallError &&
  7665. WSAGetLastError() == WSAETIMEDOUT))) {
  7666. #else
  7667. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  7668. #endif
  7669. if (wait_writable()) {
  7670. std::this_thread::sleep_for(std::chrono::microseconds{10});
  7671. ret = tls::write(session_, ptr, handle_size, err);
  7672. if (ret >= 0) { return ret; }
  7673. } else {
  7674. break;
  7675. }
  7676. }
  7677. assert(ret < 0);
  7678. }
  7679. return ret;
  7680. }
  7681. return -1;
  7682. }
  7683. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  7684. int &port) const {
  7685. detail::get_remote_ip_and_port(sock_, ip, port);
  7686. }
  7687. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  7688. int &port) const {
  7689. detail::get_local_ip_and_port(sock_, ip, port);
  7690. }
  7691. inline socket_t SSLSocketStream::socket() const { return sock_; }
  7692. inline time_t SSLSocketStream::duration() const {
  7693. return std::chrono::duration_cast<std::chrono::milliseconds>(
  7694. std::chrono::steady_clock::now() - start_time_)
  7695. .count();
  7696. }
  7697. } // namespace detail
  7698. #endif // CPPHTTPLIB_SSL_ENABLED
  7699. /*
  7700. * Group 4: Server implementation
  7701. */
  7702. // HTTP server implementation
  7703. inline Server::Server()
  7704. : new_task_queue(
  7705. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  7706. #ifndef _WIN32
  7707. signal(SIGPIPE, SIG_IGN);
  7708. #endif
  7709. }
  7710. inline Server::~Server() = default;
  7711. inline std::unique_ptr<detail::MatcherBase>
  7712. Server::make_matcher(const std::string &pattern) {
  7713. if (pattern.find("/:") != std::string::npos) {
  7714. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  7715. } else {
  7716. return detail::make_unique<detail::RegexMatcher>(pattern);
  7717. }
  7718. }
  7719. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  7720. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7721. return *this;
  7722. }
  7723. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  7724. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7725. return *this;
  7726. }
  7727. inline Server &Server::Post(const std::string &pattern,
  7728. HandlerWithContentReader handler) {
  7729. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7730. std::move(handler));
  7731. return *this;
  7732. }
  7733. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  7734. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7735. return *this;
  7736. }
  7737. inline Server &Server::Put(const std::string &pattern,
  7738. HandlerWithContentReader handler) {
  7739. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7740. std::move(handler));
  7741. return *this;
  7742. }
  7743. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  7744. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7745. return *this;
  7746. }
  7747. inline Server &Server::Patch(const std::string &pattern,
  7748. HandlerWithContentReader handler) {
  7749. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7750. std::move(handler));
  7751. return *this;
  7752. }
  7753. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  7754. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7755. return *this;
  7756. }
  7757. inline Server &Server::Delete(const std::string &pattern,
  7758. HandlerWithContentReader handler) {
  7759. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7760. std::move(handler));
  7761. return *this;
  7762. }
  7763. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  7764. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7765. return *this;
  7766. }
  7767. inline bool Server::set_base_dir(const std::string &dir,
  7768. const std::string &mount_point) {
  7769. return set_mount_point(mount_point, dir);
  7770. }
  7771. inline bool Server::set_mount_point(const std::string &mount_point,
  7772. const std::string &dir, Headers headers) {
  7773. detail::FileStat stat(dir);
  7774. if (stat.is_dir()) {
  7775. std::string mnt = !mount_point.empty() ? mount_point : "/";
  7776. if (!mnt.empty() && mnt[0] == '/') {
  7777. base_dirs_.push_back({std::move(mnt), dir, std::move(headers)});
  7778. return true;
  7779. }
  7780. }
  7781. return false;
  7782. }
  7783. inline bool Server::remove_mount_point(const std::string &mount_point) {
  7784. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  7785. if (it->mount_point == mount_point) {
  7786. base_dirs_.erase(it);
  7787. return true;
  7788. }
  7789. }
  7790. return false;
  7791. }
  7792. inline Server &
  7793. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  7794. const std::string &mime) {
  7795. file_extension_and_mimetype_map_[ext] = mime;
  7796. return *this;
  7797. }
  7798. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  7799. default_file_mimetype_ = mime;
  7800. return *this;
  7801. }
  7802. inline Server &Server::set_file_request_handler(Handler handler) {
  7803. file_request_handler_ = std::move(handler);
  7804. return *this;
  7805. }
  7806. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  7807. std::true_type) {
  7808. error_handler_ = std::move(handler);
  7809. return *this;
  7810. }
  7811. inline Server &Server::set_error_handler_core(Handler handler,
  7812. std::false_type) {
  7813. error_handler_ = [handler](const Request &req, Response &res) {
  7814. handler(req, res);
  7815. return HandlerResponse::Handled;
  7816. };
  7817. return *this;
  7818. }
  7819. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  7820. exception_handler_ = std::move(handler);
  7821. return *this;
  7822. }
  7823. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  7824. pre_routing_handler_ = std::move(handler);
  7825. return *this;
  7826. }
  7827. inline Server &Server::set_post_routing_handler(Handler handler) {
  7828. post_routing_handler_ = std::move(handler);
  7829. return *this;
  7830. }
  7831. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  7832. pre_request_handler_ = std::move(handler);
  7833. return *this;
  7834. }
  7835. inline Server &Server::set_logger(Logger logger) {
  7836. logger_ = std::move(logger);
  7837. return *this;
  7838. }
  7839. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  7840. error_logger_ = std::move(error_logger);
  7841. return *this;
  7842. }
  7843. inline Server &Server::set_pre_compression_logger(Logger logger) {
  7844. pre_compression_logger_ = std::move(logger);
  7845. return *this;
  7846. }
  7847. inline Server &
  7848. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  7849. expect_100_continue_handler_ = std::move(handler);
  7850. return *this;
  7851. }
  7852. inline Server &Server::set_address_family(int family) {
  7853. address_family_ = family;
  7854. return *this;
  7855. }
  7856. inline Server &Server::set_tcp_nodelay(bool on) {
  7857. tcp_nodelay_ = on;
  7858. return *this;
  7859. }
  7860. inline Server &Server::set_ipv6_v6only(bool on) {
  7861. ipv6_v6only_ = on;
  7862. return *this;
  7863. }
  7864. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  7865. socket_options_ = std::move(socket_options);
  7866. return *this;
  7867. }
  7868. inline Server &Server::set_default_headers(Headers headers) {
  7869. default_headers_ = std::move(headers);
  7870. return *this;
  7871. }
  7872. inline Server &Server::set_header_writer(
  7873. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7874. header_writer_ = writer;
  7875. return *this;
  7876. }
  7877. inline Server &
  7878. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  7879. trusted_proxies_ = proxies;
  7880. return *this;
  7881. }
  7882. inline Server &Server::set_keep_alive_max_count(size_t count) {
  7883. keep_alive_max_count_ = count;
  7884. return *this;
  7885. }
  7886. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  7887. keep_alive_timeout_sec_ = sec;
  7888. return *this;
  7889. }
  7890. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  7891. read_timeout_sec_ = sec;
  7892. read_timeout_usec_ = usec;
  7893. return *this;
  7894. }
  7895. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  7896. write_timeout_sec_ = sec;
  7897. write_timeout_usec_ = usec;
  7898. return *this;
  7899. }
  7900. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  7901. idle_interval_sec_ = sec;
  7902. idle_interval_usec_ = usec;
  7903. return *this;
  7904. }
  7905. inline Server &Server::set_payload_max_length(size_t length) {
  7906. payload_max_length_ = length;
  7907. return *this;
  7908. }
  7909. inline bool Server::bind_to_port(const std::string &host, int port,
  7910. int socket_flags) {
  7911. auto ret = bind_internal(host, port, socket_flags);
  7912. if (ret == -1) { is_decommissioned = true; }
  7913. return ret >= 0;
  7914. }
  7915. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  7916. auto ret = bind_internal(host, 0, socket_flags);
  7917. if (ret == -1) { is_decommissioned = true; }
  7918. return ret;
  7919. }
  7920. inline bool Server::listen_after_bind() { return listen_internal(); }
  7921. inline bool Server::listen(const std::string &host, int port,
  7922. int socket_flags) {
  7923. return bind_to_port(host, port, socket_flags) && listen_internal();
  7924. }
  7925. inline bool Server::is_running() const { return is_running_; }
  7926. inline void Server::wait_until_ready() const {
  7927. while (!is_running_ && !is_decommissioned) {
  7928. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7929. }
  7930. }
  7931. inline void Server::stop() {
  7932. if (is_running_) {
  7933. assert(svr_sock_ != INVALID_SOCKET);
  7934. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  7935. detail::shutdown_socket(sock);
  7936. detail::close_socket(sock);
  7937. }
  7938. is_decommissioned = false;
  7939. }
  7940. inline void Server::decommission() { is_decommissioned = true; }
  7941. inline bool Server::parse_request_line(const char *s, Request &req) const {
  7942. auto len = strlen(s);
  7943. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  7944. len -= 2;
  7945. {
  7946. size_t count = 0;
  7947. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  7948. switch (count) {
  7949. case 0: req.method = std::string(b, e); break;
  7950. case 1: req.target = std::string(b, e); break;
  7951. case 2: req.version = std::string(b, e); break;
  7952. default: break;
  7953. }
  7954. count++;
  7955. });
  7956. if (count != 3) { return false; }
  7957. }
  7958. thread_local const std::set<std::string> methods{
  7959. "GET", "HEAD", "POST", "PUT", "DELETE",
  7960. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7961. if (methods.find(req.method) == methods.end()) {
  7962. output_error_log(Error::InvalidHTTPMethod, &req);
  7963. return false;
  7964. }
  7965. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  7966. output_error_log(Error::InvalidHTTPVersion, &req);
  7967. return false;
  7968. }
  7969. {
  7970. // Skip URL fragment
  7971. for (size_t i = 0; i < req.target.size(); i++) {
  7972. if (req.target[i] == '#') {
  7973. req.target.erase(i);
  7974. break;
  7975. }
  7976. }
  7977. detail::divide(req.target, '?',
  7978. [&](const char *lhs_data, std::size_t lhs_size,
  7979. const char *rhs_data, std::size_t rhs_size) {
  7980. req.path =
  7981. decode_path_component(std::string(lhs_data, lhs_size));
  7982. detail::parse_query_text(rhs_data, rhs_size, req.params);
  7983. });
  7984. }
  7985. return true;
  7986. }
  7987. inline bool Server::write_response(Stream &strm, bool close_connection,
  7988. Request &req, Response &res) {
  7989. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  7990. // incorrectly to the error content.
  7991. req.ranges.clear();
  7992. return write_response_core(strm, close_connection, req, res, false);
  7993. }
  7994. inline bool Server::write_response_with_content(Stream &strm,
  7995. bool close_connection,
  7996. const Request &req,
  7997. Response &res) {
  7998. return write_response_core(strm, close_connection, req, res, true);
  7999. }
  8000. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  8001. const Request &req, Response &res,
  8002. bool need_apply_ranges) {
  8003. assert(res.status != -1);
  8004. if (400 <= res.status && error_handler_ &&
  8005. error_handler_(req, res) == HandlerResponse::Handled) {
  8006. need_apply_ranges = true;
  8007. }
  8008. std::string content_type;
  8009. std::string boundary;
  8010. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  8011. // Prepare additional headers
  8012. if (close_connection || req.get_header_value("Connection") == "close" ||
  8013. 400 <= res.status) { // Don't leave connections open after errors
  8014. res.set_header("Connection", "close");
  8015. } else {
  8016. std::string s = "timeout=";
  8017. s += std::to_string(keep_alive_timeout_sec_);
  8018. s += ", max=";
  8019. s += std::to_string(keep_alive_max_count_);
  8020. res.set_header("Keep-Alive", s);
  8021. }
  8022. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  8023. !res.has_header("Content-Type")) {
  8024. res.set_header("Content-Type", "text/plain");
  8025. }
  8026. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  8027. !res.has_header("Content-Length")) {
  8028. res.set_header("Content-Length", "0");
  8029. }
  8030. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  8031. res.set_header("Accept-Ranges", "bytes");
  8032. }
  8033. if (post_routing_handler_) { post_routing_handler_(req, res); }
  8034. // Response line and headers
  8035. {
  8036. detail::BufferStream bstrm;
  8037. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  8038. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  8039. // Flush buffer
  8040. auto &data = bstrm.get_buffer();
  8041. detail::write_data(strm, data.data(), data.size());
  8042. }
  8043. // Body
  8044. auto ret = true;
  8045. if (req.method != "HEAD") {
  8046. if (!res.body.empty()) {
  8047. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  8048. ret = false;
  8049. }
  8050. } else if (res.content_provider_) {
  8051. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  8052. res.content_provider_success_ = true;
  8053. } else {
  8054. ret = false;
  8055. }
  8056. }
  8057. }
  8058. // Log
  8059. output_log(req, res);
  8060. return ret;
  8061. }
  8062. inline bool
  8063. Server::write_content_with_provider(Stream &strm, const Request &req,
  8064. Response &res, const std::string &boundary,
  8065. const std::string &content_type) {
  8066. auto is_shutting_down = [this]() {
  8067. return this->svr_sock_ == INVALID_SOCKET;
  8068. };
  8069. if (res.content_length_ > 0) {
  8070. if (req.ranges.empty()) {
  8071. return detail::write_content(strm, res.content_provider_, 0,
  8072. res.content_length_, is_shutting_down);
  8073. } else if (req.ranges.size() == 1) {
  8074. auto offset_and_length = detail::get_range_offset_and_length(
  8075. req.ranges[0], res.content_length_);
  8076. return detail::write_content(strm, res.content_provider_,
  8077. offset_and_length.first,
  8078. offset_and_length.second, is_shutting_down);
  8079. } else {
  8080. return detail::write_multipart_ranges_data(
  8081. strm, req, res, boundary, content_type, res.content_length_,
  8082. is_shutting_down);
  8083. }
  8084. } else {
  8085. if (res.is_chunked_content_provider_) {
  8086. auto type = detail::encoding_type(req, res);
  8087. std::unique_ptr<detail::compressor> compressor;
  8088. if (type == detail::EncodingType::Gzip) {
  8089. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8090. compressor = detail::make_unique<detail::gzip_compressor>();
  8091. #endif
  8092. } else if (type == detail::EncodingType::Brotli) {
  8093. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8094. compressor = detail::make_unique<detail::brotli_compressor>();
  8095. #endif
  8096. } else if (type == detail::EncodingType::Zstd) {
  8097. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8098. compressor = detail::make_unique<detail::zstd_compressor>();
  8099. #endif
  8100. } else {
  8101. compressor = detail::make_unique<detail::nocompressor>();
  8102. }
  8103. assert(compressor != nullptr);
  8104. return detail::write_content_chunked(strm, res.content_provider_,
  8105. is_shutting_down, *compressor);
  8106. } else {
  8107. return detail::write_content_without_length(strm, res.content_provider_,
  8108. is_shutting_down);
  8109. }
  8110. }
  8111. }
  8112. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  8113. FormFields::iterator cur_field;
  8114. FormFiles::iterator cur_file;
  8115. auto is_text_field = false;
  8116. size_t count = 0;
  8117. if (read_content_core(
  8118. strm, req, res,
  8119. // Regular
  8120. [&](const char *buf, size_t n) {
  8121. // Prevent arithmetic overflow when checking sizes.
  8122. // Avoid computing (req.body.size() + n) directly because
  8123. // adding two unsigned `size_t` values can wrap around and
  8124. // produce a small result instead of indicating overflow.
  8125. // Instead, check using subtraction: ensure `n` does not
  8126. // exceed the remaining capacity `max_size() - size()`.
  8127. if (req.body.size() >= req.body.max_size() ||
  8128. n > req.body.max_size() - req.body.size()) {
  8129. return false;
  8130. }
  8131. // Limit decompressed body size to payload_max_length_ to protect
  8132. // against "zip bomb" attacks where a small compressed payload
  8133. // decompresses to a massive size.
  8134. if (payload_max_length_ > 0 &&
  8135. (req.body.size() >= payload_max_length_ ||
  8136. n > payload_max_length_ - req.body.size())) {
  8137. return false;
  8138. }
  8139. req.body.append(buf, n);
  8140. return true;
  8141. },
  8142. // Multipart FormData
  8143. [&](const FormData &file) {
  8144. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  8145. output_error_log(Error::TooManyFormDataFiles, &req);
  8146. return false;
  8147. }
  8148. if (file.filename.empty()) {
  8149. cur_field = req.form.fields.emplace(
  8150. file.name, FormField{file.name, file.content, file.headers});
  8151. is_text_field = true;
  8152. } else {
  8153. cur_file = req.form.files.emplace(file.name, file);
  8154. is_text_field = false;
  8155. }
  8156. return true;
  8157. },
  8158. [&](const char *buf, size_t n) {
  8159. if (is_text_field) {
  8160. auto &content = cur_field->second.content;
  8161. if (content.size() + n > content.max_size()) { return false; }
  8162. content.append(buf, n);
  8163. } else {
  8164. auto &content = cur_file->second.content;
  8165. if (content.size() + n > content.max_size()) { return false; }
  8166. content.append(buf, n);
  8167. }
  8168. return true;
  8169. })) {
  8170. const auto &content_type = req.get_header_value("Content-Type");
  8171. if (!content_type.find("application/x-www-form-urlencoded")) {
  8172. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  8173. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  8174. output_error_log(Error::ExceedMaxPayloadSize, &req);
  8175. return false;
  8176. }
  8177. detail::parse_query_text(req.body, req.params);
  8178. }
  8179. return true;
  8180. }
  8181. return false;
  8182. }
  8183. inline bool Server::read_content_with_content_receiver(
  8184. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  8185. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  8186. return read_content_core(strm, req, res, std::move(receiver),
  8187. std::move(multipart_header),
  8188. std::move(multipart_receiver));
  8189. }
  8190. inline bool Server::read_content_core(
  8191. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  8192. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  8193. detail::FormDataParser multipart_form_data_parser;
  8194. ContentReceiverWithProgress out;
  8195. if (req.is_multipart_form_data()) {
  8196. const auto &content_type = req.get_header_value("Content-Type");
  8197. std::string boundary;
  8198. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  8199. res.status = StatusCode::BadRequest_400;
  8200. output_error_log(Error::MultipartParsing, &req);
  8201. return false;
  8202. }
  8203. multipart_form_data_parser.set_boundary(std::move(boundary));
  8204. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  8205. return multipart_form_data_parser.parse(buf, n, multipart_header,
  8206. multipart_receiver);
  8207. };
  8208. } else {
  8209. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  8210. size_t /*len*/) { return receiver(buf, n); };
  8211. }
  8212. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  8213. // are true (no Transfer-Encoding and no Content-Length), then the message
  8214. // body length is zero (no message body is present).
  8215. //
  8216. // For non-SSL builds, detect clients that send a body without a
  8217. // Content-Length header (raw HTTP over TCP). Check both the stream's
  8218. // internal read buffer (data already read from the socket during header
  8219. // parsing) and the socket itself for pending data. If data is found and
  8220. // exceeds the configured payload limit, reject with 413.
  8221. // For SSL builds we cannot reliably peek the decrypted application bytes,
  8222. // so keep the original behaviour.
  8223. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  8224. if (!req.has_header("Content-Length") &&
  8225. !detail::is_chunked_transfer_encoding(req.headers)) {
  8226. // Only check if payload_max_length is set to a finite value
  8227. if (payload_max_length_ > 0 &&
  8228. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  8229. // Check if there is data already buffered in the stream (read during
  8230. // header parsing) or pending on the socket. Use a non-blocking socket
  8231. // check to avoid deadlock when the client sends no body.
  8232. bool has_data = strm.is_readable();
  8233. if (!has_data) {
  8234. socket_t s = strm.socket();
  8235. if (s != INVALID_SOCKET) {
  8236. has_data = detail::select_read(s, 0, 0) > 0;
  8237. }
  8238. }
  8239. if (has_data) {
  8240. auto result =
  8241. detail::read_content_without_length(strm, payload_max_length_, out);
  8242. if (result == detail::ReadContentResult::PayloadTooLarge) {
  8243. res.status = StatusCode::PayloadTooLarge_413;
  8244. return false;
  8245. } else if (result != detail::ReadContentResult::Success) {
  8246. return false;
  8247. }
  8248. return true;
  8249. }
  8250. }
  8251. return true;
  8252. }
  8253. #else
  8254. if (!req.has_header("Content-Length") &&
  8255. !detail::is_chunked_transfer_encoding(req.headers)) {
  8256. return true;
  8257. }
  8258. #endif
  8259. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  8260. out, true)) {
  8261. return false;
  8262. }
  8263. if (req.is_multipart_form_data()) {
  8264. if (!multipart_form_data_parser.is_valid()) {
  8265. res.status = StatusCode::BadRequest_400;
  8266. output_error_log(Error::MultipartParsing, &req);
  8267. return false;
  8268. }
  8269. }
  8270. return true;
  8271. }
  8272. inline bool Server::handle_file_request(Request &req, Response &res) {
  8273. for (const auto &entry : base_dirs_) {
  8274. // Prefix match
  8275. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  8276. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  8277. if (detail::is_valid_path(sub_path)) {
  8278. auto path = entry.base_dir + sub_path;
  8279. if (path.back() == '/') { path += "index.html"; }
  8280. detail::FileStat stat(path);
  8281. if (stat.is_dir()) {
  8282. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  8283. return true;
  8284. }
  8285. if (stat.is_file()) {
  8286. for (const auto &kv : entry.headers) {
  8287. res.set_header(kv.first, kv.second);
  8288. }
  8289. auto etag = detail::compute_etag(stat);
  8290. if (!etag.empty()) { res.set_header("ETag", etag); }
  8291. auto mtime = stat.mtime();
  8292. auto last_modified = detail::file_mtime_to_http_date(mtime);
  8293. if (!last_modified.empty()) {
  8294. res.set_header("Last-Modified", last_modified);
  8295. }
  8296. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  8297. check_if_range(req, etag, mtime);
  8298. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8299. if (!mm->is_open()) {
  8300. output_error_log(Error::OpenFile, &req);
  8301. return false;
  8302. }
  8303. res.set_content_provider(
  8304. mm->size(),
  8305. detail::find_content_type(path, file_extension_and_mimetype_map_,
  8306. default_file_mimetype_),
  8307. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8308. sink.write(mm->data() + offset, length);
  8309. return true;
  8310. });
  8311. if (req.method != "HEAD" && file_request_handler_) {
  8312. file_request_handler_(req, res);
  8313. }
  8314. return true;
  8315. } else {
  8316. output_error_log(Error::OpenFile, &req);
  8317. }
  8318. }
  8319. }
  8320. }
  8321. return false;
  8322. }
  8323. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  8324. const std::string &etag,
  8325. time_t mtime) const {
  8326. // Handle conditional GET:
  8327. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  8328. // 2. If-Modified-Since is checked only when If-None-Match is absent
  8329. if (req.has_header("If-None-Match")) {
  8330. if (!etag.empty()) {
  8331. auto val = req.get_header_value("If-None-Match");
  8332. // NOTE: We use exact string matching here. This works correctly
  8333. // because our server always generates weak ETags (W/"..."), and
  8334. // clients typically send back the same ETag they received.
  8335. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  8336. // If-None-Match, where W/"x" and "x" would match, but this
  8337. // simplified implementation requires exact matches.
  8338. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  8339. [&](const char *b, const char *e) {
  8340. auto seg_len = static_cast<size_t>(e - b);
  8341. return (seg_len == 1 && *b == '*') ||
  8342. (seg_len == etag.size() &&
  8343. std::equal(b, e, etag.begin()));
  8344. });
  8345. if (ret) {
  8346. res.status = StatusCode::NotModified_304;
  8347. return true;
  8348. }
  8349. }
  8350. } else if (req.has_header("If-Modified-Since")) {
  8351. auto val = req.get_header_value("If-Modified-Since");
  8352. auto t = detail::parse_http_date(val);
  8353. if (t != static_cast<time_t>(-1) && mtime <= t) {
  8354. res.status = StatusCode::NotModified_304;
  8355. return true;
  8356. }
  8357. }
  8358. return false;
  8359. }
  8360. inline bool Server::check_if_range(Request &req, const std::string &etag,
  8361. time_t mtime) const {
  8362. // Handle If-Range for partial content requests (RFC 9110
  8363. // Section 13.1.5). If-Range is only evaluated when Range header is
  8364. // present. If the validator matches, serve partial content; otherwise
  8365. // serve full content.
  8366. if (!req.ranges.empty() && req.has_header("If-Range")) {
  8367. auto val = req.get_header_value("If-Range");
  8368. auto is_valid_range = [&]() {
  8369. if (detail::is_strong_etag(val)) {
  8370. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  8371. // comparison.
  8372. return (!etag.empty() && val == etag);
  8373. } else if (detail::is_weak_etag(val)) {
  8374. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  8375. return false;
  8376. } else {
  8377. // HTTP-date comparison
  8378. auto t = detail::parse_http_date(val);
  8379. return (t != static_cast<time_t>(-1) && mtime <= t);
  8380. }
  8381. };
  8382. if (!is_valid_range()) {
  8383. // Validator doesn't match: ignore Range and serve full content
  8384. req.ranges.clear();
  8385. return false;
  8386. }
  8387. }
  8388. return true;
  8389. }
  8390. inline socket_t
  8391. Server::create_server_socket(const std::string &host, int port,
  8392. int socket_flags,
  8393. SocketOptions socket_options) const {
  8394. return detail::create_socket(
  8395. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  8396. ipv6_v6only_, std::move(socket_options),
  8397. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  8398. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  8399. output_error_log(Error::BindIPAddress, nullptr);
  8400. return false;
  8401. }
  8402. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  8403. output_error_log(Error::Listen, nullptr);
  8404. return false;
  8405. }
  8406. return true;
  8407. });
  8408. }
  8409. inline int Server::bind_internal(const std::string &host, int port,
  8410. int socket_flags) {
  8411. if (is_decommissioned) { return -1; }
  8412. if (!is_valid()) { return -1; }
  8413. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  8414. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  8415. if (port == 0) {
  8416. struct sockaddr_storage addr;
  8417. socklen_t addr_len = sizeof(addr);
  8418. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  8419. &addr_len) == -1) {
  8420. output_error_log(Error::GetSockName, nullptr);
  8421. return -1;
  8422. }
  8423. if (addr.ss_family == AF_INET) {
  8424. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  8425. } else if (addr.ss_family == AF_INET6) {
  8426. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  8427. } else {
  8428. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  8429. return -1;
  8430. }
  8431. } else {
  8432. return port;
  8433. }
  8434. }
  8435. inline bool Server::listen_internal() {
  8436. if (is_decommissioned) { return false; }
  8437. auto ret = true;
  8438. is_running_ = true;
  8439. auto se = detail::scope_exit([&]() { is_running_ = false; });
  8440. {
  8441. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  8442. while (svr_sock_ != INVALID_SOCKET) {
  8443. #ifndef _WIN32
  8444. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  8445. #endif
  8446. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  8447. idle_interval_usec_);
  8448. if (val == 0) { // Timeout
  8449. task_queue->on_idle();
  8450. continue;
  8451. }
  8452. #ifndef _WIN32
  8453. }
  8454. #endif
  8455. #if defined _WIN32
  8456. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  8457. // OVERLAPPED
  8458. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  8459. #elif defined SOCK_CLOEXEC
  8460. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  8461. #else
  8462. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  8463. #endif
  8464. if (sock == INVALID_SOCKET) {
  8465. if (errno == EMFILE) {
  8466. // The per-process limit of open file descriptors has been reached.
  8467. // Try to accept new connections after a short sleep.
  8468. std::this_thread::sleep_for(std::chrono::microseconds{1});
  8469. continue;
  8470. } else if (errno == EINTR || errno == EAGAIN) {
  8471. continue;
  8472. }
  8473. if (svr_sock_ != INVALID_SOCKET) {
  8474. detail::close_socket(svr_sock_);
  8475. ret = false;
  8476. output_error_log(Error::Connection, nullptr);
  8477. } else {
  8478. ; // The server socket was closed by user.
  8479. }
  8480. break;
  8481. }
  8482. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  8483. read_timeout_sec_, read_timeout_usec_);
  8484. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  8485. write_timeout_sec_, write_timeout_usec_);
  8486. if (!task_queue->enqueue(
  8487. [this, sock]() { process_and_close_socket(sock); })) {
  8488. output_error_log(Error::ResourceExhaustion, nullptr);
  8489. detail::shutdown_socket(sock);
  8490. detail::close_socket(sock);
  8491. }
  8492. }
  8493. task_queue->shutdown();
  8494. }
  8495. is_decommissioned = !ret;
  8496. return ret;
  8497. }
  8498. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  8499. if (pre_routing_handler_ &&
  8500. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  8501. return true;
  8502. }
  8503. // File handler
  8504. if ((req.method == "GET" || req.method == "HEAD") &&
  8505. handle_file_request(req, res)) {
  8506. return true;
  8507. }
  8508. if (detail::expect_content(req)) {
  8509. // Content reader handler
  8510. {
  8511. ContentReader reader(
  8512. [&](ContentReceiver receiver) {
  8513. auto result = read_content_with_content_receiver(
  8514. strm, req, res, std::move(receiver), nullptr, nullptr);
  8515. if (!result) { output_error_log(Error::Read, &req); }
  8516. return result;
  8517. },
  8518. [&](FormDataHeader header, ContentReceiver receiver) {
  8519. auto result = read_content_with_content_receiver(
  8520. strm, req, res, nullptr, std::move(header),
  8521. std::move(receiver));
  8522. if (!result) { output_error_log(Error::Read, &req); }
  8523. return result;
  8524. });
  8525. if (req.method == "POST") {
  8526. if (dispatch_request_for_content_reader(
  8527. req, res, std::move(reader),
  8528. post_handlers_for_content_reader_)) {
  8529. return true;
  8530. }
  8531. } else if (req.method == "PUT") {
  8532. if (dispatch_request_for_content_reader(
  8533. req, res, std::move(reader),
  8534. put_handlers_for_content_reader_)) {
  8535. return true;
  8536. }
  8537. } else if (req.method == "PATCH") {
  8538. if (dispatch_request_for_content_reader(
  8539. req, res, std::move(reader),
  8540. patch_handlers_for_content_reader_)) {
  8541. return true;
  8542. }
  8543. } else if (req.method == "DELETE") {
  8544. if (dispatch_request_for_content_reader(
  8545. req, res, std::move(reader),
  8546. delete_handlers_for_content_reader_)) {
  8547. return true;
  8548. }
  8549. }
  8550. }
  8551. // Read content into `req.body`
  8552. if (!read_content(strm, req, res)) {
  8553. output_error_log(Error::Read, &req);
  8554. return false;
  8555. }
  8556. }
  8557. // Regular handler
  8558. if (req.method == "GET" || req.method == "HEAD") {
  8559. return dispatch_request(req, res, get_handlers_);
  8560. } else if (req.method == "POST") {
  8561. return dispatch_request(req, res, post_handlers_);
  8562. } else if (req.method == "PUT") {
  8563. return dispatch_request(req, res, put_handlers_);
  8564. } else if (req.method == "DELETE") {
  8565. return dispatch_request(req, res, delete_handlers_);
  8566. } else if (req.method == "OPTIONS") {
  8567. return dispatch_request(req, res, options_handlers_);
  8568. } else if (req.method == "PATCH") {
  8569. return dispatch_request(req, res, patch_handlers_);
  8570. }
  8571. res.status = StatusCode::BadRequest_400;
  8572. return false;
  8573. }
  8574. inline bool Server::dispatch_request(Request &req, Response &res,
  8575. const Handlers &handlers) const {
  8576. for (const auto &x : handlers) {
  8577. const auto &matcher = x.first;
  8578. const auto &handler = x.second;
  8579. if (matcher->match(req)) {
  8580. req.matched_route = matcher->pattern();
  8581. if (!pre_request_handler_ ||
  8582. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8583. handler(req, res);
  8584. }
  8585. return true;
  8586. }
  8587. }
  8588. return false;
  8589. }
  8590. inline void Server::apply_ranges(const Request &req, Response &res,
  8591. std::string &content_type,
  8592. std::string &boundary) const {
  8593. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  8594. auto it = res.headers.find("Content-Type");
  8595. if (it != res.headers.end()) {
  8596. content_type = it->second;
  8597. res.headers.erase(it);
  8598. }
  8599. boundary = detail::make_multipart_data_boundary();
  8600. res.set_header("Content-Type",
  8601. "multipart/byteranges; boundary=" + boundary);
  8602. }
  8603. auto type = detail::encoding_type(req, res);
  8604. if (res.body.empty()) {
  8605. if (res.content_length_ > 0) {
  8606. size_t length = 0;
  8607. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8608. length = res.content_length_;
  8609. } else if (req.ranges.size() == 1) {
  8610. auto offset_and_length = detail::get_range_offset_and_length(
  8611. req.ranges[0], res.content_length_);
  8612. length = offset_and_length.second;
  8613. auto content_range = detail::make_content_range_header_field(
  8614. offset_and_length, res.content_length_);
  8615. res.set_header("Content-Range", content_range);
  8616. } else {
  8617. length = detail::get_multipart_ranges_data_length(
  8618. req, boundary, content_type, res.content_length_);
  8619. }
  8620. res.set_header("Content-Length", std::to_string(length));
  8621. } else {
  8622. if (res.content_provider_) {
  8623. if (res.is_chunked_content_provider_) {
  8624. res.set_header("Transfer-Encoding", "chunked");
  8625. if (type == detail::EncodingType::Gzip) {
  8626. res.set_header("Content-Encoding", "gzip");
  8627. res.set_header("Vary", "Accept-Encoding");
  8628. } else if (type == detail::EncodingType::Brotli) {
  8629. res.set_header("Content-Encoding", "br");
  8630. res.set_header("Vary", "Accept-Encoding");
  8631. } else if (type == detail::EncodingType::Zstd) {
  8632. res.set_header("Content-Encoding", "zstd");
  8633. res.set_header("Vary", "Accept-Encoding");
  8634. }
  8635. }
  8636. }
  8637. }
  8638. } else {
  8639. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8640. ;
  8641. } else if (req.ranges.size() == 1) {
  8642. auto offset_and_length =
  8643. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  8644. auto offset = offset_and_length.first;
  8645. auto length = offset_and_length.second;
  8646. auto content_range = detail::make_content_range_header_field(
  8647. offset_and_length, res.body.size());
  8648. res.set_header("Content-Range", content_range);
  8649. assert(offset + length <= res.body.size());
  8650. res.body = res.body.substr(offset, length);
  8651. } else {
  8652. std::string data;
  8653. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  8654. res.body.size(), data);
  8655. res.body.swap(data);
  8656. }
  8657. if (type != detail::EncodingType::None) {
  8658. output_pre_compression_log(req, res);
  8659. std::unique_ptr<detail::compressor> compressor;
  8660. std::string content_encoding;
  8661. if (type == detail::EncodingType::Gzip) {
  8662. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8663. compressor = detail::make_unique<detail::gzip_compressor>();
  8664. content_encoding = "gzip";
  8665. #endif
  8666. } else if (type == detail::EncodingType::Brotli) {
  8667. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8668. compressor = detail::make_unique<detail::brotli_compressor>();
  8669. content_encoding = "br";
  8670. #endif
  8671. } else if (type == detail::EncodingType::Zstd) {
  8672. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8673. compressor = detail::make_unique<detail::zstd_compressor>();
  8674. content_encoding = "zstd";
  8675. #endif
  8676. }
  8677. if (compressor) {
  8678. std::string compressed;
  8679. if (compressor->compress(res.body.data(), res.body.size(), true,
  8680. [&](const char *data, size_t data_len) {
  8681. compressed.append(data, data_len);
  8682. return true;
  8683. })) {
  8684. res.body.swap(compressed);
  8685. res.set_header("Content-Encoding", content_encoding);
  8686. res.set_header("Vary", "Accept-Encoding");
  8687. }
  8688. }
  8689. }
  8690. auto length = std::to_string(res.body.size());
  8691. res.set_header("Content-Length", length);
  8692. }
  8693. }
  8694. inline bool Server::dispatch_request_for_content_reader(
  8695. Request &req, Response &res, ContentReader content_reader,
  8696. const HandlersForContentReader &handlers) const {
  8697. for (const auto &x : handlers) {
  8698. const auto &matcher = x.first;
  8699. const auto &handler = x.second;
  8700. if (matcher->match(req)) {
  8701. req.matched_route = matcher->pattern();
  8702. if (!pre_request_handler_ ||
  8703. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8704. handler(req, res, content_reader);
  8705. }
  8706. return true;
  8707. }
  8708. }
  8709. return false;
  8710. }
  8711. inline std::string
  8712. get_client_ip(const std::string &x_forwarded_for,
  8713. const std::vector<std::string> &trusted_proxies) {
  8714. // X-Forwarded-For is a comma-separated list per RFC 7239
  8715. std::vector<std::string> ip_list;
  8716. detail::split(x_forwarded_for.data(),
  8717. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  8718. [&](const char *b, const char *e) {
  8719. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  8720. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  8721. });
  8722. for (size_t i = 0; i < ip_list.size(); ++i) {
  8723. auto ip = ip_list[i];
  8724. auto is_trusted_proxy =
  8725. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  8726. [&](const std::string &proxy) { return ip == proxy; });
  8727. if (is_trusted_proxy) {
  8728. if (i == 0) {
  8729. // If the trusted proxy is the first IP, there's no preceding client IP
  8730. return ip;
  8731. } else {
  8732. // Return the IP immediately before the trusted proxy
  8733. return ip_list[i - 1];
  8734. }
  8735. }
  8736. }
  8737. // If no trusted proxy is found, return the first IP in the list
  8738. return ip_list.front();
  8739. }
  8740. inline bool
  8741. Server::process_request(Stream &strm, const std::string &remote_addr,
  8742. int remote_port, const std::string &local_addr,
  8743. int local_port, bool close_connection,
  8744. bool &connection_closed,
  8745. const std::function<void(Request &)> &setup_request) {
  8746. std::array<char, 2048> buf{};
  8747. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8748. // Connection has been closed on client
  8749. if (!line_reader.getline()) { return false; }
  8750. Request req;
  8751. req.start_time_ = std::chrono::steady_clock::now();
  8752. req.remote_addr = remote_addr;
  8753. req.remote_port = remote_port;
  8754. req.local_addr = local_addr;
  8755. req.local_port = local_port;
  8756. Response res;
  8757. res.version = "HTTP/1.1";
  8758. res.headers = default_headers_;
  8759. #ifdef __APPLE__
  8760. // Socket file descriptor exceeded FD_SETSIZE...
  8761. if (strm.socket() >= FD_SETSIZE) {
  8762. Headers dummy;
  8763. detail::read_headers(strm, dummy);
  8764. res.status = StatusCode::InternalServerError_500;
  8765. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  8766. return write_response(strm, close_connection, req, res);
  8767. }
  8768. #endif
  8769. // Request line and headers
  8770. if (!parse_request_line(line_reader.ptr(), req)) {
  8771. res.status = StatusCode::BadRequest_400;
  8772. output_error_log(Error::InvalidRequestLine, &req);
  8773. return write_response(strm, close_connection, req, res);
  8774. }
  8775. // Request headers
  8776. if (!detail::read_headers(strm, req.headers)) {
  8777. res.status = StatusCode::BadRequest_400;
  8778. output_error_log(Error::InvalidHeaders, &req);
  8779. return write_response(strm, close_connection, req, res);
  8780. }
  8781. // Check if the request URI doesn't exceed the limit
  8782. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  8783. res.status = StatusCode::UriTooLong_414;
  8784. output_error_log(Error::ExceedUriMaxLength, &req);
  8785. return write_response(strm, close_connection, req, res);
  8786. }
  8787. if (req.get_header_value("Connection") == "close") {
  8788. connection_closed = true;
  8789. }
  8790. if (req.version == "HTTP/1.0" &&
  8791. req.get_header_value("Connection") != "Keep-Alive") {
  8792. connection_closed = true;
  8793. }
  8794. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  8795. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  8796. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  8797. } else {
  8798. req.remote_addr = remote_addr;
  8799. }
  8800. req.remote_port = remote_port;
  8801. req.local_addr = local_addr;
  8802. req.local_port = local_port;
  8803. if (req.has_header("Accept")) {
  8804. const auto &accept_header = req.get_header_value("Accept");
  8805. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  8806. res.status = StatusCode::BadRequest_400;
  8807. output_error_log(Error::HTTPParsing, &req);
  8808. return write_response(strm, close_connection, req, res);
  8809. }
  8810. }
  8811. if (req.has_header("Range")) {
  8812. const auto &range_header_value = req.get_header_value("Range");
  8813. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  8814. res.status = StatusCode::RangeNotSatisfiable_416;
  8815. output_error_log(Error::InvalidRangeHeader, &req);
  8816. return write_response(strm, close_connection, req, res);
  8817. }
  8818. }
  8819. if (setup_request) { setup_request(req); }
  8820. if (req.get_header_value("Expect") == "100-continue") {
  8821. int status = StatusCode::Continue_100;
  8822. if (expect_100_continue_handler_) {
  8823. status = expect_100_continue_handler_(req, res);
  8824. }
  8825. switch (status) {
  8826. case StatusCode::Continue_100:
  8827. case StatusCode::ExpectationFailed_417:
  8828. detail::write_response_line(strm, status);
  8829. strm.write("\r\n");
  8830. break;
  8831. default:
  8832. connection_closed = true;
  8833. return write_response(strm, true, req, res);
  8834. }
  8835. }
  8836. // Setup `is_connection_closed` method
  8837. auto sock = strm.socket();
  8838. req.is_connection_closed = [sock]() {
  8839. return !detail::is_socket_alive(sock);
  8840. };
  8841. // Routing
  8842. auto routed = false;
  8843. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8844. routed = routing(req, res, strm);
  8845. #else
  8846. try {
  8847. routed = routing(req, res, strm);
  8848. } catch (std::exception &e) {
  8849. if (exception_handler_) {
  8850. auto ep = std::current_exception();
  8851. exception_handler_(req, res, ep);
  8852. routed = true;
  8853. } else {
  8854. res.status = StatusCode::InternalServerError_500;
  8855. std::string val;
  8856. auto s = e.what();
  8857. for (size_t i = 0; s[i]; i++) {
  8858. switch (s[i]) {
  8859. case '\r': val += "\\r"; break;
  8860. case '\n': val += "\\n"; break;
  8861. default: val += s[i]; break;
  8862. }
  8863. }
  8864. res.set_header("EXCEPTION_WHAT", val);
  8865. }
  8866. } catch (...) {
  8867. if (exception_handler_) {
  8868. auto ep = std::current_exception();
  8869. exception_handler_(req, res, ep);
  8870. routed = true;
  8871. } else {
  8872. res.status = StatusCode::InternalServerError_500;
  8873. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  8874. }
  8875. }
  8876. #endif
  8877. if (routed) {
  8878. if (res.status == -1) {
  8879. res.status = req.ranges.empty() ? StatusCode::OK_200
  8880. : StatusCode::PartialContent_206;
  8881. }
  8882. // Serve file content by using a content provider
  8883. if (!res.file_content_path_.empty()) {
  8884. const auto &path = res.file_content_path_;
  8885. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8886. if (!mm->is_open()) {
  8887. res.body.clear();
  8888. res.content_length_ = 0;
  8889. res.content_provider_ = nullptr;
  8890. res.status = StatusCode::NotFound_404;
  8891. output_error_log(Error::OpenFile, &req);
  8892. return write_response(strm, close_connection, req, res);
  8893. }
  8894. auto content_type = res.file_content_content_type_;
  8895. if (content_type.empty()) {
  8896. content_type = detail::find_content_type(
  8897. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  8898. }
  8899. res.set_content_provider(
  8900. mm->size(), content_type,
  8901. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8902. sink.write(mm->data() + offset, length);
  8903. return true;
  8904. });
  8905. }
  8906. if (detail::range_error(req, res)) {
  8907. res.body.clear();
  8908. res.content_length_ = 0;
  8909. res.content_provider_ = nullptr;
  8910. res.status = StatusCode::RangeNotSatisfiable_416;
  8911. return write_response(strm, close_connection, req, res);
  8912. }
  8913. return write_response_with_content(strm, close_connection, req, res);
  8914. } else {
  8915. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  8916. return write_response(strm, close_connection, req, res);
  8917. }
  8918. }
  8919. inline bool Server::is_valid() const { return true; }
  8920. inline bool Server::process_and_close_socket(socket_t sock) {
  8921. std::string remote_addr;
  8922. int remote_port = 0;
  8923. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8924. std::string local_addr;
  8925. int local_port = 0;
  8926. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8927. auto ret = detail::process_server_socket(
  8928. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8929. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8930. write_timeout_usec_,
  8931. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8932. return process_request(strm, remote_addr, remote_port, local_addr,
  8933. local_port, close_connection, connection_closed,
  8934. nullptr);
  8935. });
  8936. detail::shutdown_socket(sock);
  8937. detail::close_socket(sock);
  8938. return ret;
  8939. }
  8940. inline void Server::output_log(const Request &req, const Response &res) const {
  8941. if (logger_) {
  8942. std::lock_guard<std::mutex> guard(logger_mutex_);
  8943. logger_(req, res);
  8944. }
  8945. }
  8946. inline void Server::output_pre_compression_log(const Request &req,
  8947. const Response &res) const {
  8948. if (pre_compression_logger_) {
  8949. std::lock_guard<std::mutex> guard(logger_mutex_);
  8950. pre_compression_logger_(req, res);
  8951. }
  8952. }
  8953. inline void Server::output_error_log(const Error &err,
  8954. const Request *req) const {
  8955. if (error_logger_) {
  8956. std::lock_guard<std::mutex> guard(logger_mutex_);
  8957. error_logger_(err, req);
  8958. }
  8959. }
  8960. /*
  8961. * Group 5: ClientImpl and Client (Universal) implementation
  8962. */
  8963. // HTTP client implementation
  8964. inline ClientImpl::ClientImpl(const std::string &host)
  8965. : ClientImpl(host, 80, std::string(), std::string()) {}
  8966. inline ClientImpl::ClientImpl(const std::string &host, int port)
  8967. : ClientImpl(host, port, std::string(), std::string()) {}
  8968. inline ClientImpl::ClientImpl(const std::string &host, int port,
  8969. const std::string &client_cert_path,
  8970. const std::string &client_key_path)
  8971. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  8972. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  8973. inline ClientImpl::~ClientImpl() {
  8974. // Wait until all the requests in flight are handled.
  8975. size_t retry_count = 10;
  8976. while (retry_count-- > 0) {
  8977. {
  8978. std::lock_guard<std::mutex> guard(socket_mutex_);
  8979. if (socket_requests_in_flight_ == 0) { break; }
  8980. }
  8981. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  8982. }
  8983. std::lock_guard<std::mutex> guard(socket_mutex_);
  8984. shutdown_socket(socket_);
  8985. close_socket(socket_);
  8986. }
  8987. inline bool ClientImpl::is_valid() const { return true; }
  8988. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  8989. client_cert_path_ = rhs.client_cert_path_;
  8990. client_key_path_ = rhs.client_key_path_;
  8991. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  8992. read_timeout_sec_ = rhs.read_timeout_sec_;
  8993. read_timeout_usec_ = rhs.read_timeout_usec_;
  8994. write_timeout_sec_ = rhs.write_timeout_sec_;
  8995. write_timeout_usec_ = rhs.write_timeout_usec_;
  8996. max_timeout_msec_ = rhs.max_timeout_msec_;
  8997. basic_auth_username_ = rhs.basic_auth_username_;
  8998. basic_auth_password_ = rhs.basic_auth_password_;
  8999. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  9000. keep_alive_ = rhs.keep_alive_;
  9001. follow_location_ = rhs.follow_location_;
  9002. path_encode_ = rhs.path_encode_;
  9003. address_family_ = rhs.address_family_;
  9004. tcp_nodelay_ = rhs.tcp_nodelay_;
  9005. ipv6_v6only_ = rhs.ipv6_v6only_;
  9006. socket_options_ = rhs.socket_options_;
  9007. compress_ = rhs.compress_;
  9008. decompress_ = rhs.decompress_;
  9009. payload_max_length_ = rhs.payload_max_length_;
  9010. has_payload_max_length_ = rhs.has_payload_max_length_;
  9011. interface_ = rhs.interface_;
  9012. proxy_host_ = rhs.proxy_host_;
  9013. proxy_port_ = rhs.proxy_port_;
  9014. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  9015. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  9016. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  9017. logger_ = rhs.logger_;
  9018. error_logger_ = rhs.error_logger_;
  9019. #ifdef CPPHTTPLIB_SSL_ENABLED
  9020. digest_auth_username_ = rhs.digest_auth_username_;
  9021. digest_auth_password_ = rhs.digest_auth_password_;
  9022. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  9023. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  9024. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  9025. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  9026. server_certificate_verification_ = rhs.server_certificate_verification_;
  9027. server_hostname_verification_ = rhs.server_hostname_verification_;
  9028. #endif
  9029. }
  9030. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  9031. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9032. return detail::create_client_socket(
  9033. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  9034. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  9035. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  9036. write_timeout_sec_, write_timeout_usec_, interface_, error);
  9037. }
  9038. // Check is custom IP specified for host_
  9039. std::string ip;
  9040. auto it = addr_map_.find(host_);
  9041. if (it != addr_map_.end()) { ip = it->second; }
  9042. return detail::create_client_socket(
  9043. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  9044. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  9045. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9046. write_timeout_usec_, interface_, error);
  9047. }
  9048. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  9049. Error &error) {
  9050. auto sock = create_client_socket(error);
  9051. if (sock == INVALID_SOCKET) { return false; }
  9052. socket.sock = sock;
  9053. return true;
  9054. }
  9055. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  9056. return create_and_connect_socket(socket, error);
  9057. }
  9058. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  9059. bool /*shutdown_gracefully*/) {
  9060. // If there are any requests in flight from threads other than us, then it's
  9061. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  9062. assert(socket_requests_in_flight_ == 0 ||
  9063. socket_requests_are_from_thread_ == std::this_thread::get_id());
  9064. }
  9065. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  9066. if (socket.sock == INVALID_SOCKET) { return; }
  9067. detail::shutdown_socket(socket.sock);
  9068. }
  9069. inline void ClientImpl::close_socket(Socket &socket) {
  9070. // If there are requests in flight in another thread, usually closing
  9071. // the socket will be fine and they will simply receive an error when
  9072. // using the closed socket, but it is still a bug since rarely the OS
  9073. // may reassign the socket id to be used for a new socket, and then
  9074. // suddenly they will be operating on a live socket that is different
  9075. // than the one they intended!
  9076. assert(socket_requests_in_flight_ == 0 ||
  9077. socket_requests_are_from_thread_ == std::this_thread::get_id());
  9078. // It is also a bug if this happens while SSL is still active
  9079. #ifdef CPPHTTPLIB_SSL_ENABLED
  9080. assert(socket.ssl == nullptr);
  9081. #endif
  9082. if (socket.sock == INVALID_SOCKET) { return; }
  9083. detail::close_socket(socket.sock);
  9084. socket.sock = INVALID_SOCKET;
  9085. }
  9086. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  9087. Response &res,
  9088. bool skip_100_continue) const {
  9089. std::array<char, 2048> buf{};
  9090. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  9091. if (!line_reader.getline()) { return false; }
  9092. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  9093. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  9094. #else
  9095. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  9096. #endif
  9097. std::cmatch m;
  9098. if (!std::regex_match(line_reader.ptr(), m, re)) {
  9099. return req.method == "CONNECT";
  9100. }
  9101. res.version = std::string(m[1]);
  9102. res.status = std::stoi(std::string(m[2]));
  9103. res.reason = std::string(m[3]);
  9104. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  9105. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  9106. if (!line_reader.getline()) { return false; } // CRLF
  9107. if (!line_reader.getline()) { return false; } // next response line
  9108. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  9109. res.version = std::string(m[1]);
  9110. res.status = std::stoi(std::string(m[2]));
  9111. res.reason = std::string(m[3]);
  9112. }
  9113. return true;
  9114. }
  9115. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  9116. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  9117. auto ret = send_(req, res, error);
  9118. if (error == Error::SSLPeerCouldBeClosed_) {
  9119. assert(!ret);
  9120. ret = send_(req, res, error);
  9121. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  9122. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  9123. }
  9124. return ret;
  9125. }
  9126. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  9127. {
  9128. std::lock_guard<std::mutex> guard(socket_mutex_);
  9129. // Set this to false immediately - if it ever gets set to true by the end
  9130. // of the request, we know another thread instructed us to close the
  9131. // socket.
  9132. socket_should_be_closed_when_request_is_done_ = false;
  9133. auto is_alive = false;
  9134. if (socket_.is_open()) {
  9135. is_alive = detail::is_socket_alive(socket_.sock);
  9136. #ifdef CPPHTTPLIB_SSL_ENABLED
  9137. if (is_alive && is_ssl()) {
  9138. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  9139. is_alive = false;
  9140. }
  9141. }
  9142. #endif
  9143. if (!is_alive) {
  9144. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  9145. // seems like the other side has already closed the connection Also,
  9146. // there cannot be any requests in flight from other threads since we
  9147. // locked request_mutex_, so safe to close everything immediately
  9148. const bool shutdown_gracefully = false;
  9149. shutdown_ssl(socket_, shutdown_gracefully);
  9150. shutdown_socket(socket_);
  9151. close_socket(socket_);
  9152. }
  9153. }
  9154. if (!is_alive) {
  9155. if (!ensure_socket_connection(socket_, error)) {
  9156. output_error_log(error, &req);
  9157. return false;
  9158. }
  9159. #ifdef CPPHTTPLIB_SSL_ENABLED
  9160. // TODO: refactoring
  9161. if (is_ssl()) {
  9162. auto &scli = static_cast<SSLClient &>(*this);
  9163. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9164. auto success = false;
  9165. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  9166. error)) {
  9167. if (!success) { output_error_log(error, &req); }
  9168. return success;
  9169. }
  9170. }
  9171. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9172. if (!scli.initialize_ssl(socket_, error)) {
  9173. output_error_log(error, &req);
  9174. return false;
  9175. }
  9176. }
  9177. }
  9178. #endif
  9179. }
  9180. // Mark the current socket as being in use so that it cannot be closed by
  9181. // anyone else while this request is ongoing, even though we will be
  9182. // releasing the mutex.
  9183. if (socket_requests_in_flight_ > 1) {
  9184. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  9185. }
  9186. socket_requests_in_flight_ += 1;
  9187. socket_requests_are_from_thread_ = std::this_thread::get_id();
  9188. }
  9189. for (const auto &header : default_headers_) {
  9190. if (req.headers.find(header.first) == req.headers.end()) {
  9191. req.headers.insert(header);
  9192. }
  9193. }
  9194. auto ret = false;
  9195. auto close_connection = !keep_alive_;
  9196. auto se = detail::scope_exit([&]() {
  9197. // Briefly lock mutex in order to mark that a request is no longer ongoing
  9198. std::lock_guard<std::mutex> guard(socket_mutex_);
  9199. socket_requests_in_flight_ -= 1;
  9200. if (socket_requests_in_flight_ <= 0) {
  9201. assert(socket_requests_in_flight_ == 0);
  9202. socket_requests_are_from_thread_ = std::thread::id();
  9203. }
  9204. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  9205. !ret) {
  9206. shutdown_ssl(socket_, true);
  9207. shutdown_socket(socket_);
  9208. close_socket(socket_);
  9209. }
  9210. });
  9211. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  9212. return handle_request(strm, req, res, close_connection, error);
  9213. });
  9214. if (!ret) {
  9215. if (error == Error::Success) {
  9216. error = Error::Unknown;
  9217. output_error_log(error, &req);
  9218. }
  9219. }
  9220. return ret;
  9221. }
  9222. inline Result ClientImpl::send(const Request &req) {
  9223. auto req2 = req;
  9224. return send_(std::move(req2));
  9225. }
  9226. inline Result ClientImpl::send_(Request &&req) {
  9227. auto res = detail::make_unique<Response>();
  9228. auto error = Error::Success;
  9229. auto ret = send(req, *res, error);
  9230. #ifdef CPPHTTPLIB_SSL_ENABLED
  9231. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  9232. last_ssl_error_, last_backend_error_};
  9233. #else
  9234. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  9235. #endif
  9236. }
  9237. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  9238. const std::string &ct) {
  9239. (void)for_stream;
  9240. for (const auto &header : default_headers_) {
  9241. if (!r.has_header(header.first)) { r.headers.insert(header); }
  9242. }
  9243. if (!r.has_header("Host")) {
  9244. if (address_family_ == AF_UNIX) {
  9245. r.headers.emplace("Host", "localhost");
  9246. } else {
  9247. r.headers.emplace(
  9248. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  9249. }
  9250. }
  9251. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  9252. if (!r.content_receiver) {
  9253. if (!r.has_header("Accept-Encoding")) {
  9254. std::string accept_encoding;
  9255. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9256. accept_encoding = "br";
  9257. #endif
  9258. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9259. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  9260. accept_encoding += "gzip, deflate";
  9261. #endif
  9262. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9263. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  9264. accept_encoding += "zstd";
  9265. #endif
  9266. r.set_header("Accept-Encoding", accept_encoding);
  9267. }
  9268. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  9269. if (!r.has_header("User-Agent")) {
  9270. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  9271. r.set_header("User-Agent", agent);
  9272. }
  9273. #endif
  9274. }
  9275. if (!r.body.empty()) {
  9276. if (!ct.empty() && !r.has_header("Content-Type")) {
  9277. r.headers.emplace("Content-Type", ct);
  9278. }
  9279. if (!r.has_header("Content-Length")) {
  9280. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  9281. }
  9282. }
  9283. }
  9284. inline ClientImpl::StreamHandle
  9285. ClientImpl::open_stream(const std::string &method, const std::string &path,
  9286. const Params &params, const Headers &headers,
  9287. const std::string &body,
  9288. const std::string &content_type) {
  9289. StreamHandle handle;
  9290. handle.response = detail::make_unique<Response>();
  9291. handle.error = Error::Success;
  9292. auto query_path = params.empty() ? path : append_query_params(path, params);
  9293. handle.connection_ = detail::make_unique<ClientConnection>();
  9294. {
  9295. std::lock_guard<std::mutex> guard(socket_mutex_);
  9296. auto is_alive = false;
  9297. if (socket_.is_open()) {
  9298. is_alive = detail::is_socket_alive(socket_.sock);
  9299. #ifdef CPPHTTPLIB_SSL_ENABLED
  9300. if (is_alive && is_ssl()) {
  9301. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  9302. is_alive = false;
  9303. }
  9304. }
  9305. #endif
  9306. if (!is_alive) {
  9307. shutdown_ssl(socket_, false);
  9308. shutdown_socket(socket_);
  9309. close_socket(socket_);
  9310. }
  9311. }
  9312. if (!is_alive) {
  9313. if (!ensure_socket_connection(socket_, handle.error)) {
  9314. handle.response.reset();
  9315. return handle;
  9316. }
  9317. #ifdef CPPHTTPLIB_SSL_ENABLED
  9318. if (is_ssl()) {
  9319. auto &scli = static_cast<SSLClient &>(*this);
  9320. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9321. if (!scli.initialize_ssl(socket_, handle.error)) {
  9322. handle.response.reset();
  9323. return handle;
  9324. }
  9325. }
  9326. }
  9327. #endif
  9328. }
  9329. transfer_socket_ownership_to_handle(handle);
  9330. }
  9331. #ifdef CPPHTTPLIB_SSL_ENABLED
  9332. if (is_ssl() && handle.connection_->session) {
  9333. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  9334. handle.connection_->sock, handle.connection_->session,
  9335. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9336. write_timeout_usec_);
  9337. } else {
  9338. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  9339. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  9340. write_timeout_sec_, write_timeout_usec_);
  9341. }
  9342. #else
  9343. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  9344. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  9345. write_timeout_sec_, write_timeout_usec_);
  9346. #endif
  9347. handle.stream_ = handle.socket_stream_.get();
  9348. Request req;
  9349. req.method = method;
  9350. req.path = query_path;
  9351. req.headers = headers;
  9352. req.body = body;
  9353. prepare_default_headers(req, true, content_type);
  9354. auto &strm = *handle.stream_;
  9355. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  9356. handle.error = Error::Write;
  9357. handle.response.reset();
  9358. return handle;
  9359. }
  9360. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  9361. handle.error)) {
  9362. handle.response.reset();
  9363. return handle;
  9364. }
  9365. if (!body.empty()) {
  9366. if (strm.write(body.data(), body.size()) < 0) {
  9367. handle.error = Error::Write;
  9368. handle.response.reset();
  9369. return handle;
  9370. }
  9371. }
  9372. if (!read_response_line(strm, req, *handle.response) ||
  9373. !detail::read_headers(strm, handle.response->headers)) {
  9374. handle.error = Error::Read;
  9375. handle.response.reset();
  9376. return handle;
  9377. }
  9378. handle.body_reader_.stream = handle.stream_;
  9379. handle.body_reader_.payload_max_length = payload_max_length_;
  9380. auto content_length_str = handle.response->get_header_value("Content-Length");
  9381. if (!content_length_str.empty()) {
  9382. handle.body_reader_.has_content_length = true;
  9383. handle.body_reader_.content_length =
  9384. static_cast<size_t>(std::stoull(content_length_str));
  9385. }
  9386. auto transfer_encoding =
  9387. handle.response->get_header_value("Transfer-Encoding");
  9388. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  9389. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  9390. if (!content_encoding.empty()) {
  9391. handle.decompressor_ = detail::create_decompressor(content_encoding);
  9392. }
  9393. return handle;
  9394. }
  9395. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  9396. if (!is_valid() || !response) { return -1; }
  9397. if (decompressor_) { return read_with_decompression(buf, len); }
  9398. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  9399. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  9400. trailers_parsed_ = true;
  9401. if (body_reader_.chunked_decoder) {
  9402. if (!body_reader_.chunked_decoder->parse_trailers_into(
  9403. response->trailers, response->headers)) {
  9404. return n;
  9405. }
  9406. } else {
  9407. detail::ChunkedDecoder dec(*stream_);
  9408. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  9409. return n;
  9410. }
  9411. }
  9412. }
  9413. return n;
  9414. }
  9415. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  9416. size_t len) {
  9417. if (decompress_offset_ < decompress_buffer_.size()) {
  9418. auto available = decompress_buffer_.size() - decompress_offset_;
  9419. auto to_copy = (std::min)(len, available);
  9420. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  9421. decompress_offset_ += to_copy;
  9422. decompressed_bytes_read_ += to_copy;
  9423. return static_cast<ssize_t>(to_copy);
  9424. }
  9425. decompress_buffer_.clear();
  9426. decompress_offset_ = 0;
  9427. constexpr size_t kDecompressionBufferSize = 8192;
  9428. char compressed_buf[kDecompressionBufferSize];
  9429. while (true) {
  9430. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  9431. sizeof(compressed_buf));
  9432. if (n <= 0) { return n; }
  9433. bool decompress_ok = decompressor_->decompress(
  9434. compressed_buf, static_cast<size_t>(n),
  9435. [this](const char *data, size_t data_len) {
  9436. decompress_buffer_.append(data, data_len);
  9437. auto limit = body_reader_.payload_max_length;
  9438. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  9439. return false;
  9440. }
  9441. return true;
  9442. });
  9443. if (!decompress_ok) {
  9444. body_reader_.last_error = Error::Read;
  9445. return -1;
  9446. }
  9447. if (!decompress_buffer_.empty()) { break; }
  9448. }
  9449. auto to_copy = (std::min)(len, decompress_buffer_.size());
  9450. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  9451. decompress_offset_ = to_copy;
  9452. decompressed_bytes_read_ += to_copy;
  9453. return static_cast<ssize_t>(to_copy);
  9454. }
  9455. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  9456. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  9457. return;
  9458. }
  9459. trailers_parsed_ = true;
  9460. const auto bufsiz = 128;
  9461. char line_buf[bufsiz];
  9462. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  9463. if (!line_reader.getline()) { return; }
  9464. if (!detail::parse_trailers(line_reader, response->trailers,
  9465. response->headers)) {
  9466. return;
  9467. }
  9468. }
  9469. namespace detail {
  9470. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  9471. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  9472. size_t &out_chunk_offset,
  9473. size_t &out_chunk_total) {
  9474. if (finished) { return 0; }
  9475. if (chunk_remaining == 0) {
  9476. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9477. if (!lr.getline()) { return -1; }
  9478. char *endptr = nullptr;
  9479. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  9480. if (endptr == lr.ptr()) { return -1; }
  9481. if (chunk_len == ULONG_MAX) { return -1; }
  9482. if (chunk_len == 0) {
  9483. chunk_remaining = 0;
  9484. finished = true;
  9485. out_chunk_offset = 0;
  9486. out_chunk_total = 0;
  9487. return 0;
  9488. }
  9489. chunk_remaining = static_cast<size_t>(chunk_len);
  9490. last_chunk_total = chunk_remaining;
  9491. last_chunk_offset = 0;
  9492. }
  9493. auto to_read = (std::min)(chunk_remaining, len);
  9494. auto n = strm.read(buf, to_read);
  9495. if (n <= 0) { return -1; }
  9496. auto offset_before = last_chunk_offset;
  9497. last_chunk_offset += static_cast<size_t>(n);
  9498. chunk_remaining -= static_cast<size_t>(n);
  9499. out_chunk_offset = offset_before;
  9500. out_chunk_total = last_chunk_total;
  9501. if (chunk_remaining == 0) {
  9502. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9503. if (!lr.getline()) { return -1; }
  9504. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  9505. }
  9506. return n;
  9507. }
  9508. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  9509. const Headers &src_headers) {
  9510. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9511. if (!lr.getline()) { return false; }
  9512. return parse_trailers(lr, dest, src_headers);
  9513. }
  9514. } // namespace detail
  9515. inline void
  9516. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  9517. handle.connection_->sock = socket_.sock;
  9518. #ifdef CPPHTTPLIB_SSL_ENABLED
  9519. handle.connection_->session = socket_.ssl;
  9520. socket_.ssl = nullptr;
  9521. #endif
  9522. socket_.sock = INVALID_SOCKET;
  9523. }
  9524. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  9525. Response &res, bool close_connection,
  9526. Error &error) {
  9527. if (req.path.empty()) {
  9528. error = Error::Connection;
  9529. output_error_log(error, &req);
  9530. return false;
  9531. }
  9532. auto req_save = req;
  9533. bool ret;
  9534. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  9535. auto req2 = req;
  9536. req2.path = "http://" +
  9537. detail::make_host_and_port_string(host_, port_, false) +
  9538. req.path;
  9539. ret = process_request(strm, req2, res, close_connection, error);
  9540. req = std::move(req2);
  9541. req.path = req_save.path;
  9542. } else {
  9543. ret = process_request(strm, req, res, close_connection, error);
  9544. }
  9545. if (!ret) { return false; }
  9546. if (res.get_header_value("Connection") == "close" ||
  9547. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  9548. // TODO this requires a not-entirely-obvious chain of calls to be correct
  9549. // for this to be safe.
  9550. // This is safe to call because handle_request is only called by send_
  9551. // which locks the request mutex during the process. It would be a bug
  9552. // to call it from a different thread since it's a thread-safety issue
  9553. // to do these things to the socket if another thread is using the socket.
  9554. std::lock_guard<std::mutex> guard(socket_mutex_);
  9555. shutdown_ssl(socket_, true);
  9556. shutdown_socket(socket_);
  9557. close_socket(socket_);
  9558. }
  9559. if (300 < res.status && res.status < 400 && follow_location_) {
  9560. req = std::move(req_save);
  9561. ret = redirect(req, res, error);
  9562. }
  9563. #ifdef CPPHTTPLIB_SSL_ENABLED
  9564. if ((res.status == StatusCode::Unauthorized_401 ||
  9565. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  9566. req.authorization_count_ < 5) {
  9567. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  9568. const auto &username =
  9569. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  9570. const auto &password =
  9571. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  9572. if (!username.empty() && !password.empty()) {
  9573. std::map<std::string, std::string> auth;
  9574. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  9575. Request new_req = req;
  9576. new_req.authorization_count_ += 1;
  9577. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  9578. : "Authorization");
  9579. new_req.headers.insert(detail::make_digest_authentication_header(
  9580. req, auth, new_req.authorization_count_, detail::random_string(10),
  9581. username, password, is_proxy));
  9582. Response new_res;
  9583. ret = send(new_req, new_res, error);
  9584. if (ret) { res = std::move(new_res); }
  9585. }
  9586. }
  9587. }
  9588. #endif
  9589. return ret;
  9590. }
  9591. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  9592. if (req.redirect_count_ == 0) {
  9593. error = Error::ExceedRedirectCount;
  9594. output_error_log(error, &req);
  9595. return false;
  9596. }
  9597. auto location = res.get_header_value("location");
  9598. if (location.empty()) { return false; }
  9599. thread_local const std::regex re(
  9600. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  9601. std::smatch m;
  9602. if (!std::regex_match(location, m, re)) { return false; }
  9603. auto scheme = is_ssl() ? "https" : "http";
  9604. auto next_scheme = m[1].str();
  9605. auto next_host = m[2].str();
  9606. if (next_host.empty()) { next_host = m[3].str(); }
  9607. auto port_str = m[4].str();
  9608. auto next_path = m[5].str();
  9609. auto next_query = m[6].str();
  9610. auto next_port = port_;
  9611. if (!port_str.empty()) {
  9612. next_port = std::stoi(port_str);
  9613. } else if (!next_scheme.empty()) {
  9614. next_port = next_scheme == "https" ? 443 : 80;
  9615. }
  9616. if (next_scheme.empty()) { next_scheme = scheme; }
  9617. if (next_host.empty()) { next_host = host_; }
  9618. if (next_path.empty()) { next_path = "/"; }
  9619. auto path = decode_query_component(next_path, true) + next_query;
  9620. // Same host redirect - use current client
  9621. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  9622. return detail::redirect(*this, req, res, path, location, error);
  9623. }
  9624. // Cross-host/scheme redirect - create new client with robust setup
  9625. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  9626. path, location, error);
  9627. }
  9628. // New method for robust redirect client creation
  9629. inline bool ClientImpl::create_redirect_client(
  9630. const std::string &scheme, const std::string &host, int port, Request &req,
  9631. Response &res, const std::string &path, const std::string &location,
  9632. Error &error) {
  9633. // Determine if we need SSL
  9634. auto need_ssl = (scheme == "https");
  9635. // Clean up request headers that are host/client specific
  9636. // Remove headers that should not be carried over to new host
  9637. auto headers_to_remove =
  9638. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  9639. for (const auto &header_name : headers_to_remove) {
  9640. auto it = req.headers.find(header_name);
  9641. while (it != req.headers.end()) {
  9642. it = req.headers.erase(it);
  9643. it = req.headers.find(header_name);
  9644. }
  9645. }
  9646. // Create appropriate client type and handle redirect
  9647. if (need_ssl) {
  9648. #ifdef CPPHTTPLIB_SSL_ENABLED
  9649. // Create SSL client for HTTPS redirect
  9650. SSLClient redirect_client(host, port);
  9651. // Setup basic client configuration first
  9652. setup_redirect_client(redirect_client);
  9653. // SSL-specific configuration for proxy environments
  9654. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9655. // Critical: Disable SSL verification for proxy environments
  9656. redirect_client.enable_server_certificate_verification(false);
  9657. redirect_client.enable_server_hostname_verification(false);
  9658. } else {
  9659. // For direct SSL connections, copy SSL verification settings
  9660. redirect_client.enable_server_certificate_verification(
  9661. server_certificate_verification_);
  9662. redirect_client.enable_server_hostname_verification(
  9663. server_hostname_verification_);
  9664. }
  9665. // Transfer CA certificate to redirect client
  9666. if (!ca_cert_pem_.empty()) {
  9667. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  9668. ca_cert_pem_.size());
  9669. }
  9670. if (!ca_cert_file_path_.empty()) {
  9671. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  9672. }
  9673. // Client certificates are set through constructor for SSLClient
  9674. // NOTE: SSLClient constructor already takes client_cert_path and
  9675. // client_key_path so we need to create it properly if client certs are
  9676. // needed
  9677. // Execute the redirect
  9678. return detail::redirect(redirect_client, req, res, path, location, error);
  9679. #else
  9680. // SSL not supported - set appropriate error
  9681. error = Error::SSLConnection;
  9682. output_error_log(error, &req);
  9683. return false;
  9684. #endif
  9685. } else {
  9686. // HTTP redirect
  9687. ClientImpl redirect_client(host, port);
  9688. // Setup client with robust configuration
  9689. setup_redirect_client(redirect_client);
  9690. // Execute the redirect
  9691. return detail::redirect(redirect_client, req, res, path, location, error);
  9692. }
  9693. }
  9694. // New method for robust client setup (based on basic_manual_redirect.cpp
  9695. // logic)
  9696. template <typename ClientType>
  9697. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  9698. // Copy basic settings first
  9699. client.set_connection_timeout(connection_timeout_sec_);
  9700. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  9701. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  9702. client.set_keep_alive(keep_alive_);
  9703. client.set_follow_location(
  9704. true); // Enable redirects to handle multi-step redirects
  9705. client.set_path_encode(path_encode_);
  9706. client.set_compress(compress_);
  9707. client.set_decompress(decompress_);
  9708. // Copy authentication settings BEFORE proxy setup
  9709. if (!basic_auth_username_.empty()) {
  9710. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  9711. }
  9712. if (!bearer_token_auth_token_.empty()) {
  9713. client.set_bearer_token_auth(bearer_token_auth_token_);
  9714. }
  9715. #ifdef CPPHTTPLIB_SSL_ENABLED
  9716. if (!digest_auth_username_.empty()) {
  9717. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  9718. }
  9719. #endif
  9720. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  9721. // before proxy auth)
  9722. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9723. // First set proxy host and port
  9724. client.set_proxy(proxy_host_, proxy_port_);
  9725. // Then set proxy authentication (order matters!)
  9726. if (!proxy_basic_auth_username_.empty()) {
  9727. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  9728. proxy_basic_auth_password_);
  9729. }
  9730. if (!proxy_bearer_token_auth_token_.empty()) {
  9731. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  9732. }
  9733. #ifdef CPPHTTPLIB_SSL_ENABLED
  9734. if (!proxy_digest_auth_username_.empty()) {
  9735. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  9736. proxy_digest_auth_password_);
  9737. }
  9738. #endif
  9739. }
  9740. // Copy network and socket settings
  9741. client.set_address_family(address_family_);
  9742. client.set_tcp_nodelay(tcp_nodelay_);
  9743. client.set_ipv6_v6only(ipv6_v6only_);
  9744. if (socket_options_) { client.set_socket_options(socket_options_); }
  9745. if (!interface_.empty()) { client.set_interface(interface_); }
  9746. // Copy logging and headers
  9747. if (logger_) { client.set_logger(logger_); }
  9748. if (error_logger_) { client.set_error_logger(error_logger_); }
  9749. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  9750. // Each new client should generate its own headers based on its target host
  9751. }
  9752. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  9753. const Request &req,
  9754. Error &error) const {
  9755. auto is_shutting_down = []() { return false; };
  9756. if (req.is_chunked_content_provider_) {
  9757. // TODO: Brotli support
  9758. std::unique_ptr<detail::compressor> compressor;
  9759. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9760. if (compress_) {
  9761. compressor = detail::make_unique<detail::gzip_compressor>();
  9762. } else
  9763. #endif
  9764. {
  9765. compressor = detail::make_unique<detail::nocompressor>();
  9766. }
  9767. return detail::write_content_chunked(strm, req.content_provider_,
  9768. is_shutting_down, *compressor, error);
  9769. } else {
  9770. return detail::write_content_with_progress(
  9771. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  9772. req.upload_progress, error);
  9773. }
  9774. }
  9775. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  9776. bool close_connection, Error &error,
  9777. bool skip_body) {
  9778. // Prepare additional headers
  9779. if (close_connection) {
  9780. if (!req.has_header("Connection")) {
  9781. req.set_header("Connection", "close");
  9782. }
  9783. }
  9784. std::string ct_for_defaults;
  9785. if (!req.has_header("Content-Type") && !req.body.empty()) {
  9786. ct_for_defaults = "text/plain";
  9787. }
  9788. prepare_default_headers(req, false, ct_for_defaults);
  9789. if (req.body.empty()) {
  9790. if (req.content_provider_) {
  9791. if (!req.is_chunked_content_provider_) {
  9792. if (!req.has_header("Content-Length")) {
  9793. auto length = std::to_string(req.content_length_);
  9794. req.set_header("Content-Length", length);
  9795. }
  9796. }
  9797. } else {
  9798. if (req.method == "POST" || req.method == "PUT" ||
  9799. req.method == "PATCH") {
  9800. req.set_header("Content-Length", "0");
  9801. }
  9802. }
  9803. }
  9804. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  9805. if (!req.has_header("Authorization")) {
  9806. req.headers.insert(make_basic_authentication_header(
  9807. basic_auth_username_, basic_auth_password_, false));
  9808. }
  9809. }
  9810. if (!proxy_basic_auth_username_.empty() &&
  9811. !proxy_basic_auth_password_.empty()) {
  9812. if (!req.has_header("Proxy-Authorization")) {
  9813. req.headers.insert(make_basic_authentication_header(
  9814. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  9815. }
  9816. }
  9817. if (!bearer_token_auth_token_.empty()) {
  9818. if (!req.has_header("Authorization")) {
  9819. req.headers.insert(make_bearer_token_authentication_header(
  9820. bearer_token_auth_token_, false));
  9821. }
  9822. }
  9823. if (!proxy_bearer_token_auth_token_.empty()) {
  9824. if (!req.has_header("Proxy-Authorization")) {
  9825. req.headers.insert(make_bearer_token_authentication_header(
  9826. proxy_bearer_token_auth_token_, true));
  9827. }
  9828. }
  9829. // Request line and headers
  9830. {
  9831. detail::BufferStream bstrm;
  9832. // Extract path and query from req.path
  9833. std::string path_part, query_part;
  9834. auto query_pos = req.path.find('?');
  9835. if (query_pos != std::string::npos) {
  9836. path_part = req.path.substr(0, query_pos);
  9837. query_part = req.path.substr(query_pos + 1);
  9838. } else {
  9839. path_part = req.path;
  9840. query_part = "";
  9841. }
  9842. // Encode path part. If the original `req.path` already contained a
  9843. // query component, preserve its raw query string (including parameter
  9844. // order) instead of reparsing and reassembling it which may reorder
  9845. // parameters due to container ordering (e.g. `Params` uses
  9846. // `std::multimap`). When there is no query in `req.path`, fall back to
  9847. // building a query from `req.params` so existing callers that pass
  9848. // `Params` continue to work.
  9849. auto path_with_query =
  9850. path_encode_ ? detail::encode_path(path_part) : path_part;
  9851. if (!query_part.empty()) {
  9852. // Normalize the query string (decode then re-encode) while preserving
  9853. // the original parameter order.
  9854. auto normalized = detail::normalize_query_string(query_part);
  9855. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  9856. // Still populate req.params for handlers/users who read them.
  9857. detail::parse_query_text(query_part, req.params);
  9858. } else {
  9859. // No query in path; parse any query_part (empty) and append params
  9860. // from `req.params` when present (preserves prior behavior for
  9861. // callers who provide Params separately).
  9862. detail::parse_query_text(query_part, req.params);
  9863. if (!req.params.empty()) {
  9864. path_with_query = append_query_params(path_with_query, req.params);
  9865. }
  9866. }
  9867. // Write request line and headers
  9868. detail::write_request_line(bstrm, req.method, path_with_query);
  9869. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  9870. error)) {
  9871. output_error_log(error, &req);
  9872. return false;
  9873. }
  9874. // Flush buffer
  9875. auto &data = bstrm.get_buffer();
  9876. if (!detail::write_data(strm, data.data(), data.size())) {
  9877. error = Error::Write;
  9878. output_error_log(error, &req);
  9879. return false;
  9880. }
  9881. }
  9882. // After sending request line and headers, wait briefly for an early server
  9883. // response (e.g. 4xx) and avoid sending a potentially large request body
  9884. // unnecessarily. This workaround is only enabled on Windows because Unix
  9885. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  9886. // buffering can accept large writes even when the peer already responded.
  9887. // Check the stream first (which covers SSL via `is_readable()`), then
  9888. // fall back to select on the socket. Only perform the wait for very large
  9889. // request bodies to avoid interfering with normal small requests and
  9890. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  9891. // response. Skip this check when using Expect: 100-continue, as the protocol
  9892. // handles early responses properly.
  9893. #if defined(_WIN32)
  9894. if (!skip_body &&
  9895. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  9896. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  9897. auto start = std::chrono::high_resolution_clock::now();
  9898. for (;;) {
  9899. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  9900. // from SSL internals. If the underlying socket is readable, assume an
  9901. // early response may be present.
  9902. auto sock = strm.socket();
  9903. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  9904. return false;
  9905. }
  9906. // Fallback to stream-level check for non-socket streams or when the
  9907. // socket isn't reporting readable. Avoid using `is_readable()` for
  9908. // SSL, since `SSL_pending()` may report buffered records that do not
  9909. // indicate a complete application-level response yet.
  9910. if (!is_ssl() && strm.is_readable()) { return false; }
  9911. auto now = std::chrono::high_resolution_clock::now();
  9912. auto elapsed =
  9913. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  9914. .count();
  9915. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  9916. break;
  9917. }
  9918. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  9919. }
  9920. }
  9921. #endif
  9922. // Body
  9923. if (skip_body) { return true; }
  9924. return write_request_body(strm, req, error);
  9925. }
  9926. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  9927. Error &error) {
  9928. if (req.body.empty()) {
  9929. return write_content_with_provider(strm, req, error);
  9930. }
  9931. if (req.upload_progress) {
  9932. auto body_size = req.body.size();
  9933. size_t written = 0;
  9934. auto data = req.body.data();
  9935. while (written < body_size) {
  9936. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  9937. if (!detail::write_data(strm, data + written, to_write)) {
  9938. error = Error::Write;
  9939. output_error_log(error, &req);
  9940. return false;
  9941. }
  9942. written += to_write;
  9943. if (!req.upload_progress(written, body_size)) {
  9944. error = Error::Canceled;
  9945. output_error_log(error, &req);
  9946. return false;
  9947. }
  9948. }
  9949. } else {
  9950. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  9951. error = Error::Write;
  9952. output_error_log(error, &req);
  9953. return false;
  9954. }
  9955. }
  9956. return true;
  9957. }
  9958. inline std::unique_ptr<Response>
  9959. ClientImpl::send_with_content_provider_and_receiver(
  9960. Request &req, const char *body, size_t content_length,
  9961. ContentProvider content_provider,
  9962. ContentProviderWithoutLength content_provider_without_length,
  9963. const std::string &content_type, ContentReceiver content_receiver,
  9964. Error &error) {
  9965. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9966. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9967. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  9968. #endif
  9969. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9970. if (compress_ && !content_provider_without_length) {
  9971. // TODO: Brotli support
  9972. detail::gzip_compressor compressor;
  9973. if (content_provider) {
  9974. auto ok = true;
  9975. size_t offset = 0;
  9976. DataSink data_sink;
  9977. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  9978. if (ok) {
  9979. auto last = offset + data_len == content_length;
  9980. auto ret = compressor.compress(
  9981. data, data_len, last,
  9982. [&](const char *compressed_data, size_t compressed_data_len) {
  9983. req.body.append(compressed_data, compressed_data_len);
  9984. return true;
  9985. });
  9986. if (ret) {
  9987. offset += data_len;
  9988. } else {
  9989. ok = false;
  9990. }
  9991. }
  9992. return ok;
  9993. };
  9994. while (ok && offset < content_length) {
  9995. if (!content_provider(offset, content_length - offset, data_sink)) {
  9996. error = Error::Canceled;
  9997. output_error_log(error, &req);
  9998. return nullptr;
  9999. }
  10000. }
  10001. } else {
  10002. if (!compressor.compress(body, content_length, true,
  10003. [&](const char *data, size_t data_len) {
  10004. req.body.append(data, data_len);
  10005. return true;
  10006. })) {
  10007. error = Error::Compression;
  10008. output_error_log(error, &req);
  10009. return nullptr;
  10010. }
  10011. }
  10012. } else
  10013. #endif
  10014. {
  10015. if (content_provider) {
  10016. req.content_length_ = content_length;
  10017. req.content_provider_ = std::move(content_provider);
  10018. req.is_chunked_content_provider_ = false;
  10019. } else if (content_provider_without_length) {
  10020. req.content_length_ = 0;
  10021. req.content_provider_ = detail::ContentProviderAdapter(
  10022. std::move(content_provider_without_length));
  10023. req.is_chunked_content_provider_ = true;
  10024. req.set_header("Transfer-Encoding", "chunked");
  10025. } else {
  10026. req.body.assign(body, content_length);
  10027. }
  10028. }
  10029. if (content_receiver) {
  10030. req.content_receiver =
  10031. [content_receiver](const char *data, size_t data_length,
  10032. size_t /*offset*/, size_t /*total_length*/) {
  10033. return content_receiver(data, data_length);
  10034. };
  10035. }
  10036. auto res = detail::make_unique<Response>();
  10037. return send(req, *res, error) ? std::move(res) : nullptr;
  10038. }
  10039. inline Result ClientImpl::send_with_content_provider_and_receiver(
  10040. const std::string &method, const std::string &path, const Headers &headers,
  10041. const char *body, size_t content_length, ContentProvider content_provider,
  10042. ContentProviderWithoutLength content_provider_without_length,
  10043. const std::string &content_type, ContentReceiver content_receiver,
  10044. UploadProgress progress) {
  10045. Request req;
  10046. req.method = method;
  10047. req.headers = headers;
  10048. req.path = path;
  10049. req.upload_progress = std::move(progress);
  10050. if (max_timeout_msec_ > 0) {
  10051. req.start_time_ = std::chrono::steady_clock::now();
  10052. }
  10053. auto error = Error::Success;
  10054. auto res = send_with_content_provider_and_receiver(
  10055. req, body, content_length, std::move(content_provider),
  10056. std::move(content_provider_without_length), content_type,
  10057. std::move(content_receiver), error);
  10058. #ifdef CPPHTTPLIB_SSL_ENABLED
  10059. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  10060. last_backend_error_};
  10061. #else
  10062. return Result{std::move(res), error, std::move(req.headers)};
  10063. #endif
  10064. }
  10065. inline void ClientImpl::output_log(const Request &req,
  10066. const Response &res) const {
  10067. if (logger_) {
  10068. std::lock_guard<std::mutex> guard(logger_mutex_);
  10069. logger_(req, res);
  10070. }
  10071. }
  10072. inline void ClientImpl::output_error_log(const Error &err,
  10073. const Request *req) const {
  10074. if (error_logger_) {
  10075. std::lock_guard<std::mutex> guard(logger_mutex_);
  10076. error_logger_(err, req);
  10077. }
  10078. }
  10079. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  10080. Response &res, bool close_connection,
  10081. Error &error) {
  10082. // Auto-add Expect: 100-continue for large bodies
  10083. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  10084. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  10085. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  10086. req.set_header("Expect", "100-continue");
  10087. }
  10088. }
  10089. // Check for Expect: 100-continue
  10090. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  10091. // Send request (skip body if using Expect: 100-continue)
  10092. auto write_request_success =
  10093. write_request(strm, req, close_connection, error, expect_100_continue);
  10094. #ifdef CPPHTTPLIB_SSL_ENABLED
  10095. if (is_ssl() && !expect_100_continue) {
  10096. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  10097. if (!is_proxy_enabled) {
  10098. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10099. error = Error::SSLPeerCouldBeClosed_;
  10100. output_error_log(error, &req);
  10101. return false;
  10102. }
  10103. }
  10104. }
  10105. #endif
  10106. // Handle Expect: 100-continue with timeout
  10107. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  10108. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  10109. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  10110. auto ret = detail::select_read(strm.socket(), sec, usec);
  10111. if (ret <= 0) {
  10112. // Timeout or error: send body anyway (server didn't respond in time)
  10113. if (!write_request_body(strm, req, error)) { return false; }
  10114. expect_100_continue = false; // Switch to normal response handling
  10115. }
  10116. }
  10117. // Receive response and headers
  10118. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  10119. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  10120. !detail::read_headers(strm, res.headers)) {
  10121. if (write_request_success) { error = Error::Read; }
  10122. output_error_log(error, &req);
  10123. return false;
  10124. }
  10125. if (!write_request_success) { return false; }
  10126. // Handle Expect: 100-continue response
  10127. if (expect_100_continue) {
  10128. if (res.status == StatusCode::Continue_100) {
  10129. // Server accepted, send the body
  10130. if (!write_request_body(strm, req, error)) { return false; }
  10131. // Read the actual response
  10132. res.headers.clear();
  10133. res.body.clear();
  10134. if (!read_response_line(strm, req, res) ||
  10135. !detail::read_headers(strm, res.headers)) {
  10136. error = Error::Read;
  10137. output_error_log(error, &req);
  10138. return false;
  10139. }
  10140. }
  10141. // If not 100 Continue, server returned an error; proceed with that response
  10142. }
  10143. // Body
  10144. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  10145. req.method != "CONNECT") {
  10146. auto redirect = 300 < res.status && res.status < 400 &&
  10147. res.status != StatusCode::NotModified_304 &&
  10148. follow_location_;
  10149. if (req.response_handler && !redirect) {
  10150. if (!req.response_handler(res)) {
  10151. error = Error::Canceled;
  10152. output_error_log(error, &req);
  10153. return false;
  10154. }
  10155. }
  10156. auto out =
  10157. req.content_receiver
  10158. ? static_cast<ContentReceiverWithProgress>(
  10159. [&](const char *buf, size_t n, size_t off, size_t len) {
  10160. if (redirect) { return true; }
  10161. auto ret = req.content_receiver(buf, n, off, len);
  10162. if (!ret) {
  10163. error = Error::Canceled;
  10164. output_error_log(error, &req);
  10165. }
  10166. return ret;
  10167. })
  10168. : static_cast<ContentReceiverWithProgress>(
  10169. [&](const char *buf, size_t n, size_t /*off*/,
  10170. size_t /*len*/) {
  10171. assert(res.body.size() + n <= res.body.max_size());
  10172. if (payload_max_length_ > 0 &&
  10173. (res.body.size() >= payload_max_length_ ||
  10174. n > payload_max_length_ - res.body.size())) {
  10175. return false;
  10176. }
  10177. res.body.append(buf, n);
  10178. return true;
  10179. });
  10180. auto progress = [&](size_t current, size_t total) {
  10181. if (!req.download_progress || redirect) { return true; }
  10182. auto ret = req.download_progress(current, total);
  10183. if (!ret) {
  10184. error = Error::Canceled;
  10185. output_error_log(error, &req);
  10186. }
  10187. return ret;
  10188. };
  10189. if (res.has_header("Content-Length")) {
  10190. if (!req.content_receiver) {
  10191. auto len = res.get_header_value_u64("Content-Length");
  10192. if (len > res.body.max_size()) {
  10193. error = Error::Read;
  10194. output_error_log(error, &req);
  10195. return false;
  10196. }
  10197. res.body.reserve(static_cast<size_t>(len));
  10198. }
  10199. }
  10200. if (res.status != StatusCode::NotModified_304) {
  10201. int dummy_status;
  10202. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  10203. ? (std::numeric_limits<size_t>::max)()
  10204. : payload_max_length_;
  10205. if (!detail::read_content(strm, res, max_length, dummy_status,
  10206. std::move(progress), std::move(out),
  10207. decompress_)) {
  10208. if (error != Error::Canceled) { error = Error::Read; }
  10209. output_error_log(error, &req);
  10210. return false;
  10211. }
  10212. }
  10213. }
  10214. // Log
  10215. output_log(req, res);
  10216. return true;
  10217. }
  10218. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  10219. const std::string &boundary, const UploadFormDataItems &items,
  10220. const FormDataProviderItems &provider_items) const {
  10221. size_t cur_item = 0;
  10222. size_t cur_start = 0;
  10223. // cur_item and cur_start are copied to within the std::function and
  10224. // maintain state between successive calls
  10225. return [&, cur_item, cur_start](size_t offset,
  10226. DataSink &sink) mutable -> bool {
  10227. if (!offset && !items.empty()) {
  10228. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  10229. return true;
  10230. } else if (cur_item < provider_items.size()) {
  10231. if (!cur_start) {
  10232. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  10233. provider_items[cur_item], boundary);
  10234. offset += begin.size();
  10235. cur_start = offset;
  10236. sink.os << begin;
  10237. }
  10238. DataSink cur_sink;
  10239. auto has_data = true;
  10240. cur_sink.write = sink.write;
  10241. cur_sink.done = [&]() { has_data = false; };
  10242. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  10243. return false;
  10244. }
  10245. if (!has_data) {
  10246. sink.os << detail::serialize_multipart_formdata_item_end();
  10247. cur_item++;
  10248. cur_start = 0;
  10249. }
  10250. return true;
  10251. } else {
  10252. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  10253. sink.done();
  10254. return true;
  10255. }
  10256. };
  10257. }
  10258. inline bool ClientImpl::process_socket(
  10259. const Socket &socket,
  10260. std::chrono::time_point<std::chrono::steady_clock> start_time,
  10261. std::function<bool(Stream &strm)> callback) {
  10262. return detail::process_client_socket(
  10263. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10264. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  10265. }
  10266. inline bool ClientImpl::is_ssl() const { return false; }
  10267. inline Result ClientImpl::Get(const std::string &path,
  10268. DownloadProgress progress) {
  10269. return Get(path, Headers(), std::move(progress));
  10270. }
  10271. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  10272. const Headers &headers,
  10273. DownloadProgress progress) {
  10274. if (params.empty()) { return Get(path, headers); }
  10275. std::string path_with_query = append_query_params(path, params);
  10276. return Get(path_with_query, headers, std::move(progress));
  10277. }
  10278. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  10279. DownloadProgress progress) {
  10280. Request req;
  10281. req.method = "GET";
  10282. req.path = path;
  10283. req.headers = headers;
  10284. req.download_progress = std::move(progress);
  10285. if (max_timeout_msec_ > 0) {
  10286. req.start_time_ = std::chrono::steady_clock::now();
  10287. }
  10288. return send_(std::move(req));
  10289. }
  10290. inline Result ClientImpl::Get(const std::string &path,
  10291. ContentReceiver content_receiver,
  10292. DownloadProgress progress) {
  10293. return Get(path, Headers(), nullptr, std::move(content_receiver),
  10294. std::move(progress));
  10295. }
  10296. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  10297. ContentReceiver content_receiver,
  10298. DownloadProgress progress) {
  10299. return Get(path, headers, nullptr, std::move(content_receiver),
  10300. std::move(progress));
  10301. }
  10302. inline Result ClientImpl::Get(const std::string &path,
  10303. ResponseHandler response_handler,
  10304. ContentReceiver content_receiver,
  10305. DownloadProgress progress) {
  10306. return Get(path, Headers(), std::move(response_handler),
  10307. std::move(content_receiver), std::move(progress));
  10308. }
  10309. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  10310. ResponseHandler response_handler,
  10311. ContentReceiver content_receiver,
  10312. DownloadProgress progress) {
  10313. Request req;
  10314. req.method = "GET";
  10315. req.path = path;
  10316. req.headers = headers;
  10317. req.response_handler = std::move(response_handler);
  10318. req.content_receiver =
  10319. [content_receiver](const char *data, size_t data_length,
  10320. size_t /*offset*/, size_t /*total_length*/) {
  10321. return content_receiver(data, data_length);
  10322. };
  10323. req.download_progress = std::move(progress);
  10324. if (max_timeout_msec_ > 0) {
  10325. req.start_time_ = std::chrono::steady_clock::now();
  10326. }
  10327. return send_(std::move(req));
  10328. }
  10329. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  10330. const Headers &headers,
  10331. ContentReceiver content_receiver,
  10332. DownloadProgress progress) {
  10333. return Get(path, params, headers, nullptr, std::move(content_receiver),
  10334. std::move(progress));
  10335. }
  10336. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  10337. const Headers &headers,
  10338. ResponseHandler response_handler,
  10339. ContentReceiver content_receiver,
  10340. DownloadProgress progress) {
  10341. if (params.empty()) {
  10342. return Get(path, headers, std::move(response_handler),
  10343. std::move(content_receiver), std::move(progress));
  10344. }
  10345. std::string path_with_query = append_query_params(path, params);
  10346. return Get(path_with_query, headers, std::move(response_handler),
  10347. std::move(content_receiver), std::move(progress));
  10348. }
  10349. inline Result ClientImpl::Head(const std::string &path) {
  10350. return Head(path, Headers());
  10351. }
  10352. inline Result ClientImpl::Head(const std::string &path,
  10353. const Headers &headers) {
  10354. Request req;
  10355. req.method = "HEAD";
  10356. req.headers = headers;
  10357. req.path = path;
  10358. if (max_timeout_msec_ > 0) {
  10359. req.start_time_ = std::chrono::steady_clock::now();
  10360. }
  10361. return send_(std::move(req));
  10362. }
  10363. inline Result ClientImpl::Post(const std::string &path) {
  10364. return Post(path, std::string(), std::string());
  10365. }
  10366. inline Result ClientImpl::Post(const std::string &path,
  10367. const Headers &headers) {
  10368. return Post(path, headers, nullptr, 0, std::string());
  10369. }
  10370. inline Result ClientImpl::Post(const std::string &path, const char *body,
  10371. size_t content_length,
  10372. const std::string &content_type,
  10373. UploadProgress progress) {
  10374. return Post(path, Headers(), body, content_length, content_type, progress);
  10375. }
  10376. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  10377. const std::string &content_type,
  10378. UploadProgress progress) {
  10379. return Post(path, Headers(), body, content_type, progress);
  10380. }
  10381. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  10382. return Post(path, Headers(), params);
  10383. }
  10384. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  10385. ContentProvider content_provider,
  10386. const std::string &content_type,
  10387. UploadProgress progress) {
  10388. return Post(path, Headers(), content_length, std::move(content_provider),
  10389. content_type, progress);
  10390. }
  10391. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  10392. ContentProvider content_provider,
  10393. const std::string &content_type,
  10394. ContentReceiver content_receiver,
  10395. UploadProgress progress) {
  10396. return Post(path, Headers(), content_length, std::move(content_provider),
  10397. content_type, std::move(content_receiver), progress);
  10398. }
  10399. inline Result ClientImpl::Post(const std::string &path,
  10400. ContentProviderWithoutLength content_provider,
  10401. const std::string &content_type,
  10402. UploadProgress progress) {
  10403. return Post(path, Headers(), std::move(content_provider), content_type,
  10404. progress);
  10405. }
  10406. inline Result ClientImpl::Post(const std::string &path,
  10407. ContentProviderWithoutLength content_provider,
  10408. const std::string &content_type,
  10409. ContentReceiver content_receiver,
  10410. UploadProgress progress) {
  10411. return Post(path, Headers(), std::move(content_provider), content_type,
  10412. std::move(content_receiver), progress);
  10413. }
  10414. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10415. const Params &params) {
  10416. auto query = detail::params_to_query_str(params);
  10417. return Post(path, headers, query, "application/x-www-form-urlencoded");
  10418. }
  10419. inline Result ClientImpl::Post(const std::string &path,
  10420. const UploadFormDataItems &items,
  10421. UploadProgress progress) {
  10422. return Post(path, Headers(), items, progress);
  10423. }
  10424. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10425. const UploadFormDataItems &items,
  10426. UploadProgress progress) {
  10427. const auto &boundary = detail::make_multipart_data_boundary();
  10428. const auto &content_type =
  10429. detail::serialize_multipart_formdata_get_content_type(boundary);
  10430. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10431. return Post(path, headers, body, content_type, progress);
  10432. }
  10433. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10434. const UploadFormDataItems &items,
  10435. const std::string &boundary,
  10436. UploadProgress progress) {
  10437. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10438. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10439. }
  10440. const auto &content_type =
  10441. detail::serialize_multipart_formdata_get_content_type(boundary);
  10442. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10443. return Post(path, headers, body, content_type, progress);
  10444. }
  10445. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10446. const char *body, size_t content_length,
  10447. const std::string &content_type,
  10448. UploadProgress progress) {
  10449. return send_with_content_provider_and_receiver(
  10450. "POST", path, headers, body, content_length, nullptr, nullptr,
  10451. content_type, nullptr, progress);
  10452. }
  10453. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10454. const std::string &body,
  10455. const std::string &content_type,
  10456. UploadProgress progress) {
  10457. return send_with_content_provider_and_receiver(
  10458. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  10459. content_type, nullptr, progress);
  10460. }
  10461. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10462. size_t content_length,
  10463. ContentProvider content_provider,
  10464. const std::string &content_type,
  10465. UploadProgress progress) {
  10466. return send_with_content_provider_and_receiver(
  10467. "POST", path, headers, nullptr, content_length,
  10468. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10469. }
  10470. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10471. size_t content_length,
  10472. ContentProvider content_provider,
  10473. const std::string &content_type,
  10474. ContentReceiver content_receiver,
  10475. DownloadProgress progress) {
  10476. return send_with_content_provider_and_receiver(
  10477. "POST", path, headers, nullptr, content_length,
  10478. std::move(content_provider), nullptr, content_type,
  10479. std::move(content_receiver), std::move(progress));
  10480. }
  10481. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10482. ContentProviderWithoutLength content_provider,
  10483. const std::string &content_type,
  10484. UploadProgress progress) {
  10485. return send_with_content_provider_and_receiver(
  10486. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10487. content_type, nullptr, progress);
  10488. }
  10489. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10490. ContentProviderWithoutLength content_provider,
  10491. const std::string &content_type,
  10492. ContentReceiver content_receiver,
  10493. DownloadProgress progress) {
  10494. return send_with_content_provider_and_receiver(
  10495. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10496. content_type, std::move(content_receiver), std::move(progress));
  10497. }
  10498. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10499. const UploadFormDataItems &items,
  10500. const FormDataProviderItems &provider_items,
  10501. UploadProgress progress) {
  10502. const auto &boundary = detail::make_multipart_data_boundary();
  10503. const auto &content_type =
  10504. detail::serialize_multipart_formdata_get_content_type(boundary);
  10505. return send_with_content_provider_and_receiver(
  10506. "POST", path, headers, nullptr, 0, nullptr,
  10507. get_multipart_content_provider(boundary, items, provider_items),
  10508. content_type, nullptr, progress);
  10509. }
  10510. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10511. const std::string &body,
  10512. const std::string &content_type,
  10513. ContentReceiver content_receiver,
  10514. DownloadProgress progress) {
  10515. Request req;
  10516. req.method = "POST";
  10517. req.path = path;
  10518. req.headers = headers;
  10519. req.body = body;
  10520. req.content_receiver =
  10521. [content_receiver](const char *data, size_t data_length,
  10522. size_t /*offset*/, size_t /*total_length*/) {
  10523. return content_receiver(data, data_length);
  10524. };
  10525. req.download_progress = std::move(progress);
  10526. if (max_timeout_msec_ > 0) {
  10527. req.start_time_ = std::chrono::steady_clock::now();
  10528. }
  10529. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10530. return send_(std::move(req));
  10531. }
  10532. inline Result ClientImpl::Put(const std::string &path) {
  10533. return Put(path, std::string(), std::string());
  10534. }
  10535. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  10536. return Put(path, headers, nullptr, 0, std::string());
  10537. }
  10538. inline Result ClientImpl::Put(const std::string &path, const char *body,
  10539. size_t content_length,
  10540. const std::string &content_type,
  10541. UploadProgress progress) {
  10542. return Put(path, Headers(), body, content_length, content_type, progress);
  10543. }
  10544. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  10545. const std::string &content_type,
  10546. UploadProgress progress) {
  10547. return Put(path, Headers(), body, content_type, progress);
  10548. }
  10549. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  10550. return Put(path, Headers(), params);
  10551. }
  10552. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10553. ContentProvider content_provider,
  10554. const std::string &content_type,
  10555. UploadProgress progress) {
  10556. return Put(path, Headers(), content_length, std::move(content_provider),
  10557. content_type, progress);
  10558. }
  10559. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10560. ContentProvider content_provider,
  10561. const std::string &content_type,
  10562. ContentReceiver content_receiver,
  10563. UploadProgress progress) {
  10564. return Put(path, Headers(), content_length, std::move(content_provider),
  10565. content_type, std::move(content_receiver), progress);
  10566. }
  10567. inline Result ClientImpl::Put(const std::string &path,
  10568. ContentProviderWithoutLength content_provider,
  10569. const std::string &content_type,
  10570. UploadProgress progress) {
  10571. return Put(path, Headers(), std::move(content_provider), content_type,
  10572. progress);
  10573. }
  10574. inline Result ClientImpl::Put(const std::string &path,
  10575. ContentProviderWithoutLength content_provider,
  10576. const std::string &content_type,
  10577. ContentReceiver content_receiver,
  10578. UploadProgress progress) {
  10579. return Put(path, Headers(), std::move(content_provider), content_type,
  10580. std::move(content_receiver), progress);
  10581. }
  10582. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10583. const Params &params) {
  10584. auto query = detail::params_to_query_str(params);
  10585. return Put(path, headers, query, "application/x-www-form-urlencoded");
  10586. }
  10587. inline Result ClientImpl::Put(const std::string &path,
  10588. const UploadFormDataItems &items,
  10589. UploadProgress progress) {
  10590. return Put(path, Headers(), items, progress);
  10591. }
  10592. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10593. const UploadFormDataItems &items,
  10594. UploadProgress progress) {
  10595. const auto &boundary = detail::make_multipart_data_boundary();
  10596. const auto &content_type =
  10597. detail::serialize_multipart_formdata_get_content_type(boundary);
  10598. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10599. return Put(path, headers, body, content_type, progress);
  10600. }
  10601. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10602. const UploadFormDataItems &items,
  10603. const std::string &boundary,
  10604. UploadProgress progress) {
  10605. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10606. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10607. }
  10608. const auto &content_type =
  10609. detail::serialize_multipart_formdata_get_content_type(boundary);
  10610. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10611. return Put(path, headers, body, content_type, progress);
  10612. }
  10613. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10614. const char *body, size_t content_length,
  10615. const std::string &content_type,
  10616. UploadProgress progress) {
  10617. return send_with_content_provider_and_receiver(
  10618. "PUT", path, headers, body, content_length, nullptr, nullptr,
  10619. content_type, nullptr, progress);
  10620. }
  10621. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10622. const std::string &body,
  10623. const std::string &content_type,
  10624. UploadProgress progress) {
  10625. return send_with_content_provider_and_receiver(
  10626. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  10627. content_type, nullptr, progress);
  10628. }
  10629. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10630. size_t content_length,
  10631. ContentProvider content_provider,
  10632. const std::string &content_type,
  10633. UploadProgress progress) {
  10634. return send_with_content_provider_and_receiver(
  10635. "PUT", path, headers, nullptr, content_length,
  10636. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10637. }
  10638. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10639. size_t content_length,
  10640. ContentProvider content_provider,
  10641. const std::string &content_type,
  10642. ContentReceiver content_receiver,
  10643. UploadProgress progress) {
  10644. return send_with_content_provider_and_receiver(
  10645. "PUT", path, headers, nullptr, content_length,
  10646. std::move(content_provider), nullptr, content_type,
  10647. std::move(content_receiver), progress);
  10648. }
  10649. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10650. ContentProviderWithoutLength content_provider,
  10651. const std::string &content_type,
  10652. UploadProgress progress) {
  10653. return send_with_content_provider_and_receiver(
  10654. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10655. content_type, nullptr, progress);
  10656. }
  10657. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10658. ContentProviderWithoutLength content_provider,
  10659. const std::string &content_type,
  10660. ContentReceiver content_receiver,
  10661. UploadProgress progress) {
  10662. return send_with_content_provider_and_receiver(
  10663. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10664. content_type, std::move(content_receiver), progress);
  10665. }
  10666. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10667. const UploadFormDataItems &items,
  10668. const FormDataProviderItems &provider_items,
  10669. UploadProgress progress) {
  10670. const auto &boundary = detail::make_multipart_data_boundary();
  10671. const auto &content_type =
  10672. detail::serialize_multipart_formdata_get_content_type(boundary);
  10673. return send_with_content_provider_and_receiver(
  10674. "PUT", path, headers, nullptr, 0, nullptr,
  10675. get_multipart_content_provider(boundary, items, provider_items),
  10676. content_type, nullptr, progress);
  10677. }
  10678. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10679. const std::string &body,
  10680. const std::string &content_type,
  10681. ContentReceiver content_receiver,
  10682. DownloadProgress progress) {
  10683. Request req;
  10684. req.method = "PUT";
  10685. req.path = path;
  10686. req.headers = headers;
  10687. req.body = body;
  10688. req.content_receiver =
  10689. [content_receiver](const char *data, size_t data_length,
  10690. size_t /*offset*/, size_t /*total_length*/) {
  10691. return content_receiver(data, data_length);
  10692. };
  10693. req.download_progress = std::move(progress);
  10694. if (max_timeout_msec_ > 0) {
  10695. req.start_time_ = std::chrono::steady_clock::now();
  10696. }
  10697. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10698. return send_(std::move(req));
  10699. }
  10700. inline Result ClientImpl::Patch(const std::string &path) {
  10701. return Patch(path, std::string(), std::string());
  10702. }
  10703. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10704. UploadProgress progress) {
  10705. return Patch(path, headers, nullptr, 0, std::string(), progress);
  10706. }
  10707. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  10708. size_t content_length,
  10709. const std::string &content_type,
  10710. UploadProgress progress) {
  10711. return Patch(path, Headers(), body, content_length, content_type, progress);
  10712. }
  10713. inline Result ClientImpl::Patch(const std::string &path,
  10714. const std::string &body,
  10715. const std::string &content_type,
  10716. UploadProgress progress) {
  10717. return Patch(path, Headers(), body, content_type, progress);
  10718. }
  10719. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  10720. return Patch(path, Headers(), params);
  10721. }
  10722. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10723. ContentProvider content_provider,
  10724. const std::string &content_type,
  10725. UploadProgress progress) {
  10726. return Patch(path, Headers(), content_length, std::move(content_provider),
  10727. content_type, progress);
  10728. }
  10729. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10730. ContentProvider content_provider,
  10731. const std::string &content_type,
  10732. ContentReceiver content_receiver,
  10733. UploadProgress progress) {
  10734. return Patch(path, Headers(), content_length, std::move(content_provider),
  10735. content_type, std::move(content_receiver), progress);
  10736. }
  10737. inline Result ClientImpl::Patch(const std::string &path,
  10738. ContentProviderWithoutLength content_provider,
  10739. const std::string &content_type,
  10740. UploadProgress progress) {
  10741. return Patch(path, Headers(), std::move(content_provider), content_type,
  10742. progress);
  10743. }
  10744. inline Result ClientImpl::Patch(const std::string &path,
  10745. ContentProviderWithoutLength content_provider,
  10746. const std::string &content_type,
  10747. ContentReceiver content_receiver,
  10748. UploadProgress progress) {
  10749. return Patch(path, Headers(), std::move(content_provider), content_type,
  10750. std::move(content_receiver), progress);
  10751. }
  10752. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10753. const Params &params) {
  10754. auto query = detail::params_to_query_str(params);
  10755. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  10756. }
  10757. inline Result ClientImpl::Patch(const std::string &path,
  10758. const UploadFormDataItems &items,
  10759. UploadProgress progress) {
  10760. return Patch(path, Headers(), items, progress);
  10761. }
  10762. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10763. const UploadFormDataItems &items,
  10764. UploadProgress progress) {
  10765. const auto &boundary = detail::make_multipart_data_boundary();
  10766. const auto &content_type =
  10767. detail::serialize_multipart_formdata_get_content_type(boundary);
  10768. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10769. return Patch(path, headers, body, content_type, progress);
  10770. }
  10771. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10772. const UploadFormDataItems &items,
  10773. const std::string &boundary,
  10774. UploadProgress progress) {
  10775. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10776. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10777. }
  10778. const auto &content_type =
  10779. detail::serialize_multipart_formdata_get_content_type(boundary);
  10780. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10781. return Patch(path, headers, body, content_type, progress);
  10782. }
  10783. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10784. const char *body, size_t content_length,
  10785. const std::string &content_type,
  10786. UploadProgress progress) {
  10787. return send_with_content_provider_and_receiver(
  10788. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  10789. content_type, nullptr, progress);
  10790. }
  10791. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10792. const std::string &body,
  10793. const std::string &content_type,
  10794. UploadProgress progress) {
  10795. return send_with_content_provider_and_receiver(
  10796. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  10797. content_type, nullptr, progress);
  10798. }
  10799. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10800. size_t content_length,
  10801. ContentProvider content_provider,
  10802. const std::string &content_type,
  10803. UploadProgress progress) {
  10804. return send_with_content_provider_and_receiver(
  10805. "PATCH", path, headers, nullptr, content_length,
  10806. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10807. }
  10808. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10809. size_t content_length,
  10810. ContentProvider content_provider,
  10811. const std::string &content_type,
  10812. ContentReceiver content_receiver,
  10813. UploadProgress progress) {
  10814. return send_with_content_provider_and_receiver(
  10815. "PATCH", path, headers, nullptr, content_length,
  10816. std::move(content_provider), nullptr, content_type,
  10817. std::move(content_receiver), progress);
  10818. }
  10819. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10820. ContentProviderWithoutLength content_provider,
  10821. const std::string &content_type,
  10822. UploadProgress progress) {
  10823. return send_with_content_provider_and_receiver(
  10824. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10825. content_type, nullptr, progress);
  10826. }
  10827. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10828. ContentProviderWithoutLength content_provider,
  10829. const std::string &content_type,
  10830. ContentReceiver content_receiver,
  10831. UploadProgress progress) {
  10832. return send_with_content_provider_and_receiver(
  10833. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10834. content_type, std::move(content_receiver), progress);
  10835. }
  10836. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10837. const UploadFormDataItems &items,
  10838. const FormDataProviderItems &provider_items,
  10839. UploadProgress progress) {
  10840. const auto &boundary = detail::make_multipart_data_boundary();
  10841. const auto &content_type =
  10842. detail::serialize_multipart_formdata_get_content_type(boundary);
  10843. return send_with_content_provider_and_receiver(
  10844. "PATCH", path, headers, nullptr, 0, nullptr,
  10845. get_multipart_content_provider(boundary, items, provider_items),
  10846. content_type, nullptr, progress);
  10847. }
  10848. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10849. const std::string &body,
  10850. const std::string &content_type,
  10851. ContentReceiver content_receiver,
  10852. DownloadProgress progress) {
  10853. Request req;
  10854. req.method = "PATCH";
  10855. req.path = path;
  10856. req.headers = headers;
  10857. req.body = body;
  10858. req.content_receiver =
  10859. [content_receiver](const char *data, size_t data_length,
  10860. size_t /*offset*/, size_t /*total_length*/) {
  10861. return content_receiver(data, data_length);
  10862. };
  10863. req.download_progress = std::move(progress);
  10864. if (max_timeout_msec_ > 0) {
  10865. req.start_time_ = std::chrono::steady_clock::now();
  10866. }
  10867. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10868. return send_(std::move(req));
  10869. }
  10870. inline Result ClientImpl::Delete(const std::string &path,
  10871. DownloadProgress progress) {
  10872. return Delete(path, Headers(), std::string(), std::string(), progress);
  10873. }
  10874. inline Result ClientImpl::Delete(const std::string &path,
  10875. const Headers &headers,
  10876. DownloadProgress progress) {
  10877. return Delete(path, headers, std::string(), std::string(), progress);
  10878. }
  10879. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  10880. size_t content_length,
  10881. const std::string &content_type,
  10882. DownloadProgress progress) {
  10883. return Delete(path, Headers(), body, content_length, content_type, progress);
  10884. }
  10885. inline Result ClientImpl::Delete(const std::string &path,
  10886. const std::string &body,
  10887. const std::string &content_type,
  10888. DownloadProgress progress) {
  10889. return Delete(path, Headers(), body.data(), body.size(), content_type,
  10890. progress);
  10891. }
  10892. inline Result ClientImpl::Delete(const std::string &path,
  10893. const Headers &headers,
  10894. const std::string &body,
  10895. const std::string &content_type,
  10896. DownloadProgress progress) {
  10897. return Delete(path, headers, body.data(), body.size(), content_type,
  10898. progress);
  10899. }
  10900. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  10901. DownloadProgress progress) {
  10902. return Delete(path, Headers(), params, progress);
  10903. }
  10904. inline Result ClientImpl::Delete(const std::string &path,
  10905. const Headers &headers, const Params &params,
  10906. DownloadProgress progress) {
  10907. auto query = detail::params_to_query_str(params);
  10908. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  10909. progress);
  10910. }
  10911. inline Result ClientImpl::Delete(const std::string &path,
  10912. const Headers &headers, const char *body,
  10913. size_t content_length,
  10914. const std::string &content_type,
  10915. DownloadProgress progress) {
  10916. Request req;
  10917. req.method = "DELETE";
  10918. req.headers = headers;
  10919. req.path = path;
  10920. req.download_progress = std::move(progress);
  10921. if (max_timeout_msec_ > 0) {
  10922. req.start_time_ = std::chrono::steady_clock::now();
  10923. }
  10924. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10925. req.body.assign(body, content_length);
  10926. return send_(std::move(req));
  10927. }
  10928. inline Result ClientImpl::Options(const std::string &path) {
  10929. return Options(path, Headers());
  10930. }
  10931. inline Result ClientImpl::Options(const std::string &path,
  10932. const Headers &headers) {
  10933. Request req;
  10934. req.method = "OPTIONS";
  10935. req.headers = headers;
  10936. req.path = path;
  10937. if (max_timeout_msec_ > 0) {
  10938. req.start_time_ = std::chrono::steady_clock::now();
  10939. }
  10940. return send_(std::move(req));
  10941. }
  10942. inline void ClientImpl::stop() {
  10943. std::lock_guard<std::mutex> guard(socket_mutex_);
  10944. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  10945. // do is to shutdown_socket, so that threads using this socket suddenly
  10946. // discover they can't read/write any more and error out. Everything else
  10947. // (closing the socket, shutting ssl down) is unsafe because these actions
  10948. // are not thread-safe.
  10949. if (socket_requests_in_flight_ > 0) {
  10950. shutdown_socket(socket_);
  10951. // Aside from that, we set a flag for the socket to be closed when we're
  10952. // done.
  10953. socket_should_be_closed_when_request_is_done_ = true;
  10954. return;
  10955. }
  10956. // Otherwise, still holding the mutex, we can shut everything down ourselves
  10957. shutdown_ssl(socket_, true);
  10958. shutdown_socket(socket_);
  10959. close_socket(socket_);
  10960. }
  10961. inline std::string ClientImpl::host() const { return host_; }
  10962. inline int ClientImpl::port() const { return port_; }
  10963. inline size_t ClientImpl::is_socket_open() const {
  10964. std::lock_guard<std::mutex> guard(socket_mutex_);
  10965. return socket_.is_open();
  10966. }
  10967. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  10968. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  10969. connection_timeout_sec_ = sec;
  10970. connection_timeout_usec_ = usec;
  10971. }
  10972. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  10973. read_timeout_sec_ = sec;
  10974. read_timeout_usec_ = usec;
  10975. }
  10976. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  10977. write_timeout_sec_ = sec;
  10978. write_timeout_usec_ = usec;
  10979. }
  10980. inline void ClientImpl::set_max_timeout(time_t msec) {
  10981. max_timeout_msec_ = msec;
  10982. }
  10983. inline void ClientImpl::set_basic_auth(const std::string &username,
  10984. const std::string &password) {
  10985. basic_auth_username_ = username;
  10986. basic_auth_password_ = password;
  10987. }
  10988. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  10989. bearer_token_auth_token_ = token;
  10990. }
  10991. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  10992. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  10993. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  10994. inline void
  10995. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  10996. addr_map_ = std::move(addr_map);
  10997. }
  10998. inline void ClientImpl::set_default_headers(Headers headers) {
  10999. default_headers_ = std::move(headers);
  11000. }
  11001. inline void ClientImpl::set_header_writer(
  11002. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11003. header_writer_ = writer;
  11004. }
  11005. inline void ClientImpl::set_address_family(int family) {
  11006. address_family_ = family;
  11007. }
  11008. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  11009. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  11010. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  11011. socket_options_ = std::move(socket_options);
  11012. }
  11013. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  11014. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  11015. inline void ClientImpl::set_payload_max_length(size_t length) {
  11016. payload_max_length_ = length;
  11017. has_payload_max_length_ = true;
  11018. }
  11019. inline void ClientImpl::set_interface(const std::string &intf) {
  11020. interface_ = intf;
  11021. }
  11022. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  11023. proxy_host_ = host;
  11024. proxy_port_ = port;
  11025. }
  11026. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  11027. const std::string &password) {
  11028. proxy_basic_auth_username_ = username;
  11029. proxy_basic_auth_password_ = password;
  11030. }
  11031. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  11032. proxy_bearer_token_auth_token_ = token;
  11033. }
  11034. #ifdef CPPHTTPLIB_SSL_ENABLED
  11035. inline void ClientImpl::set_digest_auth(const std::string &username,
  11036. const std::string &password) {
  11037. digest_auth_username_ = username;
  11038. digest_auth_password_ = password;
  11039. }
  11040. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  11041. const std::string &ca_cert_dir_path) {
  11042. ca_cert_file_path_ = ca_cert_file_path;
  11043. ca_cert_dir_path_ = ca_cert_dir_path;
  11044. }
  11045. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  11046. const std::string &password) {
  11047. proxy_digest_auth_username_ = username;
  11048. proxy_digest_auth_password_ = password;
  11049. }
  11050. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  11051. server_certificate_verification_ = enabled;
  11052. }
  11053. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  11054. server_hostname_verification_ = enabled;
  11055. }
  11056. #endif
  11057. // ClientImpl::set_ca_cert_store is defined after TLS namespace (uses helpers)
  11058. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11059. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  11060. std::size_t size) const {
  11061. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  11062. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  11063. if (!mem) { return nullptr; }
  11064. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  11065. if (!inf) { return nullptr; }
  11066. auto cts = X509_STORE_new();
  11067. if (cts) {
  11068. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  11069. auto itmp = sk_X509_INFO_value(inf, i);
  11070. if (!itmp) { continue; }
  11071. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  11072. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  11073. }
  11074. }
  11075. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  11076. return cts;
  11077. }
  11078. inline void ClientImpl::set_server_certificate_verifier(
  11079. std::function<SSLVerifierResponse(SSL *ssl)> /*verifier*/) {
  11080. // Base implementation does nothing - SSLClient overrides this
  11081. }
  11082. #endif
  11083. inline void ClientImpl::set_logger(Logger logger) {
  11084. logger_ = std::move(logger);
  11085. }
  11086. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  11087. error_logger_ = std::move(error_logger);
  11088. }
  11089. /*
  11090. * SSL/TLS Common Implementation
  11091. */
  11092. inline ClientConnection::~ClientConnection() {
  11093. #ifdef CPPHTTPLIB_SSL_ENABLED
  11094. if (session) {
  11095. tls::shutdown(session, true);
  11096. tls::free_session(session);
  11097. session = nullptr;
  11098. }
  11099. #endif
  11100. if (sock != INVALID_SOCKET) {
  11101. detail::close_socket(sock);
  11102. sock = INVALID_SOCKET;
  11103. }
  11104. }
  11105. // Universal client implementation
  11106. inline Client::Client(const std::string &scheme_host_port)
  11107. : Client(scheme_host_port, std::string(), std::string()) {}
  11108. inline Client::Client(const std::string &scheme_host_port,
  11109. const std::string &client_cert_path,
  11110. const std::string &client_key_path) {
  11111. const static std::regex re(
  11112. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  11113. std::smatch m;
  11114. if (std::regex_match(scheme_host_port, m, re)) {
  11115. auto scheme = m[1].str();
  11116. #ifdef CPPHTTPLIB_SSL_ENABLED
  11117. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  11118. #else
  11119. if (!scheme.empty() && scheme != "http") {
  11120. #endif
  11121. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11122. std::string msg = "'" + scheme + "' scheme is not supported.";
  11123. throw std::invalid_argument(msg);
  11124. #endif
  11125. return;
  11126. }
  11127. auto is_ssl = scheme == "https";
  11128. auto host = m[2].str();
  11129. if (host.empty()) { host = m[3].str(); }
  11130. auto port_str = m[4].str();
  11131. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  11132. if (is_ssl) {
  11133. #ifdef CPPHTTPLIB_SSL_ENABLED
  11134. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  11135. client_key_path);
  11136. is_ssl_ = is_ssl;
  11137. #endif
  11138. } else {
  11139. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  11140. client_key_path);
  11141. }
  11142. } else {
  11143. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  11144. // if port param below changes.
  11145. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  11146. client_cert_path, client_key_path);
  11147. }
  11148. } // namespace detail
  11149. inline Client::Client(const std::string &host, int port)
  11150. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  11151. inline Client::Client(const std::string &host, int port,
  11152. const std::string &client_cert_path,
  11153. const std::string &client_key_path)
  11154. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  11155. client_key_path)) {}
  11156. inline Client::~Client() = default;
  11157. inline bool Client::is_valid() const {
  11158. return cli_ != nullptr && cli_->is_valid();
  11159. }
  11160. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  11161. return cli_->Get(path, std::move(progress));
  11162. }
  11163. inline Result Client::Get(const std::string &path, const Headers &headers,
  11164. DownloadProgress progress) {
  11165. return cli_->Get(path, headers, std::move(progress));
  11166. }
  11167. inline Result Client::Get(const std::string &path,
  11168. ContentReceiver content_receiver,
  11169. DownloadProgress progress) {
  11170. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  11171. }
  11172. inline Result Client::Get(const std::string &path, const Headers &headers,
  11173. ContentReceiver content_receiver,
  11174. DownloadProgress progress) {
  11175. return cli_->Get(path, headers, std::move(content_receiver),
  11176. std::move(progress));
  11177. }
  11178. inline Result Client::Get(const std::string &path,
  11179. ResponseHandler response_handler,
  11180. ContentReceiver content_receiver,
  11181. DownloadProgress progress) {
  11182. return cli_->Get(path, std::move(response_handler),
  11183. std::move(content_receiver), std::move(progress));
  11184. }
  11185. inline Result Client::Get(const std::string &path, const Headers &headers,
  11186. ResponseHandler response_handler,
  11187. ContentReceiver content_receiver,
  11188. DownloadProgress progress) {
  11189. return cli_->Get(path, headers, std::move(response_handler),
  11190. std::move(content_receiver), std::move(progress));
  11191. }
  11192. inline Result Client::Get(const std::string &path, const Params &params,
  11193. const Headers &headers, DownloadProgress progress) {
  11194. return cli_->Get(path, params, headers, std::move(progress));
  11195. }
  11196. inline Result Client::Get(const std::string &path, const Params &params,
  11197. const Headers &headers,
  11198. ContentReceiver content_receiver,
  11199. DownloadProgress progress) {
  11200. return cli_->Get(path, params, headers, std::move(content_receiver),
  11201. std::move(progress));
  11202. }
  11203. inline Result Client::Get(const std::string &path, const Params &params,
  11204. const Headers &headers,
  11205. ResponseHandler response_handler,
  11206. ContentReceiver content_receiver,
  11207. DownloadProgress progress) {
  11208. return cli_->Get(path, params, headers, std::move(response_handler),
  11209. std::move(content_receiver), std::move(progress));
  11210. }
  11211. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  11212. inline Result Client::Head(const std::string &path, const Headers &headers) {
  11213. return cli_->Head(path, headers);
  11214. }
  11215. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  11216. inline Result Client::Post(const std::string &path, const Headers &headers) {
  11217. return cli_->Post(path, headers);
  11218. }
  11219. inline Result Client::Post(const std::string &path, const char *body,
  11220. size_t content_length,
  11221. const std::string &content_type,
  11222. UploadProgress progress) {
  11223. return cli_->Post(path, body, content_length, content_type, progress);
  11224. }
  11225. inline Result Client::Post(const std::string &path, const Headers &headers,
  11226. const char *body, size_t content_length,
  11227. const std::string &content_type,
  11228. UploadProgress progress) {
  11229. return cli_->Post(path, headers, body, content_length, content_type,
  11230. progress);
  11231. }
  11232. inline Result Client::Post(const std::string &path, const std::string &body,
  11233. const std::string &content_type,
  11234. UploadProgress progress) {
  11235. return cli_->Post(path, body, content_type, progress);
  11236. }
  11237. inline Result Client::Post(const std::string &path, const Headers &headers,
  11238. const std::string &body,
  11239. const std::string &content_type,
  11240. UploadProgress progress) {
  11241. return cli_->Post(path, headers, body, content_type, progress);
  11242. }
  11243. inline Result Client::Post(const std::string &path, size_t content_length,
  11244. ContentProvider content_provider,
  11245. const std::string &content_type,
  11246. UploadProgress progress) {
  11247. return cli_->Post(path, content_length, std::move(content_provider),
  11248. content_type, progress);
  11249. }
  11250. inline Result Client::Post(const std::string &path, size_t content_length,
  11251. ContentProvider content_provider,
  11252. const std::string &content_type,
  11253. ContentReceiver content_receiver,
  11254. UploadProgress progress) {
  11255. return cli_->Post(path, content_length, std::move(content_provider),
  11256. content_type, std::move(content_receiver), progress);
  11257. }
  11258. inline Result Client::Post(const std::string &path,
  11259. ContentProviderWithoutLength content_provider,
  11260. const std::string &content_type,
  11261. UploadProgress progress) {
  11262. return cli_->Post(path, std::move(content_provider), content_type, progress);
  11263. }
  11264. inline Result Client::Post(const std::string &path,
  11265. ContentProviderWithoutLength content_provider,
  11266. const std::string &content_type,
  11267. ContentReceiver content_receiver,
  11268. UploadProgress progress) {
  11269. return cli_->Post(path, std::move(content_provider), content_type,
  11270. std::move(content_receiver), progress);
  11271. }
  11272. inline Result Client::Post(const std::string &path, const Headers &headers,
  11273. size_t content_length,
  11274. ContentProvider content_provider,
  11275. const std::string &content_type,
  11276. UploadProgress progress) {
  11277. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11278. content_type, progress);
  11279. }
  11280. inline Result Client::Post(const std::string &path, const Headers &headers,
  11281. size_t content_length,
  11282. ContentProvider content_provider,
  11283. const std::string &content_type,
  11284. ContentReceiver content_receiver,
  11285. DownloadProgress progress) {
  11286. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11287. content_type, std::move(content_receiver), progress);
  11288. }
  11289. inline Result Client::Post(const std::string &path, const Headers &headers,
  11290. ContentProviderWithoutLength content_provider,
  11291. const std::string &content_type,
  11292. UploadProgress progress) {
  11293. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11294. progress);
  11295. }
  11296. inline Result Client::Post(const std::string &path, const Headers &headers,
  11297. ContentProviderWithoutLength content_provider,
  11298. const std::string &content_type,
  11299. ContentReceiver content_receiver,
  11300. DownloadProgress progress) {
  11301. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11302. std::move(content_receiver), progress);
  11303. }
  11304. inline Result Client::Post(const std::string &path, const Params &params) {
  11305. return cli_->Post(path, params);
  11306. }
  11307. inline Result Client::Post(const std::string &path, const Headers &headers,
  11308. const Params &params) {
  11309. return cli_->Post(path, headers, params);
  11310. }
  11311. inline Result Client::Post(const std::string &path,
  11312. const UploadFormDataItems &items,
  11313. UploadProgress progress) {
  11314. return cli_->Post(path, items, progress);
  11315. }
  11316. inline Result Client::Post(const std::string &path, const Headers &headers,
  11317. const UploadFormDataItems &items,
  11318. UploadProgress progress) {
  11319. return cli_->Post(path, headers, items, progress);
  11320. }
  11321. inline Result Client::Post(const std::string &path, const Headers &headers,
  11322. const UploadFormDataItems &items,
  11323. const std::string &boundary,
  11324. UploadProgress progress) {
  11325. return cli_->Post(path, headers, items, boundary, progress);
  11326. }
  11327. inline Result Client::Post(const std::string &path, const Headers &headers,
  11328. const UploadFormDataItems &items,
  11329. const FormDataProviderItems &provider_items,
  11330. UploadProgress progress) {
  11331. return cli_->Post(path, headers, items, provider_items, progress);
  11332. }
  11333. inline Result Client::Post(const std::string &path, const Headers &headers,
  11334. const std::string &body,
  11335. const std::string &content_type,
  11336. ContentReceiver content_receiver,
  11337. DownloadProgress progress) {
  11338. return cli_->Post(path, headers, body, content_type,
  11339. std::move(content_receiver), progress);
  11340. }
  11341. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  11342. inline Result Client::Put(const std::string &path, const Headers &headers) {
  11343. return cli_->Put(path, headers);
  11344. }
  11345. inline Result Client::Put(const std::string &path, const char *body,
  11346. size_t content_length,
  11347. const std::string &content_type,
  11348. UploadProgress progress) {
  11349. return cli_->Put(path, body, content_length, content_type, progress);
  11350. }
  11351. inline Result Client::Put(const std::string &path, const Headers &headers,
  11352. const char *body, size_t content_length,
  11353. const std::string &content_type,
  11354. UploadProgress progress) {
  11355. return cli_->Put(path, headers, body, content_length, content_type, progress);
  11356. }
  11357. inline Result Client::Put(const std::string &path, const std::string &body,
  11358. const std::string &content_type,
  11359. UploadProgress progress) {
  11360. return cli_->Put(path, body, content_type, progress);
  11361. }
  11362. inline Result Client::Put(const std::string &path, const Headers &headers,
  11363. const std::string &body,
  11364. const std::string &content_type,
  11365. UploadProgress progress) {
  11366. return cli_->Put(path, headers, body, content_type, progress);
  11367. }
  11368. inline Result Client::Put(const std::string &path, size_t content_length,
  11369. ContentProvider content_provider,
  11370. const std::string &content_type,
  11371. UploadProgress progress) {
  11372. return cli_->Put(path, content_length, std::move(content_provider),
  11373. content_type, progress);
  11374. }
  11375. inline Result Client::Put(const std::string &path, size_t content_length,
  11376. ContentProvider content_provider,
  11377. const std::string &content_type,
  11378. ContentReceiver content_receiver,
  11379. UploadProgress progress) {
  11380. return cli_->Put(path, content_length, std::move(content_provider),
  11381. content_type, std::move(content_receiver), progress);
  11382. }
  11383. inline Result Client::Put(const std::string &path,
  11384. ContentProviderWithoutLength content_provider,
  11385. const std::string &content_type,
  11386. UploadProgress progress) {
  11387. return cli_->Put(path, std::move(content_provider), content_type, progress);
  11388. }
  11389. inline Result Client::Put(const std::string &path,
  11390. ContentProviderWithoutLength content_provider,
  11391. const std::string &content_type,
  11392. ContentReceiver content_receiver,
  11393. UploadProgress progress) {
  11394. return cli_->Put(path, std::move(content_provider), content_type,
  11395. std::move(content_receiver), progress);
  11396. }
  11397. inline Result Client::Put(const std::string &path, const Headers &headers,
  11398. size_t content_length,
  11399. ContentProvider content_provider,
  11400. const std::string &content_type,
  11401. UploadProgress progress) {
  11402. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11403. content_type, progress);
  11404. }
  11405. inline Result Client::Put(const std::string &path, const Headers &headers,
  11406. size_t content_length,
  11407. ContentProvider content_provider,
  11408. const std::string &content_type,
  11409. ContentReceiver content_receiver,
  11410. UploadProgress progress) {
  11411. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11412. content_type, std::move(content_receiver), progress);
  11413. }
  11414. inline Result Client::Put(const std::string &path, const Headers &headers,
  11415. ContentProviderWithoutLength content_provider,
  11416. const std::string &content_type,
  11417. UploadProgress progress) {
  11418. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11419. progress);
  11420. }
  11421. inline Result Client::Put(const std::string &path, const Headers &headers,
  11422. ContentProviderWithoutLength content_provider,
  11423. const std::string &content_type,
  11424. ContentReceiver content_receiver,
  11425. UploadProgress progress) {
  11426. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11427. std::move(content_receiver), progress);
  11428. }
  11429. inline Result Client::Put(const std::string &path, const Params &params) {
  11430. return cli_->Put(path, params);
  11431. }
  11432. inline Result Client::Put(const std::string &path, const Headers &headers,
  11433. const Params &params) {
  11434. return cli_->Put(path, headers, params);
  11435. }
  11436. inline Result Client::Put(const std::string &path,
  11437. const UploadFormDataItems &items,
  11438. UploadProgress progress) {
  11439. return cli_->Put(path, items, progress);
  11440. }
  11441. inline Result Client::Put(const std::string &path, const Headers &headers,
  11442. const UploadFormDataItems &items,
  11443. UploadProgress progress) {
  11444. return cli_->Put(path, headers, items, progress);
  11445. }
  11446. inline Result Client::Put(const std::string &path, const Headers &headers,
  11447. const UploadFormDataItems &items,
  11448. const std::string &boundary,
  11449. UploadProgress progress) {
  11450. return cli_->Put(path, headers, items, boundary, progress);
  11451. }
  11452. inline Result Client::Put(const std::string &path, const Headers &headers,
  11453. const UploadFormDataItems &items,
  11454. const FormDataProviderItems &provider_items,
  11455. UploadProgress progress) {
  11456. return cli_->Put(path, headers, items, provider_items, progress);
  11457. }
  11458. inline Result Client::Put(const std::string &path, const Headers &headers,
  11459. const std::string &body,
  11460. const std::string &content_type,
  11461. ContentReceiver content_receiver,
  11462. DownloadProgress progress) {
  11463. return cli_->Put(path, headers, body, content_type, content_receiver,
  11464. progress);
  11465. }
  11466. inline Result Client::Patch(const std::string &path) {
  11467. return cli_->Patch(path);
  11468. }
  11469. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  11470. return cli_->Patch(path, headers);
  11471. }
  11472. inline Result Client::Patch(const std::string &path, const char *body,
  11473. size_t content_length,
  11474. const std::string &content_type,
  11475. UploadProgress progress) {
  11476. return cli_->Patch(path, body, content_length, content_type, progress);
  11477. }
  11478. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11479. const char *body, size_t content_length,
  11480. const std::string &content_type,
  11481. UploadProgress progress) {
  11482. return cli_->Patch(path, headers, body, content_length, content_type,
  11483. progress);
  11484. }
  11485. inline Result Client::Patch(const std::string &path, const std::string &body,
  11486. const std::string &content_type,
  11487. UploadProgress progress) {
  11488. return cli_->Patch(path, body, content_type, progress);
  11489. }
  11490. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11491. const std::string &body,
  11492. const std::string &content_type,
  11493. UploadProgress progress) {
  11494. return cli_->Patch(path, headers, body, content_type, progress);
  11495. }
  11496. inline Result Client::Patch(const std::string &path, size_t content_length,
  11497. ContentProvider content_provider,
  11498. const std::string &content_type,
  11499. UploadProgress progress) {
  11500. return cli_->Patch(path, content_length, std::move(content_provider),
  11501. content_type, progress);
  11502. }
  11503. inline Result Client::Patch(const std::string &path, size_t content_length,
  11504. ContentProvider content_provider,
  11505. const std::string &content_type,
  11506. ContentReceiver content_receiver,
  11507. UploadProgress progress) {
  11508. return cli_->Patch(path, content_length, std::move(content_provider),
  11509. content_type, std::move(content_receiver), progress);
  11510. }
  11511. inline Result Client::Patch(const std::string &path,
  11512. ContentProviderWithoutLength content_provider,
  11513. const std::string &content_type,
  11514. UploadProgress progress) {
  11515. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  11516. }
  11517. inline Result Client::Patch(const std::string &path,
  11518. ContentProviderWithoutLength content_provider,
  11519. const std::string &content_type,
  11520. ContentReceiver content_receiver,
  11521. UploadProgress progress) {
  11522. return cli_->Patch(path, std::move(content_provider), content_type,
  11523. std::move(content_receiver), progress);
  11524. }
  11525. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11526. size_t content_length,
  11527. ContentProvider content_provider,
  11528. const std::string &content_type,
  11529. UploadProgress progress) {
  11530. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11531. content_type, progress);
  11532. }
  11533. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11534. size_t content_length,
  11535. ContentProvider content_provider,
  11536. const std::string &content_type,
  11537. ContentReceiver content_receiver,
  11538. UploadProgress progress) {
  11539. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11540. content_type, std::move(content_receiver), progress);
  11541. }
  11542. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11543. ContentProviderWithoutLength content_provider,
  11544. const std::string &content_type,
  11545. UploadProgress progress) {
  11546. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11547. progress);
  11548. }
  11549. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11550. ContentProviderWithoutLength content_provider,
  11551. const std::string &content_type,
  11552. ContentReceiver content_receiver,
  11553. UploadProgress progress) {
  11554. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11555. std::move(content_receiver), progress);
  11556. }
  11557. inline Result Client::Patch(const std::string &path, const Params &params) {
  11558. return cli_->Patch(path, params);
  11559. }
  11560. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11561. const Params &params) {
  11562. return cli_->Patch(path, headers, params);
  11563. }
  11564. inline Result Client::Patch(const std::string &path,
  11565. const UploadFormDataItems &items,
  11566. UploadProgress progress) {
  11567. return cli_->Patch(path, items, progress);
  11568. }
  11569. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11570. const UploadFormDataItems &items,
  11571. UploadProgress progress) {
  11572. return cli_->Patch(path, headers, items, progress);
  11573. }
  11574. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11575. const UploadFormDataItems &items,
  11576. const std::string &boundary,
  11577. UploadProgress progress) {
  11578. return cli_->Patch(path, headers, items, boundary, progress);
  11579. }
  11580. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11581. const UploadFormDataItems &items,
  11582. const FormDataProviderItems &provider_items,
  11583. UploadProgress progress) {
  11584. return cli_->Patch(path, headers, items, provider_items, progress);
  11585. }
  11586. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11587. const std::string &body,
  11588. const std::string &content_type,
  11589. ContentReceiver content_receiver,
  11590. DownloadProgress progress) {
  11591. return cli_->Patch(path, headers, body, content_type, content_receiver,
  11592. progress);
  11593. }
  11594. inline Result Client::Delete(const std::string &path,
  11595. DownloadProgress progress) {
  11596. return cli_->Delete(path, progress);
  11597. }
  11598. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11599. DownloadProgress progress) {
  11600. return cli_->Delete(path, headers, progress);
  11601. }
  11602. inline Result Client::Delete(const std::string &path, const char *body,
  11603. size_t content_length,
  11604. const std::string &content_type,
  11605. DownloadProgress progress) {
  11606. return cli_->Delete(path, body, content_length, content_type, progress);
  11607. }
  11608. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11609. const char *body, size_t content_length,
  11610. const std::string &content_type,
  11611. DownloadProgress progress) {
  11612. return cli_->Delete(path, headers, body, content_length, content_type,
  11613. progress);
  11614. }
  11615. inline Result Client::Delete(const std::string &path, const std::string &body,
  11616. const std::string &content_type,
  11617. DownloadProgress progress) {
  11618. return cli_->Delete(path, body, content_type, progress);
  11619. }
  11620. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11621. const std::string &body,
  11622. const std::string &content_type,
  11623. DownloadProgress progress) {
  11624. return cli_->Delete(path, headers, body, content_type, progress);
  11625. }
  11626. inline Result Client::Delete(const std::string &path, const Params &params,
  11627. DownloadProgress progress) {
  11628. return cli_->Delete(path, params, progress);
  11629. }
  11630. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11631. const Params &params, DownloadProgress progress) {
  11632. return cli_->Delete(path, headers, params, progress);
  11633. }
  11634. inline Result Client::Options(const std::string &path) {
  11635. return cli_->Options(path);
  11636. }
  11637. inline Result Client::Options(const std::string &path, const Headers &headers) {
  11638. return cli_->Options(path, headers);
  11639. }
  11640. inline ClientImpl::StreamHandle
  11641. Client::open_stream(const std::string &method, const std::string &path,
  11642. const Params &params, const Headers &headers,
  11643. const std::string &body, const std::string &content_type) {
  11644. return cli_->open_stream(method, path, params, headers, body, content_type);
  11645. }
  11646. inline bool Client::send(Request &req, Response &res, Error &error) {
  11647. return cli_->send(req, res, error);
  11648. }
  11649. inline Result Client::send(const Request &req) { return cli_->send(req); }
  11650. inline void Client::stop() { cli_->stop(); }
  11651. inline std::string Client::host() const { return cli_->host(); }
  11652. inline int Client::port() const { return cli_->port(); }
  11653. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  11654. inline socket_t Client::socket() const { return cli_->socket(); }
  11655. inline void
  11656. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  11657. cli_->set_hostname_addr_map(std::move(addr_map));
  11658. }
  11659. inline void Client::set_default_headers(Headers headers) {
  11660. cli_->set_default_headers(std::move(headers));
  11661. }
  11662. inline void Client::set_header_writer(
  11663. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11664. cli_->set_header_writer(writer);
  11665. }
  11666. inline void Client::set_address_family(int family) {
  11667. cli_->set_address_family(family);
  11668. }
  11669. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  11670. inline void Client::set_socket_options(SocketOptions socket_options) {
  11671. cli_->set_socket_options(std::move(socket_options));
  11672. }
  11673. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  11674. cli_->set_connection_timeout(sec, usec);
  11675. }
  11676. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  11677. cli_->set_read_timeout(sec, usec);
  11678. }
  11679. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  11680. cli_->set_write_timeout(sec, usec);
  11681. }
  11682. inline void Client::set_basic_auth(const std::string &username,
  11683. const std::string &password) {
  11684. cli_->set_basic_auth(username, password);
  11685. }
  11686. inline void Client::set_bearer_token_auth(const std::string &token) {
  11687. cli_->set_bearer_token_auth(token);
  11688. }
  11689. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  11690. inline void Client::set_follow_location(bool on) {
  11691. cli_->set_follow_location(on);
  11692. }
  11693. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  11694. [[deprecated("Use set_path_encode instead")]]
  11695. inline void Client::set_url_encode(bool on) {
  11696. cli_->set_path_encode(on);
  11697. }
  11698. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  11699. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  11700. inline void Client::set_payload_max_length(size_t length) {
  11701. cli_->set_payload_max_length(length);
  11702. }
  11703. inline void Client::set_interface(const std::string &intf) {
  11704. cli_->set_interface(intf);
  11705. }
  11706. inline void Client::set_proxy(const std::string &host, int port) {
  11707. cli_->set_proxy(host, port);
  11708. }
  11709. inline void Client::set_proxy_basic_auth(const std::string &username,
  11710. const std::string &password) {
  11711. cli_->set_proxy_basic_auth(username, password);
  11712. }
  11713. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  11714. cli_->set_proxy_bearer_token_auth(token);
  11715. }
  11716. inline void Client::set_logger(Logger logger) {
  11717. cli_->set_logger(std::move(logger));
  11718. }
  11719. inline void Client::set_error_logger(ErrorLogger error_logger) {
  11720. cli_->set_error_logger(std::move(error_logger));
  11721. }
  11722. /*
  11723. * Group 6: SSL Server and Client implementation
  11724. */
  11725. #ifdef CPPHTTPLIB_SSL_ENABLED
  11726. // SSL HTTP server implementation
  11727. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  11728. const char *client_ca_cert_file_path,
  11729. const char *client_ca_cert_dir_path,
  11730. const char *private_key_password) {
  11731. using namespace tls;
  11732. ctx_ = create_server_context();
  11733. if (!ctx_) { return; }
  11734. // Load server certificate and private key
  11735. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  11736. private_key_password)) {
  11737. last_ssl_error_ = static_cast<int>(get_error());
  11738. free_context(ctx_);
  11739. ctx_ = nullptr;
  11740. return;
  11741. }
  11742. // Load client CA certificates for client authentication
  11743. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  11744. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  11745. client_ca_cert_dir_path)) {
  11746. last_ssl_error_ = static_cast<int>(get_error());
  11747. free_context(ctx_);
  11748. ctx_ = nullptr;
  11749. return;
  11750. }
  11751. // Enable client certificate verification
  11752. set_verify_client(ctx_, true);
  11753. }
  11754. }
  11755. inline SSLServer::SSLServer(const PemMemory &pem) {
  11756. using namespace tls;
  11757. ctx_ = create_server_context();
  11758. if (ctx_) {
  11759. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  11760. pem.private_key_password)) {
  11761. last_ssl_error_ = static_cast<int>(get_error());
  11762. free_context(ctx_);
  11763. ctx_ = nullptr;
  11764. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  11765. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  11766. last_ssl_error_ = static_cast<int>(get_error());
  11767. free_context(ctx_);
  11768. ctx_ = nullptr;
  11769. } else {
  11770. set_verify_client(ctx_, true);
  11771. }
  11772. }
  11773. }
  11774. }
  11775. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  11776. using namespace tls;
  11777. ctx_ = create_server_context();
  11778. if (ctx_) {
  11779. if (!setup_callback(ctx_)) {
  11780. free_context(ctx_);
  11781. ctx_ = nullptr;
  11782. }
  11783. }
  11784. }
  11785. inline SSLServer::~SSLServer() {
  11786. if (ctx_) { tls::free_context(ctx_); }
  11787. }
  11788. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  11789. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  11790. using namespace tls;
  11791. // Create TLS session with mutex protection
  11792. session_t session = nullptr;
  11793. {
  11794. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11795. session = create_session(static_cast<ctx_t>(ctx_), sock);
  11796. }
  11797. if (!session) {
  11798. last_ssl_error_ = static_cast<int>(get_error());
  11799. detail::shutdown_socket(sock);
  11800. detail::close_socket(sock);
  11801. return false;
  11802. }
  11803. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  11804. bool handshake_done = false;
  11805. bool ret = false;
  11806. auto cleanup = detail::scope_exit([&] {
  11807. // Shutdown gracefully if handshake succeeded and processing was successful
  11808. if (handshake_done) { shutdown(session, ret); }
  11809. free_session(session);
  11810. detail::shutdown_socket(sock);
  11811. detail::close_socket(sock);
  11812. });
  11813. // Perform TLS accept handshake with timeout
  11814. TlsError tls_err;
  11815. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  11816. &tls_err)) {
  11817. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11818. // Map TlsError to legacy ssl_error for backward compatibility
  11819. if (tls_err.code == ErrorCode::WantRead) {
  11820. last_ssl_error_ = SSL_ERROR_WANT_READ;
  11821. } else if (tls_err.code == ErrorCode::WantWrite) {
  11822. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  11823. } else {
  11824. last_ssl_error_ = SSL_ERROR_SSL;
  11825. }
  11826. #else
  11827. last_ssl_error_ = static_cast<int>(get_error());
  11828. #endif
  11829. return false;
  11830. }
  11831. handshake_done = true;
  11832. std::string remote_addr;
  11833. int remote_port = 0;
  11834. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  11835. std::string local_addr;
  11836. int local_port = 0;
  11837. detail::get_local_ip_and_port(sock, local_addr, local_port);
  11838. ret = detail::process_server_socket_ssl(
  11839. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  11840. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11841. write_timeout_usec_,
  11842. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  11843. return process_request(strm, remote_addr, remote_port, local_addr,
  11844. local_port, close_connection, connection_closed,
  11845. [&](Request &req) { req.ssl = session; });
  11846. });
  11847. return ret;
  11848. }
  11849. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  11850. const char *key_pem,
  11851. const char *client_ca_pem,
  11852. const char *password) {
  11853. if (!ctx_) { return false; }
  11854. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11855. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  11856. return false;
  11857. }
  11858. if (client_ca_pem) {
  11859. return tls::update_server_client_ca(ctx_, client_ca_pem);
  11860. }
  11861. return true;
  11862. }
  11863. // SSL HTTP client implementation
  11864. inline SSLClient::~SSLClient() {
  11865. if (ctx_) { tls::free_context(ctx_); }
  11866. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  11867. // base function rather than the derived function once we get to the
  11868. // base class destructor, and won't free the SSL (causing a leak).
  11869. shutdown_ssl_impl(socket_, true);
  11870. }
  11871. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  11872. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  11873. shutdown_ssl_impl(socket, shutdown_gracefully);
  11874. }
  11875. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  11876. bool shutdown_gracefully) {
  11877. if (socket.sock == INVALID_SOCKET) {
  11878. assert(socket.ssl == nullptr);
  11879. return;
  11880. }
  11881. if (socket.ssl) {
  11882. tls::shutdown(socket.ssl, shutdown_gracefully);
  11883. {
  11884. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11885. tls::free_session(socket.ssl);
  11886. }
  11887. socket.ssl = nullptr;
  11888. }
  11889. assert(socket.ssl == nullptr);
  11890. }
  11891. inline bool SSLClient::process_socket(
  11892. const Socket &socket,
  11893. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11894. std::function<bool(Stream &strm)> callback) {
  11895. assert(socket.ssl);
  11896. return detail::process_client_socket_ssl(
  11897. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  11898. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  11899. std::move(callback));
  11900. }
  11901. inline bool SSLClient::is_ssl() const { return true; }
  11902. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  11903. if (!is_valid()) {
  11904. error = Error::SSLConnection;
  11905. return false;
  11906. }
  11907. return ClientImpl::create_and_connect_socket(socket, error);
  11908. }
  11909. // Assumes that socket_mutex_ is locked and that there are no requests in
  11910. // flight
  11911. inline bool SSLClient::connect_with_proxy(
  11912. Socket &socket,
  11913. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11914. Response &res, bool &success, Error &error) {
  11915. success = true;
  11916. Response proxy_res;
  11917. if (!detail::process_client_socket(
  11918. socket.sock, read_timeout_sec_, read_timeout_usec_,
  11919. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  11920. start_time, [&](Stream &strm) {
  11921. Request req2;
  11922. req2.method = "CONNECT";
  11923. req2.path =
  11924. detail::make_host_and_port_string_always_port(host_, port_);
  11925. if (max_timeout_msec_ > 0) {
  11926. req2.start_time_ = std::chrono::steady_clock::now();
  11927. }
  11928. return process_request(strm, req2, proxy_res, false, error);
  11929. })) {
  11930. // Thread-safe to close everything because we are assuming there are no
  11931. // requests in flight
  11932. shutdown_ssl(socket, true);
  11933. shutdown_socket(socket);
  11934. close_socket(socket);
  11935. success = false;
  11936. return false;
  11937. }
  11938. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  11939. if (!proxy_digest_auth_username_.empty() &&
  11940. !proxy_digest_auth_password_.empty()) {
  11941. std::map<std::string, std::string> auth;
  11942. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  11943. // Close the current socket and create a new one for the authenticated
  11944. // request
  11945. shutdown_ssl(socket, true);
  11946. shutdown_socket(socket);
  11947. close_socket(socket);
  11948. // Create a new socket for the authenticated CONNECT request
  11949. if (!ensure_socket_connection(socket, error)) {
  11950. success = false;
  11951. output_error_log(error, nullptr);
  11952. return false;
  11953. }
  11954. proxy_res = Response();
  11955. if (!detail::process_client_socket(
  11956. socket.sock, read_timeout_sec_, read_timeout_usec_,
  11957. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  11958. start_time, [&](Stream &strm) {
  11959. Request req3;
  11960. req3.method = "CONNECT";
  11961. req3.path = detail::make_host_and_port_string_always_port(
  11962. host_, port_);
  11963. req3.headers.insert(detail::make_digest_authentication_header(
  11964. req3, auth, 1, detail::random_string(10),
  11965. proxy_digest_auth_username_, proxy_digest_auth_password_,
  11966. true));
  11967. if (max_timeout_msec_ > 0) {
  11968. req3.start_time_ = std::chrono::steady_clock::now();
  11969. }
  11970. return process_request(strm, req3, proxy_res, false, error);
  11971. })) {
  11972. // Thread-safe to close everything because we are assuming there are
  11973. // no requests in flight
  11974. shutdown_ssl(socket, true);
  11975. shutdown_socket(socket);
  11976. close_socket(socket);
  11977. success = false;
  11978. return false;
  11979. }
  11980. }
  11981. }
  11982. }
  11983. // If status code is not 200, proxy request is failed.
  11984. // Set error to ProxyConnection and return proxy response
  11985. // as the response of the request
  11986. if (proxy_res.status != StatusCode::OK_200) {
  11987. error = Error::ProxyConnection;
  11988. output_error_log(error, nullptr);
  11989. res = std::move(proxy_res);
  11990. // Thread-safe to close everything because we are assuming there are
  11991. // no requests in flight
  11992. shutdown_ssl(socket, true);
  11993. shutdown_socket(socket);
  11994. close_socket(socket);
  11995. return false;
  11996. }
  11997. return true;
  11998. }
  11999. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  12000. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  12001. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  12002. if (!initialize_ssl(socket, error)) {
  12003. shutdown_socket(socket);
  12004. close_socket(socket);
  12005. return false;
  12006. }
  12007. return true;
  12008. }
  12009. // SSL HTTP client implementation
  12010. inline SSLClient::SSLClient(const std::string &host)
  12011. : SSLClient(host, 443, std::string(), std::string()) {}
  12012. inline SSLClient::SSLClient(const std::string &host, int port)
  12013. : SSLClient(host, port, std::string(), std::string()) {}
  12014. inline SSLClient::SSLClient(const std::string &host, int port,
  12015. const std::string &client_cert_path,
  12016. const std::string &client_key_path,
  12017. const std::string &private_key_password)
  12018. : ClientImpl(host, port, client_cert_path, client_key_path) {
  12019. ctx_ = tls::create_client_context();
  12020. if (!ctx_) { return; }
  12021. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  12022. if (!client_cert_path.empty() && !client_key_path.empty()) {
  12023. const char *password =
  12024. private_key_password.empty() ? nullptr : private_key_password.c_str();
  12025. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  12026. client_key_path.c_str(), password)) {
  12027. last_backend_error_ = tls::get_error();
  12028. tls::free_context(ctx_);
  12029. ctx_ = nullptr;
  12030. }
  12031. }
  12032. }
  12033. inline SSLClient::SSLClient(const std::string &host, int port,
  12034. const PemMemory &pem)
  12035. : ClientImpl(host, port) {
  12036. ctx_ = tls::create_client_context();
  12037. if (!ctx_) { return; }
  12038. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  12039. if (pem.cert_pem && pem.key_pem) {
  12040. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  12041. pem.private_key_password)) {
  12042. last_backend_error_ = tls::get_error();
  12043. tls::free_context(ctx_);
  12044. ctx_ = nullptr;
  12045. }
  12046. }
  12047. }
  12048. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  12049. if (ca_cert_store && ctx_) {
  12050. // set_ca_store takes ownership of ca_cert_store
  12051. tls::set_ca_store(ctx_, ca_cert_store);
  12052. } else if (ca_cert_store) {
  12053. tls::free_ca_store(ca_cert_store);
  12054. }
  12055. }
  12056. inline void
  12057. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  12058. if (!ctx_) { return; }
  12059. tls::set_verify_callback(ctx_, verifier);
  12060. }
  12061. inline void SSLClient::set_session_verifier(
  12062. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  12063. session_verifier_ = std::move(verifier);
  12064. }
  12065. #if defined(_WIN32) && \
  12066. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12067. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  12068. enable_windows_cert_verification_ = enabled;
  12069. }
  12070. #endif
  12071. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  12072. std::size_t size) {
  12073. if (ctx_ && ca_cert && size > 0) {
  12074. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  12075. tls::load_ca_pem(ctx_, ca_cert, size);
  12076. }
  12077. }
  12078. inline bool SSLClient::load_certs() {
  12079. auto ret = true;
  12080. std::call_once(initialize_cert_, [&]() {
  12081. std::lock_guard<std::mutex> guard(ctx_mutex_);
  12082. if (!ca_cert_file_path_.empty()) {
  12083. if (!tls::load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  12084. last_backend_error_ = tls::get_error();
  12085. ret = false;
  12086. }
  12087. } else if (!ca_cert_dir_path_.empty()) {
  12088. if (!tls::load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  12089. last_backend_error_ = tls::get_error();
  12090. ret = false;
  12091. }
  12092. } else if (ca_cert_pem_.empty()) {
  12093. if (!tls::load_system_certs(ctx_)) {
  12094. last_backend_error_ = tls::get_error();
  12095. }
  12096. }
  12097. });
  12098. return ret;
  12099. }
  12100. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  12101. using namespace tls;
  12102. // Load CA certificates if server verification is enabled
  12103. if (server_certificate_verification_) {
  12104. if (!load_certs()) {
  12105. error = Error::SSLLoadingCerts;
  12106. output_error_log(error, nullptr);
  12107. return false;
  12108. }
  12109. }
  12110. bool is_ip = detail::is_ip_address(host_);
  12111. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  12112. // MbedTLS needs explicit verification mode (OpenSSL uses SSL_VERIFY_NONE
  12113. // by default and performs all verification post-handshake).
  12114. // For IP addresses with verification enabled, use OPTIONAL mode since
  12115. // MbedTLS requires hostname for VERIFY_REQUIRED.
  12116. if (is_ip && server_certificate_verification_) {
  12117. set_verify_client(ctx_, false);
  12118. } else {
  12119. set_verify_client(ctx_, server_certificate_verification_);
  12120. }
  12121. #endif
  12122. // Create TLS session
  12123. session_t session = nullptr;
  12124. {
  12125. std::lock_guard<std::mutex> guard(ctx_mutex_);
  12126. session = create_session(ctx_, socket.sock);
  12127. }
  12128. if (!session) {
  12129. error = Error::SSLConnection;
  12130. last_backend_error_ = get_error();
  12131. return false;
  12132. }
  12133. // Use scope_exit to ensure session is freed on error paths
  12134. bool success = false;
  12135. auto session_guard = detail::scope_exit([&] {
  12136. if (!success) { free_session(session); }
  12137. });
  12138. // Set SNI extension (skip for IP addresses per RFC 6066).
  12139. // On MbedTLS, set_sni also enables hostname verification internally.
  12140. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  12141. if (!is_ip) {
  12142. if (!set_sni(session, host_.c_str())) {
  12143. error = Error::SSLConnection;
  12144. last_backend_error_ = get_error();
  12145. return false;
  12146. }
  12147. }
  12148. // Perform non-blocking TLS handshake with timeout
  12149. TlsError tls_err;
  12150. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  12151. connection_timeout_usec_, &tls_err)) {
  12152. last_ssl_error_ = static_cast<int>(tls_err.code);
  12153. last_backend_error_ = tls_err.backend_code;
  12154. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  12155. error = Error::SSLServerVerification;
  12156. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  12157. error = Error::SSLServerHostnameVerification;
  12158. } else {
  12159. error = Error::SSLConnection;
  12160. }
  12161. output_error_log(error, nullptr);
  12162. return false;
  12163. }
  12164. // Post-handshake session verifier callback
  12165. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  12166. if (session_verifier_) { verification_status = session_verifier_(session); }
  12167. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  12168. last_backend_error_ = get_error();
  12169. error = Error::SSLServerVerification;
  12170. output_error_log(error, nullptr);
  12171. return false;
  12172. }
  12173. // Default server certificate verification
  12174. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  12175. server_certificate_verification_) {
  12176. verify_result_ = tls::get_verify_result(session);
  12177. if (verify_result_ != 0) {
  12178. last_backend_error_ = static_cast<unsigned long>(verify_result_);
  12179. error = Error::SSLServerVerification;
  12180. output_error_log(error, nullptr);
  12181. return false;
  12182. }
  12183. auto server_cert = get_peer_cert(session);
  12184. if (!server_cert) {
  12185. last_backend_error_ = get_error();
  12186. error = Error::SSLServerVerification;
  12187. output_error_log(error, nullptr);
  12188. return false;
  12189. }
  12190. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  12191. // Hostname verification (post-handshake for all cases).
  12192. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  12193. // On MbedTLS, set_sni already enabled hostname verification during
  12194. // handshake for non-IP hosts, but this check is still needed for IP
  12195. // addresses where SNI is not set.
  12196. if (server_hostname_verification_) {
  12197. if (!verify_hostname(server_cert, host_.c_str())) {
  12198. last_backend_error_ = hostname_mismatch_code();
  12199. error = Error::SSLServerHostnameVerification;
  12200. output_error_log(error, nullptr);
  12201. return false;
  12202. }
  12203. }
  12204. #if defined(_WIN32) && \
  12205. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12206. // Additional Windows Schannel verification.
  12207. // This provides real-time certificate validation with Windows Update
  12208. // integration, working with both OpenSSL and MbedTLS backends.
  12209. // Skip when a custom CA cert is specified, as the Windows certificate
  12210. // store would not know about user-provided CA certificates.
  12211. if (enable_windows_cert_verification_ && ca_cert_file_path_.empty() &&
  12212. ca_cert_dir_path_.empty() && ca_cert_pem_.empty()) {
  12213. std::vector<unsigned char> der;
  12214. if (get_cert_der(server_cert, der)) {
  12215. unsigned long wincrypt_error = 0;
  12216. if (!detail::verify_cert_with_windows_schannel(
  12217. der, host_, server_hostname_verification_, wincrypt_error)) {
  12218. last_backend_error_ = wincrypt_error;
  12219. error = Error::SSLServerVerification;
  12220. output_error_log(error, nullptr);
  12221. return false;
  12222. }
  12223. }
  12224. }
  12225. #endif
  12226. }
  12227. success = true;
  12228. socket.ssl = session;
  12229. return true;
  12230. }
  12231. inline void Client::set_digest_auth(const std::string &username,
  12232. const std::string &password) {
  12233. cli_->set_digest_auth(username, password);
  12234. }
  12235. inline void Client::set_proxy_digest_auth(const std::string &username,
  12236. const std::string &password) {
  12237. cli_->set_proxy_digest_auth(username, password);
  12238. }
  12239. inline void Client::enable_server_certificate_verification(bool enabled) {
  12240. cli_->enable_server_certificate_verification(enabled);
  12241. }
  12242. inline void Client::enable_server_hostname_verification(bool enabled) {
  12243. cli_->enable_server_hostname_verification(enabled);
  12244. }
  12245. #if defined(_WIN32) && \
  12246. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12247. inline void Client::enable_windows_certificate_verification(bool enabled) {
  12248. if (is_ssl_) {
  12249. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  12250. enabled);
  12251. }
  12252. }
  12253. #endif
  12254. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  12255. const std::string &ca_cert_dir_path) {
  12256. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  12257. }
  12258. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  12259. if (is_ssl_) {
  12260. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  12261. } else if (ca_cert_store) {
  12262. tls::free_ca_store(ca_cert_store);
  12263. }
  12264. }
  12265. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  12266. set_ca_cert_store(tls::create_ca_store(ca_cert, size));
  12267. }
  12268. inline void
  12269. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  12270. if (is_ssl_) {
  12271. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  12272. std::move(verifier));
  12273. }
  12274. }
  12275. inline void Client::set_session_verifier(
  12276. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  12277. if (is_ssl_) {
  12278. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  12279. }
  12280. }
  12281. inline tls::ctx_t Client::tls_context() const {
  12282. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  12283. return nullptr;
  12284. }
  12285. #endif // CPPHTTPLIB_SSL_ENABLED
  12286. /*
  12287. * Group 7: TLS abstraction layer - Common API
  12288. */
  12289. #ifdef CPPHTTPLIB_SSL_ENABLED
  12290. namespace tls {
  12291. // Helper for PeerCert construction
  12292. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  12293. return PeerCert(get_peer_cert(session));
  12294. }
  12295. namespace impl {
  12296. inline VerifyCallback &get_verify_callback() {
  12297. static thread_local VerifyCallback callback;
  12298. return callback;
  12299. }
  12300. inline VerifyCallback &get_mbedtls_verify_callback() {
  12301. static thread_local VerifyCallback callback;
  12302. return callback;
  12303. }
  12304. } // namespace impl
  12305. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  12306. const char *ca_dir) {
  12307. if (!ctx) { return false; }
  12308. bool success = true;
  12309. if (ca_file && *ca_file) {
  12310. if (!load_ca_file(ctx, ca_file)) { success = false; }
  12311. }
  12312. if (ca_dir && *ca_dir) {
  12313. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  12314. }
  12315. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12316. // Set CA list for client certificate request (CertificateRequest message)
  12317. if (ca_file && *ca_file) {
  12318. auto list = SSL_load_client_CA_file(ca_file);
  12319. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  12320. }
  12321. #endif
  12322. return success;
  12323. }
  12324. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  12325. const char *password) {
  12326. return set_client_cert_pem(ctx, cert, key, password);
  12327. }
  12328. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  12329. const char *key_path, const char *password) {
  12330. return set_client_cert_file(ctx, cert_path, key_path, password);
  12331. }
  12332. // PeerCert implementation
  12333. inline PeerCert::PeerCert() = default;
  12334. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  12335. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  12336. other.cert_ = nullptr;
  12337. }
  12338. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  12339. if (this != &other) {
  12340. if (cert_) { free_cert(cert_); }
  12341. cert_ = other.cert_;
  12342. other.cert_ = nullptr;
  12343. }
  12344. return *this;
  12345. }
  12346. inline PeerCert::~PeerCert() {
  12347. if (cert_) { free_cert(cert_); }
  12348. }
  12349. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  12350. inline std::string PeerCert::subject_cn() const {
  12351. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  12352. }
  12353. inline std::string PeerCert::issuer_name() const {
  12354. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  12355. }
  12356. inline bool PeerCert::check_hostname(const char *hostname) const {
  12357. return cert_ ? verify_hostname(cert_, hostname) : false;
  12358. }
  12359. inline std::vector<SanEntry> PeerCert::sans() const {
  12360. std::vector<SanEntry> result;
  12361. if (cert_) { get_cert_sans(cert_, result); }
  12362. return result;
  12363. }
  12364. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  12365. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  12366. }
  12367. inline std::string PeerCert::serial() const {
  12368. return cert_ ? get_cert_serial(cert_) : std::string();
  12369. }
  12370. // VerifyContext method implementations
  12371. inline std::string VerifyContext::subject_cn() const {
  12372. return cert ? get_cert_subject_cn(cert) : std::string();
  12373. }
  12374. inline std::string VerifyContext::issuer_name() const {
  12375. return cert ? get_cert_issuer_name(cert) : std::string();
  12376. }
  12377. inline bool VerifyContext::check_hostname(const char *hostname) const {
  12378. return cert ? verify_hostname(cert, hostname) : false;
  12379. }
  12380. inline std::vector<SanEntry> VerifyContext::sans() const {
  12381. std::vector<SanEntry> result;
  12382. if (cert) { get_cert_sans(cert, result); }
  12383. return result;
  12384. }
  12385. inline bool VerifyContext::validity(time_t &not_before,
  12386. time_t &not_after) const {
  12387. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  12388. }
  12389. inline std::string VerifyContext::serial() const {
  12390. return cert ? get_cert_serial(cert) : std::string();
  12391. }
  12392. // TlsError static method implementation
  12393. inline std::string TlsError::verify_error_to_string(long error_code) {
  12394. return verify_error_string(error_code);
  12395. }
  12396. } // namespace tls
  12397. // Request::peer_cert() implementation
  12398. inline tls::PeerCert Request::peer_cert() const {
  12399. return tls::get_peer_cert_from_session(ssl);
  12400. }
  12401. // Request::sni() implementation
  12402. inline std::string Request::sni() const {
  12403. if (!ssl) { return std::string(); }
  12404. const char *s = tls::get_sni(ssl);
  12405. return s ? std::string(s) : std::string();
  12406. }
  12407. #endif // CPPHTTPLIB_SSL_ENABLED
  12408. /*
  12409. * Group 8: TLS abstraction layer - OpenSSL backend
  12410. */
  12411. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12412. inline SSL_CTX *Client::ssl_context() const {
  12413. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  12414. return nullptr;
  12415. }
  12416. inline void Client::set_server_certificate_verifier(
  12417. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  12418. cli_->set_server_certificate_verifier(verifier);
  12419. }
  12420. inline long Client::get_verify_result() const {
  12421. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).get_verify_result(); }
  12422. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  12423. }
  12424. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  12425. /*
  12426. * OpenSSL Backend Implementation
  12427. */
  12428. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12429. namespace tls {
  12430. namespace impl {
  12431. // OpenSSL-specific helpers for converting native types to PEM
  12432. inline std::string x509_to_pem(X509 *cert) {
  12433. if (!cert) return {};
  12434. BIO *bio = BIO_new(BIO_s_mem());
  12435. if (!bio) return {};
  12436. if (PEM_write_bio_X509(bio, cert) != 1) {
  12437. BIO_free(bio);
  12438. return {};
  12439. }
  12440. char *data = nullptr;
  12441. long len = BIO_get_mem_data(bio, &data);
  12442. std::string pem(data, static_cast<size_t>(len));
  12443. BIO_free(bio);
  12444. return pem;
  12445. }
  12446. inline std::string evp_pkey_to_pem(EVP_PKEY *key) {
  12447. if (!key) return {};
  12448. BIO *bio = BIO_new(BIO_s_mem());
  12449. if (!bio) return {};
  12450. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr,
  12451. nullptr) != 1) {
  12452. BIO_free(bio);
  12453. return {};
  12454. }
  12455. char *data = nullptr;
  12456. long len = BIO_get_mem_data(bio, &data);
  12457. std::string pem(data, static_cast<size_t>(len));
  12458. BIO_free(bio);
  12459. return pem;
  12460. }
  12461. inline std::string x509_store_to_pem(X509_STORE *store) {
  12462. if (!store) return {};
  12463. std::string pem;
  12464. auto objs = X509_STORE_get0_objects(store);
  12465. if (!objs) return {};
  12466. auto count = sk_X509_OBJECT_num(objs);
  12467. for (decltype(count) i = 0; i < count; i++) {
  12468. auto obj = sk_X509_OBJECT_value(objs, i);
  12469. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  12470. auto cert = X509_OBJECT_get0_X509(obj);
  12471. if (cert) { pem += x509_to_pem(cert); }
  12472. }
  12473. }
  12474. return pem;
  12475. }
  12476. // Helper to map OpenSSL SSL_get_error to ErrorCode
  12477. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  12478. switch (ssl_error) {
  12479. case SSL_ERROR_NONE: return ErrorCode::Success;
  12480. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  12481. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  12482. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  12483. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  12484. case SSL_ERROR_SSL:
  12485. default: return ErrorCode::Fatal;
  12486. }
  12487. }
  12488. // Helper: Create client CA list from PEM string
  12489. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  12490. // Caller takes ownership of returned list
  12491. inline STACK_OF(X509_NAME) *
  12492. create_client_ca_list_from_pem(const char *ca_pem) {
  12493. if (!ca_pem) { return nullptr; }
  12494. auto ca_list = sk_X509_NAME_new_null();
  12495. if (!ca_list) { return nullptr; }
  12496. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  12497. if (!bio) {
  12498. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  12499. return nullptr;
  12500. }
  12501. X509 *cert = nullptr;
  12502. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  12503. nullptr) {
  12504. X509_NAME *name = X509_get_subject_name(cert);
  12505. if (name) { sk_X509_NAME_push(ca_list, X509_NAME_dup(name)); }
  12506. X509_free(cert);
  12507. }
  12508. BIO_free(bio);
  12509. return ca_list;
  12510. }
  12511. // Helper: Extract CA names from X509_STORE
  12512. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  12513. // Caller takes ownership of returned list
  12514. inline STACK_OF(X509_NAME) *
  12515. extract_client_ca_list_from_store(X509_STORE *store) {
  12516. if (!store) { return nullptr; }
  12517. auto ca_list = sk_X509_NAME_new_null();
  12518. if (!ca_list) { return nullptr; }
  12519. auto objs = X509_STORE_get0_objects(store);
  12520. if (!objs) {
  12521. sk_X509_NAME_free(ca_list);
  12522. return nullptr;
  12523. }
  12524. auto count = sk_X509_OBJECT_num(objs);
  12525. for (decltype(count) i = 0; i < count; i++) {
  12526. auto obj = sk_X509_OBJECT_value(objs, i);
  12527. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  12528. auto cert = X509_OBJECT_get0_X509(obj);
  12529. if (cert) {
  12530. auto subject = X509_get_subject_name(cert);
  12531. if (subject) {
  12532. auto name_dup = X509_NAME_dup(subject);
  12533. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  12534. }
  12535. }
  12536. }
  12537. }
  12538. if (sk_X509_NAME_num(ca_list) == 0) {
  12539. sk_X509_NAME_free(ca_list);
  12540. return nullptr;
  12541. }
  12542. return ca_list;
  12543. }
  12544. // OpenSSL verify callback wrapper
  12545. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  12546. auto &callback = get_verify_callback();
  12547. if (!callback) { return preverify_ok; }
  12548. // Get SSL object from X509_STORE_CTX
  12549. auto ssl = static_cast<SSL *>(
  12550. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  12551. if (!ssl) { return preverify_ok; }
  12552. // Get current certificate and depth
  12553. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  12554. int depth = X509_STORE_CTX_get_error_depth(ctx);
  12555. int error = X509_STORE_CTX_get_error(ctx);
  12556. // Build context
  12557. VerifyContext verify_ctx;
  12558. verify_ctx.session = static_cast<session_t>(ssl);
  12559. verify_ctx.cert = static_cast<cert_t>(cert);
  12560. verify_ctx.depth = depth;
  12561. verify_ctx.preverify_ok = (preverify_ok != 0);
  12562. verify_ctx.error_code = error;
  12563. verify_ctx.error_string =
  12564. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  12565. return callback(verify_ctx) ? 1 : 0;
  12566. }
  12567. } // namespace impl
  12568. inline ctx_t create_client_context() {
  12569. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  12570. if (ctx) {
  12571. // Disable auto-retry to properly handle non-blocking I/O
  12572. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  12573. // Set minimum TLS version
  12574. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  12575. }
  12576. return static_cast<ctx_t>(ctx);
  12577. }
  12578. inline void free_context(ctx_t ctx) {
  12579. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  12580. }
  12581. inline bool set_min_version(ctx_t ctx, Version version) {
  12582. if (!ctx) return false;
  12583. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  12584. static_cast<int>(version)) == 1;
  12585. }
  12586. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  12587. if (!ctx || !pem || len == 0) return false;
  12588. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12589. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12590. if (!store) return false;
  12591. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  12592. if (!bio) return false;
  12593. bool ok = true;
  12594. X509 *cert = nullptr;
  12595. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  12596. nullptr) {
  12597. if (X509_STORE_add_cert(store, cert) != 1) {
  12598. // Ignore duplicate errors
  12599. auto err = ERR_peek_last_error();
  12600. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  12601. ok = false;
  12602. }
  12603. }
  12604. X509_free(cert);
  12605. if (!ok) break;
  12606. }
  12607. BIO_free(bio);
  12608. // Clear any "no more certificates" errors
  12609. ERR_clear_error();
  12610. return ok;
  12611. }
  12612. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  12613. if (!ctx || !file_path) return false;
  12614. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  12615. nullptr) == 1;
  12616. }
  12617. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  12618. if (!ctx || !dir_path) return false;
  12619. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  12620. dir_path) == 1;
  12621. }
  12622. inline bool load_system_certs(ctx_t ctx) {
  12623. if (!ctx) return false;
  12624. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12625. #ifdef _WIN32
  12626. // Windows: Load from system certificate store (ROOT and CA)
  12627. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12628. if (!store) return false;
  12629. bool loaded_any = false;
  12630. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  12631. for (auto store_name : store_names) {
  12632. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  12633. if (!hStore) continue;
  12634. PCCERT_CONTEXT pContext = nullptr;
  12635. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  12636. nullptr) {
  12637. const unsigned char *data = pContext->pbCertEncoded;
  12638. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  12639. if (x509) {
  12640. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  12641. X509_free(x509);
  12642. }
  12643. }
  12644. CertCloseStore(hStore, 0);
  12645. }
  12646. return loaded_any;
  12647. #elif defined(__APPLE__)
  12648. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  12649. // macOS: Load from Keychain
  12650. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12651. if (!store) return false;
  12652. CFArrayRef certs = nullptr;
  12653. if (SecTrustCopyAnchorCertificates(&certs) != errSecSuccess || !certs) {
  12654. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12655. }
  12656. bool loaded_any = false;
  12657. auto count = CFArrayGetCount(certs);
  12658. for (CFIndex i = 0; i < count; i++) {
  12659. auto cert = reinterpret_cast<SecCertificateRef>(
  12660. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  12661. CFDataRef der = SecCertificateCopyData(cert);
  12662. if (der) {
  12663. const unsigned char *data = CFDataGetBytePtr(der);
  12664. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  12665. if (x509) {
  12666. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  12667. X509_free(x509);
  12668. }
  12669. CFRelease(der);
  12670. }
  12671. }
  12672. CFRelease(certs);
  12673. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12674. #else
  12675. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12676. #endif
  12677. #else
  12678. // Other Unix: use default verify paths
  12679. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12680. #endif
  12681. }
  12682. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  12683. const char *password) {
  12684. if (!ctx || !cert || !key) return false;
  12685. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12686. // Load certificate
  12687. auto cert_bio = BIO_new_mem_buf(cert, -1);
  12688. if (!cert_bio) return false;
  12689. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  12690. BIO_free(cert_bio);
  12691. if (!x509) return false;
  12692. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  12693. X509_free(x509);
  12694. if (!cert_ok) return false;
  12695. // Load private key
  12696. auto key_bio = BIO_new_mem_buf(key, -1);
  12697. if (!key_bio) return false;
  12698. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  12699. password ? const_cast<char *>(password)
  12700. : nullptr);
  12701. BIO_free(key_bio);
  12702. if (!pkey) return false;
  12703. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  12704. EVP_PKEY_free(pkey);
  12705. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  12706. }
  12707. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  12708. const char *key_path, const char *password) {
  12709. if (!ctx || !cert_path || !key_path) return false;
  12710. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12711. if (password && password[0] != '\0') {
  12712. SSL_CTX_set_default_passwd_cb_userdata(
  12713. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  12714. }
  12715. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  12716. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  12717. }
  12718. inline ctx_t create_server_context() {
  12719. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12720. if (ctx) {
  12721. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  12722. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12723. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  12724. }
  12725. return static_cast<ctx_t>(ctx);
  12726. }
  12727. inline void set_verify_client(ctx_t ctx, bool require) {
  12728. if (!ctx) return;
  12729. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  12730. require
  12731. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  12732. : SSL_VERIFY_NONE,
  12733. nullptr);
  12734. }
  12735. inline session_t create_session(ctx_t ctx, socket_t sock) {
  12736. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  12737. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12738. SSL *ssl = SSL_new(ssl_ctx);
  12739. if (!ssl) return nullptr;
  12740. // Disable auto-retry for proper non-blocking I/O handling
  12741. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  12742. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  12743. if (!bio) {
  12744. SSL_free(ssl);
  12745. return nullptr;
  12746. }
  12747. SSL_set_bio(ssl, bio, bio);
  12748. return static_cast<session_t>(ssl);
  12749. }
  12750. inline void free_session(session_t session) {
  12751. if (session) { SSL_free(static_cast<SSL *>(session)); }
  12752. }
  12753. inline bool set_sni(session_t session, const char *hostname) {
  12754. if (!session || !hostname) return false;
  12755. auto ssl = static_cast<SSL *>(session);
  12756. // Set SNI (Server Name Indication) only - does not enable verification
  12757. #if defined(OPENSSL_IS_BORINGSSL)
  12758. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  12759. #else
  12760. // Direct call instead of macro to suppress -Wold-style-cast warning
  12761. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  12762. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  12763. #endif
  12764. }
  12765. inline bool set_hostname(session_t session, const char *hostname) {
  12766. if (!session || !hostname) return false;
  12767. auto ssl = static_cast<SSL *>(session);
  12768. // Set SNI (Server Name Indication)
  12769. if (!set_sni(session, hostname)) { return false; }
  12770. // Enable hostname verification
  12771. auto param = SSL_get0_param(ssl);
  12772. if (!param) return false;
  12773. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  12774. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  12775. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  12776. return true;
  12777. }
  12778. inline TlsError connect(session_t session) {
  12779. if (!session) { return TlsError(); }
  12780. auto ssl = static_cast<SSL *>(session);
  12781. auto ret = SSL_connect(ssl);
  12782. TlsError err;
  12783. if (ret == 1) {
  12784. err.code = ErrorCode::Success;
  12785. } else {
  12786. auto ssl_err = SSL_get_error(ssl, ret);
  12787. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12788. err.backend_code = ERR_get_error();
  12789. }
  12790. return err;
  12791. }
  12792. inline TlsError accept(session_t session) {
  12793. if (!session) { return TlsError(); }
  12794. auto ssl = static_cast<SSL *>(session);
  12795. auto ret = SSL_accept(ssl);
  12796. TlsError err;
  12797. if (ret == 1) {
  12798. err.code = ErrorCode::Success;
  12799. } else {
  12800. auto ssl_err = SSL_get_error(ssl, ret);
  12801. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12802. err.backend_code = ERR_get_error();
  12803. }
  12804. return err;
  12805. }
  12806. inline bool connect_nonblocking(session_t session, socket_t sock,
  12807. time_t timeout_sec, time_t timeout_usec,
  12808. TlsError *err) {
  12809. if (!session) {
  12810. if (err) { err->code = ErrorCode::Fatal; }
  12811. return false;
  12812. }
  12813. auto ssl = static_cast<SSL *>(session);
  12814. auto bio = SSL_get_rbio(ssl);
  12815. // Set non-blocking mode for handshake
  12816. detail::set_nonblocking(sock, true);
  12817. if (bio) { BIO_set_nbio(bio, 1); }
  12818. auto cleanup = detail::scope_exit([&]() {
  12819. // Restore blocking mode after handshake
  12820. if (bio) { BIO_set_nbio(bio, 0); }
  12821. detail::set_nonblocking(sock, false);
  12822. });
  12823. auto res = 0;
  12824. while ((res = SSL_connect(ssl)) != 1) {
  12825. auto ssl_err = SSL_get_error(ssl, res);
  12826. switch (ssl_err) {
  12827. case SSL_ERROR_WANT_READ:
  12828. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  12829. continue;
  12830. }
  12831. break;
  12832. case SSL_ERROR_WANT_WRITE:
  12833. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  12834. continue;
  12835. }
  12836. break;
  12837. default: break;
  12838. }
  12839. if (err) {
  12840. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  12841. err->backend_code = ERR_get_error();
  12842. }
  12843. return false;
  12844. }
  12845. if (err) { err->code = ErrorCode::Success; }
  12846. return true;
  12847. }
  12848. inline bool accept_nonblocking(session_t session, socket_t sock,
  12849. time_t timeout_sec, time_t timeout_usec,
  12850. TlsError *err) {
  12851. if (!session) {
  12852. if (err) { err->code = ErrorCode::Fatal; }
  12853. return false;
  12854. }
  12855. auto ssl = static_cast<SSL *>(session);
  12856. auto bio = SSL_get_rbio(ssl);
  12857. // Set non-blocking mode for handshake
  12858. detail::set_nonblocking(sock, true);
  12859. if (bio) { BIO_set_nbio(bio, 1); }
  12860. auto cleanup = detail::scope_exit([&]() {
  12861. // Restore blocking mode after handshake
  12862. if (bio) { BIO_set_nbio(bio, 0); }
  12863. detail::set_nonblocking(sock, false);
  12864. });
  12865. auto res = 0;
  12866. while ((res = SSL_accept(ssl)) != 1) {
  12867. auto ssl_err = SSL_get_error(ssl, res);
  12868. switch (ssl_err) {
  12869. case SSL_ERROR_WANT_READ:
  12870. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  12871. continue;
  12872. }
  12873. break;
  12874. case SSL_ERROR_WANT_WRITE:
  12875. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  12876. continue;
  12877. }
  12878. break;
  12879. default: break;
  12880. }
  12881. if (err) {
  12882. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  12883. err->backend_code = ERR_get_error();
  12884. }
  12885. return false;
  12886. }
  12887. if (err) { err->code = ErrorCode::Success; }
  12888. return true;
  12889. }
  12890. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  12891. if (!session || !buf) {
  12892. err.code = ErrorCode::Fatal;
  12893. return -1;
  12894. }
  12895. auto ssl = static_cast<SSL *>(session);
  12896. constexpr auto max_len =
  12897. static_cast<size_t>((std::numeric_limits<int>::max)());
  12898. if (len > max_len) { len = max_len; }
  12899. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  12900. if (ret > 0) {
  12901. err.code = ErrorCode::Success;
  12902. return ret;
  12903. }
  12904. auto ssl_err = SSL_get_error(ssl, ret);
  12905. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12906. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  12907. return -1;
  12908. }
  12909. inline ssize_t write(session_t session, const void *buf, size_t len,
  12910. TlsError &err) {
  12911. if (!session || !buf) {
  12912. err.code = ErrorCode::Fatal;
  12913. return -1;
  12914. }
  12915. auto ssl = static_cast<SSL *>(session);
  12916. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  12917. if (ret > 0) {
  12918. err.code = ErrorCode::Success;
  12919. return ret;
  12920. }
  12921. auto ssl_err = SSL_get_error(ssl, ret);
  12922. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12923. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  12924. return -1;
  12925. }
  12926. inline int pending(const_session_t session) {
  12927. if (!session) return 0;
  12928. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  12929. }
  12930. inline void shutdown(session_t session, bool graceful) {
  12931. if (!session) return;
  12932. auto ssl = static_cast<SSL *>(session);
  12933. if (graceful) {
  12934. // First call sends close_notify
  12935. if (SSL_shutdown(ssl) == 0) {
  12936. // Second call waits for peer's close_notify
  12937. SSL_shutdown(ssl);
  12938. }
  12939. }
  12940. }
  12941. inline bool is_peer_closed(session_t session, socket_t sock) {
  12942. if (!session) return true;
  12943. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  12944. detail::set_nonblocking(sock, true);
  12945. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  12946. auto ssl = static_cast<SSL *>(session);
  12947. char buf;
  12948. auto ret = SSL_peek(ssl, &buf, 1);
  12949. if (ret > 0) return false;
  12950. auto err = SSL_get_error(ssl, ret);
  12951. return err == SSL_ERROR_ZERO_RETURN;
  12952. }
  12953. inline cert_t get_peer_cert(const_session_t session) {
  12954. if (!session) return nullptr;
  12955. return static_cast<cert_t>(SSL_get1_peer_certificate(
  12956. static_cast<SSL *>(const_cast<void *>(session))));
  12957. }
  12958. inline void free_cert(cert_t cert) {
  12959. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  12960. }
  12961. inline bool verify_hostname(cert_t cert, const char *hostname) {
  12962. if (!cert || !hostname) return false;
  12963. auto x509 = static_cast<X509 *>(cert);
  12964. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  12965. if (detail::is_ip_address(hostname)) {
  12966. return X509_check_ip_asc(x509, hostname, 0) == 1;
  12967. }
  12968. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  12969. }
  12970. inline uint64_t hostname_mismatch_code() {
  12971. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  12972. }
  12973. inline long get_verify_result(const_session_t session) {
  12974. if (!session) return X509_V_ERR_UNSPECIFIED;
  12975. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  12976. }
  12977. inline std::string get_cert_subject_cn(cert_t cert) {
  12978. if (!cert) return "";
  12979. auto x509 = static_cast<X509 *>(cert);
  12980. auto subject_name = X509_get_subject_name(x509);
  12981. if (!subject_name) return "";
  12982. char buf[256];
  12983. auto len =
  12984. X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf, sizeof(buf));
  12985. if (len < 0) return "";
  12986. return std::string(buf, static_cast<size_t>(len));
  12987. }
  12988. inline std::string get_cert_issuer_name(cert_t cert) {
  12989. if (!cert) return "";
  12990. auto x509 = static_cast<X509 *>(cert);
  12991. auto issuer_name = X509_get_issuer_name(x509);
  12992. if (!issuer_name) return "";
  12993. char buf[256];
  12994. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  12995. return std::string(buf);
  12996. }
  12997. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  12998. sans.clear();
  12999. if (!cert) return false;
  13000. auto x509 = static_cast<X509 *>(cert);
  13001. auto names = static_cast<GENERAL_NAMES *>(
  13002. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  13003. if (!names) return true; // No SANs is valid
  13004. auto count = sk_GENERAL_NAME_num(names);
  13005. for (int i = 0; i < count; i++) {
  13006. auto gen = sk_GENERAL_NAME_value(names, i);
  13007. if (!gen) continue;
  13008. SanEntry entry;
  13009. switch (gen->type) {
  13010. case GEN_DNS:
  13011. entry.type = SanType::DNS;
  13012. if (gen->d.dNSName) {
  13013. entry.value = std::string(
  13014. reinterpret_cast<const char *>(
  13015. ASN1_STRING_get0_data(gen->d.dNSName)),
  13016. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  13017. }
  13018. break;
  13019. case GEN_IPADD:
  13020. entry.type = SanType::IP;
  13021. if (gen->d.iPAddress) {
  13022. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  13023. auto len = ASN1_STRING_length(gen->d.iPAddress);
  13024. if (len == 4) {
  13025. // IPv4
  13026. char buf[INET_ADDRSTRLEN];
  13027. inet_ntop(AF_INET, data, buf, sizeof(buf));
  13028. entry.value = buf;
  13029. } else if (len == 16) {
  13030. // IPv6
  13031. char buf[INET6_ADDRSTRLEN];
  13032. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  13033. entry.value = buf;
  13034. }
  13035. }
  13036. break;
  13037. case GEN_EMAIL:
  13038. entry.type = SanType::EMAIL;
  13039. if (gen->d.rfc822Name) {
  13040. entry.value = std::string(
  13041. reinterpret_cast<const char *>(
  13042. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  13043. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  13044. }
  13045. break;
  13046. case GEN_URI:
  13047. entry.type = SanType::URI;
  13048. if (gen->d.uniformResourceIdentifier) {
  13049. entry.value = std::string(
  13050. reinterpret_cast<const char *>(
  13051. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  13052. static_cast<size_t>(
  13053. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  13054. }
  13055. break;
  13056. default: entry.type = SanType::OTHER; break;
  13057. }
  13058. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  13059. }
  13060. GENERAL_NAMES_free(names);
  13061. return true;
  13062. }
  13063. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  13064. time_t &not_after) {
  13065. if (!cert) return false;
  13066. auto x509 = static_cast<X509 *>(cert);
  13067. auto nb = X509_get0_notBefore(x509);
  13068. auto na = X509_get0_notAfter(x509);
  13069. if (!nb || !na) return false;
  13070. ASN1_TIME *epoch = ASN1_TIME_new();
  13071. if (!epoch) return false;
  13072. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  13073. if (!ASN1_TIME_set(epoch, 0)) return false;
  13074. int pday, psec;
  13075. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  13076. not_before = 86400 * (time_t)pday + psec;
  13077. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  13078. not_after = 86400 * (time_t)pday + psec;
  13079. return true;
  13080. }
  13081. inline std::string get_cert_serial(cert_t cert) {
  13082. if (!cert) return "";
  13083. auto x509 = static_cast<X509 *>(cert);
  13084. auto serial = X509_get_serialNumber(x509);
  13085. if (!serial) return "";
  13086. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  13087. if (!bn) return "";
  13088. auto hex = BN_bn2hex(bn);
  13089. BN_free(bn);
  13090. if (!hex) return "";
  13091. std::string result(hex);
  13092. OPENSSL_free(hex);
  13093. return result;
  13094. }
  13095. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  13096. if (!cert) return false;
  13097. auto x509 = static_cast<X509 *>(cert);
  13098. auto len = i2d_X509(x509, nullptr);
  13099. if (len < 0) return false;
  13100. der.resize(static_cast<size_t>(len));
  13101. auto p = der.data();
  13102. i2d_X509(x509, &p);
  13103. return true;
  13104. }
  13105. inline const char *get_sni(const_session_t session) {
  13106. if (!session) return nullptr;
  13107. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  13108. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13109. }
  13110. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  13111. inline uint64_t get_error() { return ERR_get_error(); }
  13112. inline std::string error_string(uint64_t code) {
  13113. char buf[256];
  13114. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  13115. return std::string(buf);
  13116. }
  13117. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  13118. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  13119. if (!mem) { return nullptr; }
  13120. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  13121. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  13122. if (!inf) { return nullptr; }
  13123. auto store = X509_STORE_new();
  13124. if (store) {
  13125. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  13126. auto itmp = sk_X509_INFO_value(inf, i);
  13127. if (!itmp) { continue; }
  13128. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  13129. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  13130. }
  13131. }
  13132. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  13133. return static_cast<ca_store_t>(store);
  13134. }
  13135. inline void free_ca_store(ca_store_t store) {
  13136. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  13137. }
  13138. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  13139. if (!ctx || !store) { return false; }
  13140. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13141. auto x509_store = static_cast<X509_STORE *>(store);
  13142. // Check if same store is already set
  13143. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  13144. // SSL_CTX_set_cert_store takes ownership and frees the old store
  13145. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  13146. return true;
  13147. }
  13148. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  13149. certs.clear();
  13150. if (!ctx) { return 0; }
  13151. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13152. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13153. if (!store) { return 0; }
  13154. auto objs = X509_STORE_get0_objects(store);
  13155. if (!objs) { return 0; }
  13156. auto count = sk_X509_OBJECT_num(objs);
  13157. for (decltype(count) i = 0; i < count; i++) {
  13158. auto obj = sk_X509_OBJECT_value(objs, i);
  13159. if (!obj) { continue; }
  13160. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13161. auto x509 = X509_OBJECT_get0_X509(obj);
  13162. if (x509) {
  13163. // Increment reference count so caller can free it
  13164. X509_up_ref(x509);
  13165. certs.push_back(static_cast<cert_t>(x509));
  13166. }
  13167. }
  13168. }
  13169. return certs.size();
  13170. }
  13171. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  13172. std::vector<std::string> names;
  13173. if (!ctx) { return names; }
  13174. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13175. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  13176. if (!store) { return names; }
  13177. auto objs = X509_STORE_get0_objects(store);
  13178. if (!objs) { return names; }
  13179. auto count = sk_X509_OBJECT_num(objs);
  13180. for (decltype(count) i = 0; i < count; i++) {
  13181. auto obj = sk_X509_OBJECT_value(objs, i);
  13182. if (!obj) { continue; }
  13183. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  13184. auto x509 = X509_OBJECT_get0_X509(obj);
  13185. if (x509) {
  13186. auto subject = X509_get_subject_name(x509);
  13187. if (subject) {
  13188. char buf[512];
  13189. X509_NAME_oneline(subject, buf, sizeof(buf));
  13190. names.push_back(buf);
  13191. }
  13192. }
  13193. }
  13194. }
  13195. return names;
  13196. }
  13197. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  13198. const char *key_pem, const char *password) {
  13199. if (!ctx || !cert_pem || !key_pem) { return false; }
  13200. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13201. // Load certificate from PEM
  13202. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  13203. if (!cert_bio) { return false; }
  13204. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  13205. BIO_free(cert_bio);
  13206. if (!cert) { return false; }
  13207. // Load private key from PEM
  13208. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  13209. if (!key_bio) {
  13210. X509_free(cert);
  13211. return false;
  13212. }
  13213. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  13214. password ? const_cast<char *>(password)
  13215. : nullptr);
  13216. BIO_free(key_bio);
  13217. if (!key) {
  13218. X509_free(cert);
  13219. return false;
  13220. }
  13221. // Update certificate and key
  13222. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  13223. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  13224. X509_free(cert);
  13225. EVP_PKEY_free(key);
  13226. return ret;
  13227. }
  13228. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  13229. if (!ctx || !ca_pem) { return false; }
  13230. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13231. // Create new X509_STORE from PEM
  13232. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  13233. if (!store) { return false; }
  13234. // SSL_CTX_set_cert_store takes ownership
  13235. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  13236. // Set client CA list for client certificate request
  13237. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  13238. if (ca_list) {
  13239. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  13240. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  13241. }
  13242. return true;
  13243. }
  13244. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  13245. if (!ctx) { return false; }
  13246. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13247. impl::get_verify_callback() = std::move(callback);
  13248. if (impl::get_verify_callback()) {
  13249. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  13250. } else {
  13251. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  13252. }
  13253. return true;
  13254. }
  13255. inline long get_verify_error(const_session_t session) {
  13256. if (!session) { return -1; }
  13257. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  13258. return SSL_get_verify_result(ssl);
  13259. }
  13260. inline std::string verify_error_string(long error_code) {
  13261. if (error_code == X509_V_OK) { return ""; }
  13262. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  13263. return str ? str : "unknown error";
  13264. }
  13265. namespace impl {
  13266. // OpenSSL-specific helpers for public API wrappers
  13267. inline ctx_t create_server_context_from_x509(X509 *cert, EVP_PKEY *key,
  13268. X509_STORE *client_ca_store,
  13269. int &out_error) {
  13270. out_error = 0;
  13271. auto cert_pem = x509_to_pem(cert);
  13272. auto key_pem = evp_pkey_to_pem(key);
  13273. if (cert_pem.empty() || key_pem.empty()) {
  13274. out_error = static_cast<int>(ERR_get_error());
  13275. return nullptr;
  13276. }
  13277. auto ctx = create_server_context();
  13278. if (!ctx) {
  13279. out_error = static_cast<int>(get_error());
  13280. return nullptr;
  13281. }
  13282. if (!set_server_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr)) {
  13283. out_error = static_cast<int>(get_error());
  13284. free_context(ctx);
  13285. return nullptr;
  13286. }
  13287. if (client_ca_store) {
  13288. // Set cert store for verification (SSL_CTX_set_cert_store takes ownership)
  13289. SSL_CTX_set_cert_store(static_cast<SSL_CTX *>(ctx), client_ca_store);
  13290. // Extract and set client CA list directly from store (more efficient than
  13291. // PEM conversion)
  13292. auto ca_list = extract_client_ca_list_from_store(client_ca_store);
  13293. if (ca_list) {
  13294. SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), ca_list);
  13295. }
  13296. set_verify_client(ctx, true);
  13297. }
  13298. return ctx;
  13299. }
  13300. inline void update_server_certs_from_x509(ctx_t ctx, X509 *cert, EVP_PKEY *key,
  13301. X509_STORE *client_ca_store) {
  13302. auto cert_pem = x509_to_pem(cert);
  13303. auto key_pem = evp_pkey_to_pem(key);
  13304. if (!cert_pem.empty() && !key_pem.empty()) {
  13305. update_server_cert(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr);
  13306. }
  13307. if (client_ca_store) {
  13308. auto ca_pem = x509_store_to_pem(client_ca_store);
  13309. if (!ca_pem.empty()) { update_server_client_ca(ctx, ca_pem.c_str()); }
  13310. X509_STORE_free(client_ca_store);
  13311. }
  13312. }
  13313. inline ctx_t create_client_context_from_x509(X509 *cert, EVP_PKEY *key,
  13314. const char *password,
  13315. unsigned long &out_error) {
  13316. out_error = 0;
  13317. auto ctx = create_client_context();
  13318. if (!ctx) {
  13319. out_error = static_cast<unsigned long>(get_error());
  13320. return nullptr;
  13321. }
  13322. if (cert && key) {
  13323. auto cert_pem = x509_to_pem(cert);
  13324. auto key_pem = evp_pkey_to_pem(key);
  13325. if (cert_pem.empty() || key_pem.empty()) {
  13326. out_error = ERR_get_error();
  13327. free_context(ctx);
  13328. return nullptr;
  13329. }
  13330. if (!set_client_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  13331. password)) {
  13332. out_error = static_cast<unsigned long>(get_error());
  13333. free_context(ctx);
  13334. return nullptr;
  13335. }
  13336. }
  13337. return ctx;
  13338. }
  13339. } // namespace impl
  13340. } // namespace tls
  13341. // ClientImpl::set_ca_cert_store - defined here to use
  13342. // tls::impl::x509_store_to_pem Deprecated: converts X509_STORE to PEM and
  13343. // stores for redirect transfer
  13344. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  13345. if (ca_cert_store) {
  13346. ca_cert_pem_ = tls::impl::x509_store_to_pem(ca_cert_store);
  13347. }
  13348. }
  13349. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  13350. X509_STORE *client_ca_cert_store) {
  13351. ctx_ = tls::impl::create_server_context_from_x509(
  13352. cert, private_key, client_ca_cert_store, last_ssl_error_);
  13353. }
  13354. inline SSLServer::SSLServer(
  13355. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  13356. // Use abstract API to create context
  13357. ctx_ = tls::create_server_context();
  13358. if (ctx_) {
  13359. // Pass to OpenSSL-specific callback (ctx_ is SSL_CTX* internally)
  13360. auto ssl_ctx = static_cast<SSL_CTX *>(ctx_);
  13361. if (!setup_ssl_ctx_callback(*ssl_ctx)) {
  13362. tls::free_context(ctx_);
  13363. ctx_ = nullptr;
  13364. }
  13365. }
  13366. }
  13367. inline SSL_CTX *SSLServer::ssl_context() const {
  13368. return static_cast<SSL_CTX *>(ctx_);
  13369. }
  13370. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  13371. X509_STORE *client_ca_cert_store) {
  13372. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13373. tls::impl::update_server_certs_from_x509(ctx_, cert, private_key,
  13374. client_ca_cert_store);
  13375. }
  13376. inline SSLClient::SSLClient(const std::string &host, int port,
  13377. X509 *client_cert, EVP_PKEY *client_key,
  13378. const std::string &private_key_password)
  13379. : ClientImpl(host, port) {
  13380. const char *password =
  13381. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13382. ctx_ = tls::impl::create_client_context_from_x509(
  13383. client_cert, client_key, password, last_backend_error_);
  13384. }
  13385. inline long SSLClient::get_verify_result() const { return verify_result_; }
  13386. inline void SSLClient::set_server_certificate_verifier(
  13387. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  13388. // Wrap SSL* callback into backend-independent session_verifier_
  13389. auto v = std::make_shared<std::function<SSLVerifierResponse(SSL *)>>(
  13390. std::move(verifier));
  13391. session_verifier_ = [v](tls::session_t session) {
  13392. return (*v)(static_cast<SSL *>(session));
  13393. };
  13394. }
  13395. inline SSL_CTX *SSLClient::ssl_context() const {
  13396. return static_cast<SSL_CTX *>(ctx_);
  13397. }
  13398. inline bool SSLClient::verify_host(X509 *server_cert) const {
  13399. /* Quote from RFC2818 section 3.1 "Server Identity"
  13400. If a subjectAltName extension of type dNSName is present, that MUST
  13401. be used as the identity. Otherwise, the (most specific) Common Name
  13402. field in the Subject field of the certificate MUST be used. Although
  13403. the use of the Common Name is existing practice, it is deprecated and
  13404. Certification Authorities are encouraged to use the dNSName instead.
  13405. Matching is performed using the matching rules specified by
  13406. [RFC2459]. If more than one identity of a given type is present in
  13407. the certificate (e.g., more than one dNSName name, a match in any one
  13408. of the set is considered acceptable.) Names may contain the wildcard
  13409. character * which is considered to match any single domain name
  13410. component or component fragment. E.g., *.a.com matches foo.a.com but
  13411. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  13412. In some cases, the URI is specified as an IP address rather than a
  13413. hostname. In this case, the iPAddress subjectAltName must be present
  13414. in the certificate and must exactly match the IP in the URI.
  13415. */
  13416. return verify_host_with_subject_alt_name(server_cert) ||
  13417. verify_host_with_common_name(server_cert);
  13418. }
  13419. inline bool
  13420. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  13421. auto ret = false;
  13422. auto type = GEN_DNS;
  13423. struct in6_addr addr6 = {};
  13424. struct in_addr addr = {};
  13425. size_t addr_len = 0;
  13426. #ifndef __MINGW32__
  13427. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  13428. type = GEN_IPADD;
  13429. addr_len = sizeof(struct in6_addr);
  13430. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  13431. type = GEN_IPADD;
  13432. addr_len = sizeof(struct in_addr);
  13433. }
  13434. #endif
  13435. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  13436. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  13437. if (alt_names) {
  13438. auto dsn_matched = false;
  13439. auto ip_matched = false;
  13440. auto count = sk_GENERAL_NAME_num(alt_names);
  13441. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  13442. auto val = sk_GENERAL_NAME_value(alt_names, i);
  13443. if (!val || val->type != type) { continue; }
  13444. auto name =
  13445. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  13446. if (name == nullptr) { continue; }
  13447. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  13448. switch (type) {
  13449. case GEN_DNS:
  13450. dsn_matched =
  13451. detail::match_hostname(std::string(name, name_len), host_);
  13452. break;
  13453. case GEN_IPADD:
  13454. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  13455. ip_matched = true;
  13456. }
  13457. break;
  13458. }
  13459. }
  13460. if (dsn_matched || ip_matched) { ret = true; }
  13461. }
  13462. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  13463. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  13464. return ret;
  13465. }
  13466. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  13467. const auto subject_name = X509_get_subject_name(server_cert);
  13468. if (subject_name != nullptr) {
  13469. char name[BUFSIZ];
  13470. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  13471. name, sizeof(name));
  13472. if (name_len != -1) {
  13473. return detail::match_hostname(
  13474. std::string(name, static_cast<size_t>(name_len)), host_);
  13475. }
  13476. }
  13477. return false;
  13478. }
  13479. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  13480. /*
  13481. * Group 9: TLS abstraction layer - Mbed TLS backend
  13482. */
  13483. /*
  13484. * Mbed TLS Backend Implementation
  13485. */
  13486. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13487. namespace tls {
  13488. namespace impl {
  13489. // Mbed TLS session wrapper
  13490. struct MbedTlsSession {
  13491. mbedtls_ssl_context ssl;
  13492. socket_t sock = INVALID_SOCKET;
  13493. std::string hostname; // For client: set via set_sni
  13494. std::string sni_hostname; // For server: received from client via SNI callback
  13495. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  13496. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  13497. MbedTlsSession(const MbedTlsSession &) = delete;
  13498. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  13499. };
  13500. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  13501. // queue)
  13502. inline int &mbedtls_last_error() {
  13503. static thread_local int err = 0;
  13504. return err;
  13505. }
  13506. // Helper to map Mbed TLS error to ErrorCode
  13507. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  13508. if (ret == 0) { return ErrorCode::Success; }
  13509. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  13510. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  13511. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  13512. return ErrorCode::PeerClosed;
  13513. }
  13514. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  13515. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  13516. out_errno = errno;
  13517. return ErrorCode::SyscallError;
  13518. }
  13519. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  13520. return ErrorCode::CertVerifyFailed;
  13521. }
  13522. return ErrorCode::Fatal;
  13523. }
  13524. // BIO-like send callback for Mbed TLS
  13525. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  13526. size_t len) {
  13527. auto sock = *static_cast<socket_t *>(ctx);
  13528. #ifdef _WIN32
  13529. auto ret =
  13530. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  13531. if (ret == SOCKET_ERROR) {
  13532. int err = WSAGetLastError();
  13533. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  13534. return MBEDTLS_ERR_NET_SEND_FAILED;
  13535. }
  13536. #else
  13537. auto ret = send(sock, buf, len, 0);
  13538. if (ret < 0) {
  13539. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  13540. return MBEDTLS_ERR_SSL_WANT_WRITE;
  13541. }
  13542. return MBEDTLS_ERR_NET_SEND_FAILED;
  13543. }
  13544. #endif
  13545. return static_cast<int>(ret);
  13546. }
  13547. // BIO-like recv callback for Mbed TLS
  13548. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  13549. auto sock = *static_cast<socket_t *>(ctx);
  13550. #ifdef _WIN32
  13551. auto ret =
  13552. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  13553. if (ret == SOCKET_ERROR) {
  13554. int err = WSAGetLastError();
  13555. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  13556. return MBEDTLS_ERR_NET_RECV_FAILED;
  13557. }
  13558. #else
  13559. auto ret = recv(sock, buf, len, 0);
  13560. if (ret < 0) {
  13561. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  13562. return MBEDTLS_ERR_SSL_WANT_READ;
  13563. }
  13564. return MBEDTLS_ERR_NET_RECV_FAILED;
  13565. }
  13566. #endif
  13567. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  13568. return static_cast<int>(ret);
  13569. }
  13570. // MbedTlsContext constructor/destructor implementations
  13571. inline MbedTlsContext::MbedTlsContext() {
  13572. mbedtls_ssl_config_init(&conf);
  13573. mbedtls_entropy_init(&entropy);
  13574. mbedtls_ctr_drbg_init(&ctr_drbg);
  13575. mbedtls_x509_crt_init(&ca_chain);
  13576. mbedtls_x509_crt_init(&own_cert);
  13577. mbedtls_pk_init(&own_key);
  13578. }
  13579. inline MbedTlsContext::~MbedTlsContext() {
  13580. mbedtls_pk_free(&own_key);
  13581. mbedtls_x509_crt_free(&own_cert);
  13582. mbedtls_x509_crt_free(&ca_chain);
  13583. mbedtls_ctr_drbg_free(&ctr_drbg);
  13584. mbedtls_entropy_free(&entropy);
  13585. mbedtls_ssl_config_free(&conf);
  13586. }
  13587. // Thread-local storage for SNI captured during handshake
  13588. // This is needed because the SNI callback doesn't have a way to pass
  13589. // session-specific data before the session is fully set up
  13590. inline std::string &mbedpending_sni() {
  13591. static thread_local std::string sni;
  13592. return sni;
  13593. }
  13594. // SNI callback for Mbed TLS server to capture client's SNI hostname
  13595. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  13596. const unsigned char *name, size_t name_len) {
  13597. (void)p_ctx;
  13598. (void)ssl;
  13599. // Store SNI name in thread-local storage
  13600. // It will be retrieved and stored in the session after handshake
  13601. if (name && name_len > 0) {
  13602. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  13603. } else {
  13604. mbedpending_sni().clear();
  13605. }
  13606. return 0; // Accept any SNI
  13607. }
  13608. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  13609. int cert_depth, uint32_t *flags);
  13610. // Check if a string is an IPv4 address
  13611. inline bool is_ipv4_address(const std::string &str) {
  13612. int dots = 0;
  13613. for (char c : str) {
  13614. if (c == '.') {
  13615. dots++;
  13616. } else if (!isdigit(static_cast<unsigned char>(c))) {
  13617. return false;
  13618. }
  13619. }
  13620. return dots == 3;
  13621. }
  13622. // Parse IPv4 address string to bytes
  13623. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  13624. int parts[4];
  13625. if (sscanf(str.c_str(), "%d.%d.%d.%d", &parts[0], &parts[1], &parts[2],
  13626. &parts[3]) != 4) {
  13627. return false;
  13628. }
  13629. for (int i = 0; i < 4; i++) {
  13630. if (parts[i] < 0 || parts[i] > 255) return false;
  13631. out[i] = static_cast<unsigned char>(parts[i]);
  13632. }
  13633. return true;
  13634. }
  13635. // MbedTLS verify callback wrapper
  13636. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  13637. int cert_depth, uint32_t *flags) {
  13638. auto &callback = get_verify_callback();
  13639. if (!callback) { return 0; } // Continue with default verification
  13640. // data points to the MbedTlsSession
  13641. auto *session = static_cast<MbedTlsSession *>(data);
  13642. // Build context
  13643. VerifyContext verify_ctx;
  13644. verify_ctx.session = static_cast<session_t>(session);
  13645. verify_ctx.cert = static_cast<cert_t>(crt);
  13646. verify_ctx.depth = cert_depth;
  13647. verify_ctx.preverify_ok = (*flags == 0);
  13648. verify_ctx.error_code = static_cast<long>(*flags);
  13649. // Convert Mbed TLS flags to error string
  13650. static thread_local char error_buf[256];
  13651. if (*flags != 0) {
  13652. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  13653. verify_ctx.error_string = error_buf;
  13654. } else {
  13655. verify_ctx.error_string = nullptr;
  13656. }
  13657. bool accepted = callback(verify_ctx);
  13658. if (accepted) {
  13659. *flags = 0; // Clear all error flags
  13660. return 0;
  13661. }
  13662. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  13663. }
  13664. } // namespace impl
  13665. inline ctx_t create_client_context() {
  13666. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  13667. if (!ctx) { return nullptr; }
  13668. ctx->is_server = false;
  13669. // Seed the random number generator
  13670. const char *pers = "httplib_client";
  13671. int ret = mbedtls_ctr_drbg_seed(
  13672. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  13673. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  13674. if (ret != 0) {
  13675. impl::mbedtls_last_error() = ret;
  13676. delete ctx;
  13677. return nullptr;
  13678. }
  13679. // Set up SSL config for client
  13680. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  13681. MBEDTLS_SSL_TRANSPORT_STREAM,
  13682. MBEDTLS_SSL_PRESET_DEFAULT);
  13683. if (ret != 0) {
  13684. impl::mbedtls_last_error() = ret;
  13685. delete ctx;
  13686. return nullptr;
  13687. }
  13688. // Set random number generator
  13689. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  13690. // Default: verify peer certificate
  13691. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13692. // Set minimum TLS version to 1.2
  13693. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13694. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13695. #else
  13696. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13697. MBEDTLS_SSL_MINOR_VERSION_3);
  13698. #endif
  13699. return static_cast<ctx_t>(ctx);
  13700. }
  13701. inline ctx_t create_server_context() {
  13702. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  13703. if (!ctx) { return nullptr; }
  13704. ctx->is_server = true;
  13705. // Seed the random number generator
  13706. const char *pers = "httplib_server";
  13707. int ret = mbedtls_ctr_drbg_seed(
  13708. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  13709. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  13710. if (ret != 0) {
  13711. impl::mbedtls_last_error() = ret;
  13712. delete ctx;
  13713. return nullptr;
  13714. }
  13715. // Set up SSL config for server
  13716. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  13717. MBEDTLS_SSL_TRANSPORT_STREAM,
  13718. MBEDTLS_SSL_PRESET_DEFAULT);
  13719. if (ret != 0) {
  13720. impl::mbedtls_last_error() = ret;
  13721. delete ctx;
  13722. return nullptr;
  13723. }
  13724. // Set random number generator
  13725. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  13726. // Default: don't verify client
  13727. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  13728. // Set minimum TLS version to 1.2
  13729. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13730. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13731. #else
  13732. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13733. MBEDTLS_SSL_MINOR_VERSION_3);
  13734. #endif
  13735. // Set SNI callback to capture client's SNI hostname
  13736. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  13737. return static_cast<ctx_t>(ctx);
  13738. }
  13739. inline void free_context(ctx_t ctx) {
  13740. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  13741. }
  13742. inline bool set_min_version(ctx_t ctx, Version version) {
  13743. if (!ctx) { return false; }
  13744. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13745. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13746. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  13747. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  13748. if (version >= Version::TLS1_3) {
  13749. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  13750. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  13751. #endif
  13752. }
  13753. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  13754. #else
  13755. // Mbed TLS 2.x uses major/minor version numbers
  13756. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  13757. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  13758. if (version >= Version::TLS1_3) {
  13759. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  13760. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  13761. #else
  13762. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  13763. #endif
  13764. }
  13765. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  13766. #endif
  13767. return true;
  13768. }
  13769. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  13770. if (!ctx || !pem) { return false; }
  13771. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13772. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  13773. // Add null terminator if not present
  13774. std::string pem_str(pem, len);
  13775. int ret = mbedtls_x509_crt_parse(
  13776. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  13777. pem_str.size() + 1);
  13778. if (ret != 0) {
  13779. impl::mbedtls_last_error() = ret;
  13780. return false;
  13781. }
  13782. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13783. return true;
  13784. }
  13785. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  13786. if (!ctx || !file_path) { return false; }
  13787. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13788. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  13789. if (ret != 0) {
  13790. impl::mbedtls_last_error() = ret;
  13791. return false;
  13792. }
  13793. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13794. return true;
  13795. }
  13796. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  13797. if (!ctx || !dir_path) { return false; }
  13798. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13799. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  13800. if (ret < 0) { // Returns number of certs on success, negative on error
  13801. impl::mbedtls_last_error() = ret;
  13802. return false;
  13803. }
  13804. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13805. return true;
  13806. }
  13807. inline bool load_system_certs(ctx_t ctx) {
  13808. if (!ctx) { return false; }
  13809. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13810. bool loaded = false;
  13811. #ifdef _WIN32
  13812. // Load from Windows certificate store (ROOT and CA)
  13813. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  13814. for (auto store_name : store_names) {
  13815. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  13816. if (hStore) {
  13817. PCCERT_CONTEXT pContext = nullptr;
  13818. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  13819. nullptr) {
  13820. int ret = mbedtls_x509_crt_parse_der(
  13821. &mctx->ca_chain, pContext->pbCertEncoded, pContext->cbCertEncoded);
  13822. if (ret == 0) { loaded = true; }
  13823. }
  13824. CertCloseStore(hStore, 0);
  13825. }
  13826. }
  13827. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  13828. // Load from macOS Keychain
  13829. CFArrayRef certs = nullptr;
  13830. OSStatus status = SecTrustCopyAnchorCertificates(&certs);
  13831. if (status == errSecSuccess && certs) {
  13832. CFIndex count = CFArrayGetCount(certs);
  13833. for (CFIndex i = 0; i < count; i++) {
  13834. SecCertificateRef cert =
  13835. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  13836. CFDataRef data = SecCertificateCopyData(cert);
  13837. if (data) {
  13838. int ret = mbedtls_x509_crt_parse_der(
  13839. &mctx->ca_chain, CFDataGetBytePtr(data),
  13840. static_cast<size_t>(CFDataGetLength(data)));
  13841. if (ret == 0) { loaded = true; }
  13842. CFRelease(data);
  13843. }
  13844. }
  13845. CFRelease(certs);
  13846. }
  13847. #else
  13848. // Try common CA certificate locations on Linux/Unix
  13849. static const char *ca_paths[] = {
  13850. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  13851. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  13852. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  13853. "/etc/pki/tls/cacert.pem", // OpenELEC
  13854. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  13855. nullptr};
  13856. for (const char **path = ca_paths; *path; ++path) {
  13857. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path);
  13858. if (ret >= 0) {
  13859. loaded = true;
  13860. break;
  13861. }
  13862. }
  13863. // Also try the CA directory
  13864. if (!loaded) {
  13865. static const char *ca_dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  13866. "/etc/pki/tls/certs", // RHEL/CentOS
  13867. "/usr/share/ca-certificates", nullptr};
  13868. for (const char **dir = ca_dirs; *dir; ++dir) {
  13869. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir);
  13870. if (ret >= 0) {
  13871. loaded = true;
  13872. break;
  13873. }
  13874. }
  13875. }
  13876. #endif
  13877. if (loaded) {
  13878. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13879. }
  13880. return loaded;
  13881. }
  13882. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  13883. const char *password) {
  13884. if (!ctx || !cert || !key) { return false; }
  13885. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13886. // Parse certificate
  13887. std::string cert_str(cert);
  13888. int ret = mbedtls_x509_crt_parse(
  13889. &mctx->own_cert,
  13890. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  13891. cert_str.size() + 1);
  13892. if (ret != 0) {
  13893. impl::mbedtls_last_error() = ret;
  13894. return false;
  13895. }
  13896. // Parse private key
  13897. std::string key_str(key);
  13898. const unsigned char *pwd =
  13899. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  13900. size_t pwd_len = password ? strlen(password) : 0;
  13901. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13902. ret = mbedtls_pk_parse_key(
  13903. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  13904. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  13905. &mctx->ctr_drbg);
  13906. #else
  13907. ret = mbedtls_pk_parse_key(
  13908. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  13909. key_str.size() + 1, pwd, pwd_len);
  13910. #endif
  13911. if (ret != 0) {
  13912. impl::mbedtls_last_error() = ret;
  13913. return false;
  13914. }
  13915. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  13916. if (ret != 0) {
  13917. impl::mbedtls_last_error() = ret;
  13918. return false;
  13919. }
  13920. return true;
  13921. }
  13922. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  13923. const char *key_path, const char *password) {
  13924. if (!ctx || !cert_path || !key_path) { return false; }
  13925. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13926. // Parse certificate file
  13927. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  13928. if (ret != 0) {
  13929. impl::mbedtls_last_error() = ret;
  13930. return false;
  13931. }
  13932. // Parse private key file
  13933. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13934. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  13935. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  13936. #else
  13937. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  13938. #endif
  13939. if (ret != 0) {
  13940. impl::mbedtls_last_error() = ret;
  13941. return false;
  13942. }
  13943. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  13944. if (ret != 0) {
  13945. impl::mbedtls_last_error() = ret;
  13946. return false;
  13947. }
  13948. return true;
  13949. }
  13950. inline void set_verify_client(ctx_t ctx, bool require) {
  13951. if (!ctx) { return; }
  13952. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13953. mctx->verify_client = require;
  13954. if (require) {
  13955. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13956. } else {
  13957. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  13958. // is called (matching OpenSSL behavior). Otherwise use NONE.
  13959. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  13960. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  13961. : MBEDTLS_SSL_VERIFY_NONE);
  13962. }
  13963. }
  13964. inline session_t create_session(ctx_t ctx, socket_t sock) {
  13965. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  13966. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13967. auto session = new (std::nothrow) impl::MbedTlsSession();
  13968. if (!session) { return nullptr; }
  13969. session->sock = sock;
  13970. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  13971. if (ret != 0) {
  13972. impl::mbedtls_last_error() = ret;
  13973. delete session;
  13974. return nullptr;
  13975. }
  13976. // Set BIO callbacks
  13977. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  13978. impl::mbedtls_net_recv_cb, nullptr);
  13979. // Set per-session verify callback with session pointer if callback is
  13980. // registered
  13981. if (mctx->has_verify_callback) {
  13982. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  13983. session);
  13984. }
  13985. return static_cast<session_t>(session);
  13986. }
  13987. inline void free_session(session_t session) {
  13988. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  13989. }
  13990. inline bool set_sni(session_t session, const char *hostname) {
  13991. if (!session || !hostname) { return false; }
  13992. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13993. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  13994. if (ret != 0) {
  13995. impl::mbedtls_last_error() = ret;
  13996. return false;
  13997. }
  13998. msession->hostname = hostname;
  13999. return true;
  14000. }
  14001. inline bool set_hostname(session_t session, const char *hostname) {
  14002. // In Mbed TLS, set_hostname also sets up hostname verification
  14003. return set_sni(session, hostname);
  14004. }
  14005. inline TlsError connect(session_t session) {
  14006. TlsError err;
  14007. if (!session) {
  14008. err.code = ErrorCode::Fatal;
  14009. return err;
  14010. }
  14011. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14012. int ret = mbedtls_ssl_handshake(&msession->ssl);
  14013. if (ret == 0) {
  14014. err.code = ErrorCode::Success;
  14015. } else {
  14016. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  14017. err.backend_code = static_cast<uint64_t>(-ret);
  14018. impl::mbedtls_last_error() = ret;
  14019. }
  14020. return err;
  14021. }
  14022. inline TlsError accept(session_t session) {
  14023. // Same as connect for Mbed TLS - handshake works for both client and server
  14024. auto result = connect(session);
  14025. // After successful handshake, capture SNI from thread-local storage
  14026. if (result.code == ErrorCode::Success && 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 bool connect_nonblocking(session_t session, socket_t sock,
  14034. time_t timeout_sec, time_t timeout_usec,
  14035. TlsError *err) {
  14036. if (!session) {
  14037. if (err) { err->code = ErrorCode::Fatal; }
  14038. return false;
  14039. }
  14040. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14041. // Set socket to non-blocking mode
  14042. detail::set_nonblocking(sock, true);
  14043. auto cleanup =
  14044. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14045. int ret;
  14046. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  14047. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  14048. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14049. continue;
  14050. }
  14051. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  14052. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14053. continue;
  14054. }
  14055. }
  14056. // TlsError or timeout
  14057. if (err) {
  14058. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  14059. err->backend_code = static_cast<uint64_t>(-ret);
  14060. }
  14061. impl::mbedtls_last_error() = ret;
  14062. return false;
  14063. }
  14064. if (err) { err->code = ErrorCode::Success; }
  14065. return true;
  14066. }
  14067. inline bool accept_nonblocking(session_t session, socket_t sock,
  14068. time_t timeout_sec, time_t timeout_usec,
  14069. TlsError *err) {
  14070. // Same implementation as connect for Mbed TLS
  14071. bool result =
  14072. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  14073. // After successful handshake, capture SNI from thread-local storage
  14074. if (result && session) {
  14075. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14076. msession->sni_hostname = std::move(impl::mbedpending_sni());
  14077. impl::mbedpending_sni().clear();
  14078. }
  14079. return result;
  14080. }
  14081. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14082. if (!session || !buf) {
  14083. err.code = ErrorCode::Fatal;
  14084. return -1;
  14085. }
  14086. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14087. int ret =
  14088. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  14089. if (ret > 0) {
  14090. err.code = ErrorCode::Success;
  14091. return static_cast<ssize_t>(ret);
  14092. }
  14093. if (ret == 0) {
  14094. err.code = ErrorCode::PeerClosed;
  14095. return 0;
  14096. }
  14097. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  14098. err.backend_code = static_cast<uint64_t>(-ret);
  14099. impl::mbedtls_last_error() = ret;
  14100. return -1;
  14101. }
  14102. inline ssize_t write(session_t session, const void *buf, size_t len,
  14103. TlsError &err) {
  14104. if (!session || !buf) {
  14105. err.code = ErrorCode::Fatal;
  14106. return -1;
  14107. }
  14108. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14109. int ret = mbedtls_ssl_write(&msession->ssl,
  14110. static_cast<const unsigned char *>(buf), len);
  14111. if (ret > 0) {
  14112. err.code = ErrorCode::Success;
  14113. return static_cast<ssize_t>(ret);
  14114. }
  14115. if (ret == 0) {
  14116. err.code = ErrorCode::PeerClosed;
  14117. return 0;
  14118. }
  14119. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  14120. err.backend_code = static_cast<uint64_t>(-ret);
  14121. impl::mbedtls_last_error() = ret;
  14122. return -1;
  14123. }
  14124. inline int pending(const_session_t session) {
  14125. if (!session) { return 0; }
  14126. auto msession =
  14127. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  14128. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  14129. }
  14130. inline void shutdown(session_t session, bool graceful) {
  14131. if (!session) { return; }
  14132. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14133. if (graceful) {
  14134. // Try to send close_notify, but don't block forever
  14135. int ret;
  14136. int attempts = 0;
  14137. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  14138. attempts < 3) {
  14139. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  14140. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  14141. break;
  14142. }
  14143. attempts++;
  14144. }
  14145. }
  14146. }
  14147. inline bool is_peer_closed(session_t session, socket_t sock) {
  14148. if (!session || sock == INVALID_SOCKET) { return true; }
  14149. auto msession = static_cast<impl::MbedTlsSession *>(session);
  14150. // Check if there's already decrypted data available in the TLS buffer
  14151. // If so, the connection is definitely alive
  14152. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  14153. // Set socket to non-blocking to avoid blocking on read
  14154. detail::set_nonblocking(sock, true);
  14155. auto cleanup =
  14156. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14157. // Try a 1-byte read to check connection status
  14158. // Note: This will consume the byte if data is available, but for the
  14159. // purpose of checking if peer is closed, this should be acceptable
  14160. // since we're only called when we expect the connection might be closing
  14161. unsigned char buf;
  14162. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  14163. // If we got data or WANT_READ (would block), connection is alive
  14164. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  14165. // If we get a peer close notify or a connection reset, the peer is closed
  14166. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  14167. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  14168. }
  14169. inline cert_t get_peer_cert(const_session_t session) {
  14170. if (!session) { return nullptr; }
  14171. auto msession =
  14172. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  14173. // Mbed TLS returns a pointer to the internal peer cert chain.
  14174. // WARNING: This pointer is only valid while the session is active.
  14175. // Do not use the certificate after calling free_session().
  14176. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  14177. return const_cast<mbedtls_x509_crt *>(cert);
  14178. }
  14179. inline void free_cert(cert_t cert) {
  14180. // Mbed TLS: peer certificate is owned by the SSL context.
  14181. // No-op here, but callers should still call this for cross-backend
  14182. // portability.
  14183. (void)cert;
  14184. }
  14185. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14186. if (!cert || !hostname) { return false; }
  14187. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  14188. std::string host_str(hostname);
  14189. // Check if hostname is an IP address
  14190. bool is_ip = impl::is_ipv4_address(host_str);
  14191. unsigned char ip_bytes[4];
  14192. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  14193. // Check Subject Alternative Names (SAN)
  14194. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  14195. // - DNS names: raw string bytes
  14196. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  14197. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  14198. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  14199. const unsigned char *p = san->buf.p;
  14200. size_t len = san->buf.len;
  14201. if (is_ip) {
  14202. // Check if this SAN is an IPv4 address (4 bytes)
  14203. if (len == 4 && memcmp(p, ip_bytes, 4) == 0) { return true; }
  14204. // Check if this SAN is an IPv6 address (16 bytes) - skip for now
  14205. } else {
  14206. // Check if this SAN is a DNS name (printable ASCII string)
  14207. bool is_dns = len > 0;
  14208. for (size_t i = 0; i < len && is_dns; i++) {
  14209. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  14210. }
  14211. if (is_dns) {
  14212. std::string san_name(reinterpret_cast<const char *>(p), len);
  14213. if (detail::match_hostname(san_name, host_str)) { return true; }
  14214. }
  14215. }
  14216. san = san->next;
  14217. }
  14218. // Fallback: Check Common Name (CN) in subject
  14219. char cn[256];
  14220. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  14221. if (ret > 0) {
  14222. std::string cn_str(cn);
  14223. // Look for "CN=" in the DN string
  14224. size_t cn_pos = cn_str.find("CN=");
  14225. if (cn_pos != std::string::npos) {
  14226. size_t start = cn_pos + 3;
  14227. size_t end = cn_str.find(',', start);
  14228. std::string cn_value =
  14229. cn_str.substr(start, end == std::string::npos ? end : end - start);
  14230. if (detail::match_hostname(cn_value, host_str)) { return true; }
  14231. }
  14232. }
  14233. return false;
  14234. }
  14235. inline uint64_t hostname_mismatch_code() {
  14236. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  14237. }
  14238. inline long get_verify_result(const_session_t session) {
  14239. if (!session) { return -1; }
  14240. auto msession =
  14241. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  14242. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  14243. // Return 0 (X509_V_OK equivalent) if verification passed
  14244. return flags == 0 ? 0 : static_cast<long>(flags);
  14245. }
  14246. inline std::string get_cert_subject_cn(cert_t cert) {
  14247. if (!cert) return "";
  14248. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14249. // Find the CN in the subject
  14250. const mbedtls_x509_name *name = &x509->subject;
  14251. while (name != nullptr) {
  14252. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  14253. return std::string(reinterpret_cast<const char *>(name->val.p),
  14254. name->val.len);
  14255. }
  14256. name = name->next;
  14257. }
  14258. return "";
  14259. }
  14260. inline std::string get_cert_issuer_name(cert_t cert) {
  14261. if (!cert) return "";
  14262. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14263. // Build a human-readable issuer name string
  14264. char buf[512];
  14265. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  14266. if (ret < 0) return "";
  14267. return std::string(buf);
  14268. }
  14269. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14270. sans.clear();
  14271. if (!cert) return false;
  14272. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14273. // Parse the Subject Alternative Name extension
  14274. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  14275. while (cur != nullptr) {
  14276. if (cur->buf.len > 0) {
  14277. // Mbed TLS stores SAN as ASN.1 sequences
  14278. // The tag byte indicates the type
  14279. const unsigned char *p = cur->buf.p;
  14280. size_t len = cur->buf.len;
  14281. // First byte is the tag
  14282. unsigned char tag = *p;
  14283. p++;
  14284. len--;
  14285. // Parse length (simple single-byte length assumed)
  14286. if (len > 0 && *p < 0x80) {
  14287. size_t value_len = *p;
  14288. p++;
  14289. len--;
  14290. if (value_len <= len) {
  14291. SanEntry entry;
  14292. // ASN.1 context tags for GeneralName
  14293. switch (tag & 0x1F) {
  14294. case 2: // dNSName
  14295. entry.type = SanType::DNS;
  14296. entry.value =
  14297. std::string(reinterpret_cast<const char *>(p), value_len);
  14298. break;
  14299. case 7: // iPAddress
  14300. entry.type = SanType::IP;
  14301. if (value_len == 4) {
  14302. // IPv4
  14303. char buf[16];
  14304. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  14305. entry.value = buf;
  14306. } else if (value_len == 16) {
  14307. // IPv6
  14308. char buf[64];
  14309. snprintf(buf, sizeof(buf),
  14310. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  14311. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  14312. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  14313. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  14314. entry.value = buf;
  14315. }
  14316. break;
  14317. case 1: // rfc822Name (email)
  14318. entry.type = SanType::EMAIL;
  14319. entry.value =
  14320. std::string(reinterpret_cast<const char *>(p), value_len);
  14321. break;
  14322. case 6: // uniformResourceIdentifier
  14323. entry.type = SanType::URI;
  14324. entry.value =
  14325. std::string(reinterpret_cast<const char *>(p), value_len);
  14326. break;
  14327. default: entry.type = SanType::OTHER; break;
  14328. }
  14329. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14330. }
  14331. }
  14332. }
  14333. cur = cur->next;
  14334. }
  14335. return true;
  14336. }
  14337. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14338. time_t &not_after) {
  14339. if (!cert) return false;
  14340. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14341. // Convert mbedtls_x509_time to time_t
  14342. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  14343. struct tm tm_time = {};
  14344. tm_time.tm_year = t.year - 1900;
  14345. tm_time.tm_mon = t.mon - 1;
  14346. tm_time.tm_mday = t.day;
  14347. tm_time.tm_hour = t.hour;
  14348. tm_time.tm_min = t.min;
  14349. tm_time.tm_sec = t.sec;
  14350. #ifdef _WIN32
  14351. return _mkgmtime(&tm_time);
  14352. #else
  14353. return timegm(&tm_time);
  14354. #endif
  14355. };
  14356. not_before = to_time_t(x509->valid_from);
  14357. not_after = to_time_t(x509->valid_to);
  14358. return true;
  14359. }
  14360. inline std::string get_cert_serial(cert_t cert) {
  14361. if (!cert) return "";
  14362. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14363. // Convert serial number to hex string
  14364. std::string result;
  14365. result.reserve(x509->serial.len * 2);
  14366. for (size_t i = 0; i < x509->serial.len; i++) {
  14367. char hex[3];
  14368. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  14369. result += hex;
  14370. }
  14371. return result;
  14372. }
  14373. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14374. if (!cert) return false;
  14375. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  14376. if (!crt->raw.p || crt->raw.len == 0) return false;
  14377. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  14378. return true;
  14379. }
  14380. inline const char *get_sni(const_session_t session) {
  14381. if (!session) return nullptr;
  14382. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  14383. // For server: return SNI received from client during handshake
  14384. if (!msession->sni_hostname.empty()) {
  14385. return msession->sni_hostname.c_str();
  14386. }
  14387. // For client: return the hostname set via set_sni
  14388. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  14389. return nullptr;
  14390. }
  14391. inline uint64_t peek_error() {
  14392. // Mbed TLS doesn't have an error queue, return the last error
  14393. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  14394. }
  14395. inline uint64_t get_error() {
  14396. // Mbed TLS doesn't have an error queue, return and clear the last error
  14397. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  14398. impl::mbedtls_last_error() = 0;
  14399. return err;
  14400. }
  14401. inline std::string error_string(uint64_t code) {
  14402. char buf[256];
  14403. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  14404. return std::string(buf);
  14405. }
  14406. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14407. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  14408. if (!ca_chain) { return nullptr; }
  14409. mbedtls_x509_crt_init(ca_chain);
  14410. // mbedtls_x509_crt_parse expects null-terminated PEM
  14411. int ret = mbedtls_x509_crt_parse(ca_chain,
  14412. reinterpret_cast<const unsigned char *>(pem),
  14413. len + 1); // +1 for null terminator
  14414. if (ret != 0) {
  14415. // Try without +1 in case PEM is already null-terminated
  14416. ret = mbedtls_x509_crt_parse(
  14417. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  14418. if (ret != 0) {
  14419. mbedtls_x509_crt_free(ca_chain);
  14420. delete ca_chain;
  14421. return nullptr;
  14422. }
  14423. }
  14424. return static_cast<ca_store_t>(ca_chain);
  14425. }
  14426. inline void free_ca_store(ca_store_t store) {
  14427. if (store) {
  14428. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  14429. mbedtls_x509_crt_free(ca_chain);
  14430. delete ca_chain;
  14431. }
  14432. }
  14433. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  14434. if (!ctx || !store) { return false; }
  14435. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14436. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  14437. // Free existing CA chain
  14438. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  14439. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  14440. // Copy the CA chain (deep copy)
  14441. // Parse from the raw data of the source cert
  14442. mbedtls_x509_crt *src = ca_chain;
  14443. while (src != nullptr) {
  14444. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  14445. src->raw.len);
  14446. if (ret != 0) { return false; }
  14447. src = src->next;
  14448. }
  14449. // Update the SSL config to use the new CA chain
  14450. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  14451. return true;
  14452. }
  14453. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  14454. certs.clear();
  14455. if (!ctx) { return 0; }
  14456. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14457. // Iterate through the CA chain
  14458. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  14459. while (cert != nullptr && cert->raw.len > 0) {
  14460. // Create a copy of the certificate for the caller
  14461. auto *copy = new mbedtls_x509_crt;
  14462. mbedtls_x509_crt_init(copy);
  14463. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  14464. if (ret == 0) {
  14465. certs.push_back(static_cast<cert_t>(copy));
  14466. } else {
  14467. mbedtls_x509_crt_free(copy);
  14468. delete copy;
  14469. }
  14470. cert = cert->next;
  14471. }
  14472. return certs.size();
  14473. }
  14474. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  14475. std::vector<std::string> names;
  14476. if (!ctx) { return names; }
  14477. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14478. // Iterate through the CA chain
  14479. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  14480. while (cert != nullptr && cert->raw.len > 0) {
  14481. char buf[512];
  14482. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  14483. if (ret > 0) { names.push_back(buf); }
  14484. cert = cert->next;
  14485. }
  14486. return names;
  14487. }
  14488. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  14489. const char *key_pem, const char *password) {
  14490. if (!ctx || !cert_pem || !key_pem) { return false; }
  14491. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14492. // Free existing certificate and key
  14493. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  14494. mbedtls_pk_free(&mbed_ctx->own_key);
  14495. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  14496. mbedtls_pk_init(&mbed_ctx->own_key);
  14497. // Parse certificate PEM
  14498. int ret = mbedtls_x509_crt_parse(
  14499. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  14500. strlen(cert_pem) + 1);
  14501. if (ret != 0) {
  14502. impl::mbedtls_last_error() = ret;
  14503. return false;
  14504. }
  14505. // Parse private key PEM
  14506. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14507. ret = mbedtls_pk_parse_key(
  14508. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  14509. strlen(key_pem) + 1,
  14510. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  14511. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  14512. &mbed_ctx->ctr_drbg);
  14513. #else
  14514. ret = mbedtls_pk_parse_key(
  14515. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  14516. strlen(key_pem) + 1,
  14517. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  14518. password ? strlen(password) : 0);
  14519. #endif
  14520. if (ret != 0) {
  14521. impl::mbedtls_last_error() = ret;
  14522. return false;
  14523. }
  14524. // Configure SSL to use the new certificate and key
  14525. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  14526. &mbed_ctx->own_key);
  14527. if (ret != 0) {
  14528. impl::mbedtls_last_error() = ret;
  14529. return false;
  14530. }
  14531. return true;
  14532. }
  14533. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  14534. if (!ctx || !ca_pem) { return false; }
  14535. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14536. // Free existing CA chain
  14537. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  14538. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  14539. // Parse CA PEM
  14540. int ret = mbedtls_x509_crt_parse(
  14541. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  14542. strlen(ca_pem) + 1);
  14543. if (ret != 0) {
  14544. impl::mbedtls_last_error() = ret;
  14545. return false;
  14546. }
  14547. // Update SSL config to use new CA chain
  14548. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  14549. return true;
  14550. }
  14551. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  14552. if (!ctx) { return false; }
  14553. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14554. impl::get_verify_callback() = std::move(callback);
  14555. mbed_ctx->has_verify_callback =
  14556. static_cast<bool>(impl::get_verify_callback());
  14557. if (mbed_ctx->has_verify_callback) {
  14558. // Set OPTIONAL mode to ensure callback is called even when verification
  14559. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  14560. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  14561. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  14562. nullptr);
  14563. } else {
  14564. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  14565. }
  14566. return true;
  14567. }
  14568. inline long get_verify_error(const_session_t session) {
  14569. if (!session) { return -1; }
  14570. auto *msession =
  14571. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  14572. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  14573. }
  14574. inline std::string verify_error_string(long error_code) {
  14575. if (error_code == 0) { return ""; }
  14576. char buf[256];
  14577. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  14578. static_cast<uint32_t>(error_code));
  14579. // Remove trailing newline if present
  14580. std::string result(buf);
  14581. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  14582. result.pop_back();
  14583. }
  14584. return result;
  14585. }
  14586. } // namespace tls
  14587. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  14588. // ----------------------------------------------------------------------------
  14589. } // namespace httplib
  14590. #endif // CPPHTTPLIB_HTTPLIB_H