httplib.h 560 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2026 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.30.2"
  10. #define CPPHTTPLIB_VERSION_NUM "0x001E02"
  11. /*
  12. * Platform compatibility check
  13. */
  14. #if defined(_WIN32) && !defined(_WIN64)
  15. #if defined(_MSC_VER)
  16. #pragma message( \
  17. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler.")
  18. #else
  19. #warning \
  20. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler."
  21. #endif
  22. #elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ < 8
  23. #warning \
  24. "cpp-httplib doesn't support 32-bit platforms. Please use a 64-bit compiler."
  25. #elif defined(__SIZEOF_SIZE_T__) && __SIZEOF_SIZE_T__ < 8
  26. #warning \
  27. "cpp-httplib doesn't support platforms where size_t is less than 64 bits."
  28. #endif
  29. #ifdef _WIN32
  30. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  31. #error \
  32. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  33. #endif
  34. #endif
  35. /*
  36. * Configuration
  37. */
  38. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  39. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  40. #endif
  41. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  42. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  43. #endif
  44. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  45. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  46. #endif
  47. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  60. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  61. #endif
  62. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  63. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  64. #endif
  65. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  66. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  67. #endif
  68. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  69. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  70. #endif
  71. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  72. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  73. #endif
  74. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  75. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  78. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  79. #endif
  80. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  81. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  82. #endif
  83. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  84. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  85. #endif
  86. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  87. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  88. #endif
  89. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  90. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  91. #endif
  92. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  93. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  94. #endif
  95. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  96. #ifdef _WIN32
  97. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  98. #else
  99. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  100. #endif
  101. #endif
  102. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  103. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  106. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  107. #endif
  108. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  109. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  110. #endif
  111. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  112. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  113. #endif
  114. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  115. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  116. #endif
  117. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  118. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  119. #endif
  120. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  121. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  122. #endif
  123. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  124. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  125. #endif
  126. #ifndef CPPHTTPLIB_TCP_NODELAY
  127. #define CPPHTTPLIB_TCP_NODELAY false
  128. #endif
  129. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  130. #define CPPHTTPLIB_IPV6_V6ONLY false
  131. #endif
  132. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  133. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  134. #endif
  135. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  136. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  137. #endif
  138. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  139. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  140. #endif
  141. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  142. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  143. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  144. ? std::thread::hardware_concurrency() - 1 \
  145. : 0))
  146. #endif
  147. #ifndef CPPHTTPLIB_RECV_FLAGS
  148. #define CPPHTTPLIB_RECV_FLAGS 0
  149. #endif
  150. #ifndef CPPHTTPLIB_SEND_FLAGS
  151. #define CPPHTTPLIB_SEND_FLAGS 0
  152. #endif
  153. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  154. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  155. #endif
  156. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  157. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  158. #endif
  159. /*
  160. * Headers
  161. */
  162. #ifdef _WIN32
  163. #ifndef _CRT_SECURE_NO_WARNINGS
  164. #define _CRT_SECURE_NO_WARNINGS
  165. #endif //_CRT_SECURE_NO_WARNINGS
  166. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  167. #define _CRT_NONSTDC_NO_DEPRECATE
  168. #endif //_CRT_NONSTDC_NO_DEPRECATE
  169. #if defined(_MSC_VER)
  170. #if _MSC_VER < 1900
  171. #error Sorry, Visual Studio versions prior to 2015 are not supported
  172. #endif
  173. #pragma comment(lib, "ws2_32.lib")
  174. #ifndef _SSIZE_T_DEFINED
  175. using ssize_t = __int64;
  176. #define _SSIZE_T_DEFINED
  177. #endif
  178. #endif // _MSC_VER
  179. #ifndef S_ISREG
  180. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  181. #endif // S_ISREG
  182. #ifndef S_ISDIR
  183. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  184. #endif // S_ISDIR
  185. #ifndef NOMINMAX
  186. #define NOMINMAX
  187. #endif // NOMINMAX
  188. #include <io.h>
  189. #include <winsock2.h>
  190. #include <ws2tcpip.h>
  191. #if defined(__has_include)
  192. #if __has_include(<afunix.h>)
  193. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  194. #include <afunix.h>
  195. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  196. #endif
  197. #endif
  198. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  199. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  200. #endif
  201. using nfds_t = unsigned long;
  202. using socket_t = SOCKET;
  203. using socklen_t = int;
  204. #else // not _WIN32
  205. #include <arpa/inet.h>
  206. #if !defined(_AIX) && !defined(__MVS__)
  207. #include <ifaddrs.h>
  208. #endif
  209. #ifdef __MVS__
  210. #include <strings.h>
  211. #ifndef NI_MAXHOST
  212. #define NI_MAXHOST 1025
  213. #endif
  214. #endif
  215. #include <net/if.h>
  216. #include <netdb.h>
  217. #include <netinet/in.h>
  218. #ifdef __linux__
  219. #include <resolv.h>
  220. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  221. #endif
  222. #include <csignal>
  223. #include <netinet/tcp.h>
  224. #include <poll.h>
  225. #include <pthread.h>
  226. #include <sys/mman.h>
  227. #include <sys/socket.h>
  228. #include <sys/un.h>
  229. #include <unistd.h>
  230. using socket_t = int;
  231. #ifndef INVALID_SOCKET
  232. #define INVALID_SOCKET (-1)
  233. #endif
  234. #endif //_WIN32
  235. #if defined(__APPLE__)
  236. #include <TargetConditionals.h>
  237. #endif
  238. #include <algorithm>
  239. #include <array>
  240. #include <atomic>
  241. #include <cassert>
  242. #include <cctype>
  243. #include <chrono>
  244. #include <climits>
  245. #include <condition_variable>
  246. #include <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. size_t content_length = 0;
  1333. size_t bytes_read = 0;
  1334. bool chunked = false;
  1335. bool eof = false;
  1336. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1337. Error last_error = Error::Success;
  1338. ssize_t read(char *buf, size_t len);
  1339. bool has_error() const { return last_error != Error::Success; }
  1340. };
  1341. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1342. size_t len) {
  1343. (void)stream;
  1344. return br.read(buf, len);
  1345. }
  1346. class decompressor;
  1347. } // namespace detail
  1348. class ClientImpl {
  1349. public:
  1350. explicit ClientImpl(const std::string &host);
  1351. explicit ClientImpl(const std::string &host, int port);
  1352. explicit ClientImpl(const std::string &host, int port,
  1353. const std::string &client_cert_path,
  1354. const std::string &client_key_path);
  1355. virtual ~ClientImpl();
  1356. virtual bool is_valid() const;
  1357. struct StreamHandle {
  1358. std::unique_ptr<Response> response;
  1359. Error error = Error::Success;
  1360. StreamHandle() = default;
  1361. StreamHandle(const StreamHandle &) = delete;
  1362. StreamHandle &operator=(const StreamHandle &) = delete;
  1363. StreamHandle(StreamHandle &&) = default;
  1364. StreamHandle &operator=(StreamHandle &&) = default;
  1365. ~StreamHandle() = default;
  1366. bool is_valid() const {
  1367. return response != nullptr && error == Error::Success;
  1368. }
  1369. ssize_t read(char *buf, size_t len);
  1370. void parse_trailers_if_needed();
  1371. Error get_read_error() const { return body_reader_.last_error; }
  1372. bool has_read_error() const { return body_reader_.has_error(); }
  1373. bool trailers_parsed_ = false;
  1374. private:
  1375. friend class ClientImpl;
  1376. ssize_t read_with_decompression(char *buf, size_t len);
  1377. std::unique_ptr<ClientConnection> connection_;
  1378. std::unique_ptr<Stream> socket_stream_;
  1379. Stream *stream_ = nullptr;
  1380. detail::BodyReader body_reader_;
  1381. std::unique_ptr<detail::decompressor> decompressor_;
  1382. std::string decompress_buffer_;
  1383. size_t decompress_offset_ = 0;
  1384. };
  1385. // clang-format off
  1386. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1387. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1388. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1389. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1390. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1391. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1392. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1393. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1394. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1395. Result Head(const std::string &path);
  1396. Result Head(const std::string &path, const Headers &headers);
  1397. Result Post(const std::string &path);
  1398. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1399. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1400. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1401. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1402. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1403. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1404. Result Post(const std::string &path, const Params &params);
  1405. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1406. Result Post(const std::string &path, const Headers &headers);
  1407. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1408. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1409. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1410. 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);
  1411. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1412. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1413. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1414. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1415. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1416. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1417. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1418. Result Put(const std::string &path);
  1419. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1420. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1421. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1422. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1423. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1424. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1425. Result Put(const std::string &path, const Params &params);
  1426. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1427. Result Put(const std::string &path, const Headers &headers);
  1428. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1429. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1430. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1431. 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);
  1432. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1433. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1434. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1435. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1436. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1437. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1438. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1439. Result Patch(const std::string &path);
  1440. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1441. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1442. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1443. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1444. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1445. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1446. Result Patch(const std::string &path, const Params &params);
  1447. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1448. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1449. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1450. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1451. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1452. 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);
  1453. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1454. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1455. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1456. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1457. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1458. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1459. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1460. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1461. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1462. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1463. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1464. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1465. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1466. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1467. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1468. Result Options(const std::string &path);
  1469. Result Options(const std::string &path, const Headers &headers);
  1470. // clang-format on
  1471. // Streaming API: Open a stream for reading response body incrementally
  1472. // Socket ownership is transferred to StreamHandle for true streaming
  1473. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1474. StreamHandle open_stream(const std::string &method, const std::string &path,
  1475. const Params &params = {},
  1476. const Headers &headers = {},
  1477. const std::string &body = {},
  1478. const std::string &content_type = {});
  1479. bool send(Request &req, Response &res, Error &error);
  1480. Result send(const Request &req);
  1481. void stop();
  1482. std::string host() const;
  1483. int port() const;
  1484. size_t is_socket_open() const;
  1485. socket_t socket() const;
  1486. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1487. void set_default_headers(Headers headers);
  1488. void
  1489. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1490. void set_address_family(int family);
  1491. void set_tcp_nodelay(bool on);
  1492. void set_ipv6_v6only(bool on);
  1493. void set_socket_options(SocketOptions socket_options);
  1494. void set_connection_timeout(time_t sec, time_t usec = 0);
  1495. template <class Rep, class Period>
  1496. void
  1497. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1498. void set_read_timeout(time_t sec, time_t usec = 0);
  1499. template <class Rep, class Period>
  1500. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1501. void set_write_timeout(time_t sec, time_t usec = 0);
  1502. template <class Rep, class Period>
  1503. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1504. void set_max_timeout(time_t msec);
  1505. template <class Rep, class Period>
  1506. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1507. void set_basic_auth(const std::string &username, const std::string &password);
  1508. void set_bearer_token_auth(const std::string &token);
  1509. void set_keep_alive(bool on);
  1510. void set_follow_location(bool on);
  1511. void set_path_encode(bool on);
  1512. void set_compress(bool on);
  1513. void set_decompress(bool on);
  1514. void set_interface(const std::string &intf);
  1515. void set_proxy(const std::string &host, int port);
  1516. void set_proxy_basic_auth(const std::string &username,
  1517. const std::string &password);
  1518. void set_proxy_bearer_token_auth(const std::string &token);
  1519. void set_logger(Logger logger);
  1520. void set_error_logger(ErrorLogger error_logger);
  1521. protected:
  1522. struct Socket {
  1523. socket_t sock = INVALID_SOCKET;
  1524. // For Mbed TLS compatibility: start_time for request timeout tracking
  1525. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1526. bool is_open() const { return sock != INVALID_SOCKET; }
  1527. #ifdef CPPHTTPLIB_SSL_ENABLED
  1528. tls::session_t ssl = nullptr;
  1529. #endif
  1530. };
  1531. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1532. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1533. // All of:
  1534. // shutdown_ssl
  1535. // shutdown_socket
  1536. // close_socket
  1537. // should ONLY be called when socket_mutex_ is locked.
  1538. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1539. // with a DIFFERENT thread sending requests using that socket.
  1540. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1541. void shutdown_socket(Socket &socket) const;
  1542. void close_socket(Socket &socket);
  1543. bool process_request(Stream &strm, Request &req, Response &res,
  1544. bool close_connection, Error &error);
  1545. bool write_content_with_provider(Stream &strm, const Request &req,
  1546. Error &error) const;
  1547. void copy_settings(const ClientImpl &rhs);
  1548. void output_log(const Request &req, const Response &res) const;
  1549. void output_error_log(const Error &err, const Request *req) const;
  1550. // Socket endpoint information
  1551. const std::string host_;
  1552. const int port_;
  1553. // Current open socket
  1554. Socket socket_;
  1555. mutable std::mutex socket_mutex_;
  1556. std::recursive_mutex request_mutex_;
  1557. // These are all protected under socket_mutex
  1558. size_t socket_requests_in_flight_ = 0;
  1559. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1560. bool socket_should_be_closed_when_request_is_done_ = false;
  1561. // Hostname-IP map
  1562. std::map<std::string, std::string> addr_map_;
  1563. // Default headers
  1564. Headers default_headers_;
  1565. // Header writer
  1566. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1567. detail::write_headers;
  1568. // Settings
  1569. std::string client_cert_path_;
  1570. std::string client_key_path_;
  1571. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1572. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1573. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1574. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1575. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1576. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1577. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1578. std::string basic_auth_username_;
  1579. std::string basic_auth_password_;
  1580. std::string bearer_token_auth_token_;
  1581. bool keep_alive_ = false;
  1582. bool follow_location_ = false;
  1583. bool path_encode_ = true;
  1584. int address_family_ = AF_UNSPEC;
  1585. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1586. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1587. SocketOptions socket_options_ = nullptr;
  1588. bool compress_ = false;
  1589. bool decompress_ = true;
  1590. std::string interface_;
  1591. std::string proxy_host_;
  1592. int proxy_port_ = -1;
  1593. std::string proxy_basic_auth_username_;
  1594. std::string proxy_basic_auth_password_;
  1595. std::string proxy_bearer_token_auth_token_;
  1596. mutable std::mutex logger_mutex_;
  1597. Logger logger_;
  1598. ErrorLogger error_logger_;
  1599. private:
  1600. bool send_(Request &req, Response &res, Error &error);
  1601. Result send_(Request &&req);
  1602. socket_t create_client_socket(Error &error) const;
  1603. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1604. bool skip_100_continue = true) const;
  1605. bool write_request(Stream &strm, Request &req, bool close_connection,
  1606. Error &error, bool skip_body = false);
  1607. bool write_request_body(Stream &strm, Request &req, Error &error);
  1608. void prepare_default_headers(Request &r, bool for_stream,
  1609. const std::string &ct);
  1610. bool redirect(Request &req, Response &res, Error &error);
  1611. bool create_redirect_client(const std::string &scheme,
  1612. const std::string &host, int port, Request &req,
  1613. Response &res, const std::string &path,
  1614. const std::string &location, Error &error);
  1615. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1616. bool handle_request(Stream &strm, Request &req, Response &res,
  1617. bool close_connection, Error &error);
  1618. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1619. Request &req, const char *body, size_t content_length,
  1620. ContentProvider content_provider,
  1621. ContentProviderWithoutLength content_provider_without_length,
  1622. const std::string &content_type, ContentReceiver content_receiver,
  1623. Error &error);
  1624. Result send_with_content_provider_and_receiver(
  1625. const std::string &method, const std::string &path,
  1626. const Headers &headers, const char *body, size_t content_length,
  1627. ContentProvider content_provider,
  1628. ContentProviderWithoutLength content_provider_without_length,
  1629. const std::string &content_type, ContentReceiver content_receiver,
  1630. UploadProgress progress);
  1631. ContentProviderWithoutLength get_multipart_content_provider(
  1632. const std::string &boundary, const UploadFormDataItems &items,
  1633. const FormDataProviderItems &provider_items) const;
  1634. virtual bool
  1635. process_socket(const Socket &socket,
  1636. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1637. std::function<bool(Stream &strm)> callback);
  1638. virtual bool is_ssl() const;
  1639. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1640. #ifdef CPPHTTPLIB_SSL_ENABLED
  1641. public:
  1642. void set_digest_auth(const std::string &username,
  1643. const std::string &password);
  1644. void set_proxy_digest_auth(const std::string &username,
  1645. const std::string &password);
  1646. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1647. const std::string &ca_cert_dir_path = std::string());
  1648. void enable_server_certificate_verification(bool enabled);
  1649. void enable_server_hostname_verification(bool enabled);
  1650. protected:
  1651. std::string digest_auth_username_;
  1652. std::string digest_auth_password_;
  1653. std::string proxy_digest_auth_username_;
  1654. std::string proxy_digest_auth_password_;
  1655. std::string ca_cert_file_path_;
  1656. std::string ca_cert_dir_path_;
  1657. bool server_certificate_verification_ = true;
  1658. bool server_hostname_verification_ = true;
  1659. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  1660. int last_ssl_error_ = 0;
  1661. unsigned long last_backend_error_ = 0;
  1662. #endif
  1663. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1664. public:
  1665. [[deprecated("Use load_ca_cert_store() instead")]]
  1666. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1667. [[deprecated("Use tls::create_ca_store() instead")]]
  1668. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1669. [[deprecated("Use set_server_certificate_verifier(VerifyCallback) instead")]]
  1670. virtual void set_server_certificate_verifier(
  1671. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1672. #endif
  1673. };
  1674. class Client {
  1675. public:
  1676. // Universal interface
  1677. explicit Client(const std::string &scheme_host_port);
  1678. explicit Client(const std::string &scheme_host_port,
  1679. const std::string &client_cert_path,
  1680. const std::string &client_key_path);
  1681. // HTTP only interface
  1682. explicit Client(const std::string &host, int port);
  1683. explicit Client(const std::string &host, int port,
  1684. const std::string &client_cert_path,
  1685. const std::string &client_key_path);
  1686. Client(Client &&) = default;
  1687. Client &operator=(Client &&) = default;
  1688. ~Client();
  1689. bool is_valid() const;
  1690. // clang-format off
  1691. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1692. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1693. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1694. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1695. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1696. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1697. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1698. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1699. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1700. Result Head(const std::string &path);
  1701. Result Head(const std::string &path, const Headers &headers);
  1702. Result Post(const std::string &path);
  1703. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1704. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1705. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1706. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1707. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1708. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1709. Result Post(const std::string &path, const Params &params);
  1710. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1711. Result Post(const std::string &path, const Headers &headers);
  1712. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1713. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1714. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1715. 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);
  1716. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1717. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1718. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1719. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1720. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1721. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1722. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1723. Result Put(const std::string &path);
  1724. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1725. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1726. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1727. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1728. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1729. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1730. Result Put(const std::string &path, const Params &params);
  1731. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1732. Result Put(const std::string &path, const Headers &headers);
  1733. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1734. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1735. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1736. 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);
  1737. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1738. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1739. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1740. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1741. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1742. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1743. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1744. Result Patch(const std::string &path);
  1745. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1746. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1747. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1748. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1749. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1750. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1751. Result Patch(const std::string &path, const Params &params);
  1752. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1753. Result Patch(const std::string &path, const Headers &headers);
  1754. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1755. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1756. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1757. 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);
  1758. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1759. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1760. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1761. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1762. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1763. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1764. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1765. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1766. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1767. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1768. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1769. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1770. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1771. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1772. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1773. Result Options(const std::string &path);
  1774. Result Options(const std::string &path, const Headers &headers);
  1775. // clang-format on
  1776. // Streaming API: Open a stream for reading response body incrementally
  1777. // Socket ownership is transferred to StreamHandle for true streaming
  1778. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1779. ClientImpl::StreamHandle open_stream(const std::string &method,
  1780. const std::string &path,
  1781. const Params &params = {},
  1782. const Headers &headers = {},
  1783. const std::string &body = {},
  1784. const std::string &content_type = {});
  1785. bool send(Request &req, Response &res, Error &error);
  1786. Result send(const Request &req);
  1787. void stop();
  1788. std::string host() const;
  1789. int port() const;
  1790. size_t is_socket_open() const;
  1791. socket_t socket() const;
  1792. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1793. void set_default_headers(Headers headers);
  1794. void
  1795. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1796. void set_address_family(int family);
  1797. void set_tcp_nodelay(bool on);
  1798. void set_socket_options(SocketOptions socket_options);
  1799. void set_connection_timeout(time_t sec, time_t usec = 0);
  1800. template <class Rep, class Period>
  1801. void
  1802. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1803. void set_read_timeout(time_t sec, time_t usec = 0);
  1804. template <class Rep, class Period>
  1805. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1806. void set_write_timeout(time_t sec, time_t usec = 0);
  1807. template <class Rep, class Period>
  1808. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1809. void set_max_timeout(time_t msec);
  1810. template <class Rep, class Period>
  1811. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1812. void set_basic_auth(const std::string &username, const std::string &password);
  1813. void set_bearer_token_auth(const std::string &token);
  1814. void set_keep_alive(bool on);
  1815. void set_follow_location(bool on);
  1816. void set_path_encode(bool on);
  1817. void set_url_encode(bool on);
  1818. void set_compress(bool on);
  1819. void set_decompress(bool on);
  1820. void set_interface(const std::string &intf);
  1821. void set_proxy(const std::string &host, int port);
  1822. void set_proxy_basic_auth(const std::string &username,
  1823. const std::string &password);
  1824. void set_proxy_bearer_token_auth(const std::string &token);
  1825. void set_logger(Logger logger);
  1826. void set_error_logger(ErrorLogger error_logger);
  1827. private:
  1828. std::unique_ptr<ClientImpl> cli_;
  1829. #ifdef CPPHTTPLIB_SSL_ENABLED
  1830. public:
  1831. void set_digest_auth(const std::string &username,
  1832. const std::string &password);
  1833. void set_proxy_digest_auth(const std::string &username,
  1834. const std::string &password);
  1835. void enable_server_certificate_verification(bool enabled);
  1836. void enable_server_hostname_verification(bool enabled);
  1837. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1838. const std::string &ca_cert_dir_path = std::string());
  1839. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  1840. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1841. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  1842. void set_session_verifier(
  1843. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  1844. tls::ctx_t tls_context() const;
  1845. private:
  1846. bool is_ssl_ = false;
  1847. #endif
  1848. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1849. public:
  1850. [[deprecated("Use tls_context() instead")]]
  1851. SSL_CTX *ssl_context() const;
  1852. [[deprecated("Use set_session_verifier(session_t) instead")]]
  1853. void set_server_certificate_verifier(
  1854. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1855. [[deprecated("Use Result::ssl_backend_error() instead")]]
  1856. long get_verify_result() const;
  1857. #endif
  1858. };
  1859. #ifdef CPPHTTPLIB_SSL_ENABLED
  1860. class SSLServer : public Server {
  1861. public:
  1862. SSLServer(const char *cert_path, const char *private_key_path,
  1863. const char *client_ca_cert_file_path = nullptr,
  1864. const char *client_ca_cert_dir_path = nullptr,
  1865. const char *private_key_password = nullptr);
  1866. struct PemMemory {
  1867. const char *cert_pem;
  1868. size_t cert_pem_len;
  1869. const char *key_pem;
  1870. size_t key_pem_len;
  1871. const char *client_ca_pem;
  1872. size_t client_ca_pem_len;
  1873. const char *private_key_password;
  1874. };
  1875. explicit SSLServer(const PemMemory &pem);
  1876. // The callback receives the ctx_t handle which can be cast to the
  1877. // appropriate backend type (SSL_CTX* for OpenSSL,
  1878. // tls::impl::MbedTlsContext* for Mbed TLS)
  1879. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  1880. ~SSLServer() override;
  1881. bool is_valid() const override;
  1882. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  1883. const char *client_ca_pem = nullptr,
  1884. const char *password = nullptr);
  1885. tls::ctx_t tls_context() const { return ctx_; }
  1886. int ssl_last_error() const { return last_ssl_error_; }
  1887. private:
  1888. bool process_and_close_socket(socket_t sock) override;
  1889. tls::ctx_t ctx_ = nullptr;
  1890. std::mutex ctx_mutex_;
  1891. int last_ssl_error_ = 0;
  1892. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1893. public:
  1894. [[deprecated("Use SSLServer(PemMemory) or "
  1895. "SSLServer(ContextSetupCallback) instead")]]
  1896. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1897. X509_STORE *client_ca_cert_store = nullptr);
  1898. [[deprecated("Use SSLServer(ContextSetupCallback) instead")]]
  1899. SSLServer(
  1900. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1901. [[deprecated("Use tls_context() instead")]]
  1902. SSL_CTX *ssl_context() const;
  1903. [[deprecated("Use update_certs_pem() instead")]]
  1904. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1905. X509_STORE *client_ca_cert_store = nullptr);
  1906. #endif
  1907. };
  1908. class SSLClient final : public ClientImpl {
  1909. public:
  1910. explicit SSLClient(const std::string &host);
  1911. explicit SSLClient(const std::string &host, int port);
  1912. explicit SSLClient(const std::string &host, int port,
  1913. const std::string &client_cert_path,
  1914. const std::string &client_key_path,
  1915. const std::string &private_key_password = std::string());
  1916. struct PemMemory {
  1917. const char *cert_pem;
  1918. size_t cert_pem_len;
  1919. const char *key_pem;
  1920. size_t key_pem_len;
  1921. const char *private_key_password;
  1922. };
  1923. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  1924. ~SSLClient() override;
  1925. bool is_valid() const override;
  1926. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  1927. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1928. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  1929. // Post-handshake session verifier (backend-independent)
  1930. void set_session_verifier(
  1931. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  1932. tls::ctx_t tls_context() const { return ctx_; }
  1933. private:
  1934. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1935. bool ensure_socket_connection(Socket &socket, Error &error) override;
  1936. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1937. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1938. bool
  1939. process_socket(const Socket &socket,
  1940. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1941. std::function<bool(Stream &strm)> callback) override;
  1942. bool is_ssl() const override;
  1943. bool connect_with_proxy(
  1944. Socket &sock,
  1945. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1946. Response &res, bool &success, Error &error);
  1947. bool initialize_ssl(Socket &socket, Error &error);
  1948. bool load_certs();
  1949. tls::ctx_t ctx_ = nullptr;
  1950. std::mutex ctx_mutex_;
  1951. std::once_flag initialize_cert_;
  1952. long verify_result_ = 0;
  1953. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  1954. friend class ClientImpl;
  1955. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1956. public:
  1957. [[deprecated("Use SSLClient(host, port, PemMemory) instead")]]
  1958. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1959. EVP_PKEY *client_key,
  1960. const std::string &private_key_password = std::string());
  1961. [[deprecated("Use Result::ssl_backend_error() instead")]]
  1962. long get_verify_result() const;
  1963. [[deprecated("Use tls_context() instead")]]
  1964. SSL_CTX *ssl_context() const;
  1965. [[deprecated("Use set_session_verifier(session_t) instead")]]
  1966. void set_server_certificate_verifier(
  1967. std::function<SSLVerifierResponse(SSL *ssl)> verifier) override;
  1968. private:
  1969. bool verify_host(X509 *server_cert) const;
  1970. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1971. bool verify_host_with_common_name(X509 *server_cert) const;
  1972. #endif
  1973. };
  1974. #endif // CPPHTTPLIB_SSL_ENABLED
  1975. namespace detail {
  1976. template <typename T, typename U>
  1977. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1978. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1979. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1980. duration - std::chrono::seconds(sec))
  1981. .count();
  1982. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1983. }
  1984. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1985. return N - 1;
  1986. }
  1987. inline bool is_numeric(const std::string &str) {
  1988. return !str.empty() &&
  1989. std::all_of(str.cbegin(), str.cend(),
  1990. [](unsigned char c) { return std::isdigit(c); });
  1991. }
  1992. inline size_t get_header_value_u64(const Headers &headers,
  1993. const std::string &key, size_t def,
  1994. size_t id, bool &is_invalid_value) {
  1995. is_invalid_value = false;
  1996. auto rng = headers.equal_range(key);
  1997. auto it = rng.first;
  1998. std::advance(it, static_cast<ssize_t>(id));
  1999. if (it != rng.second) {
  2000. if (is_numeric(it->second)) {
  2001. return std::strtoull(it->second.data(), nullptr, 10);
  2002. } else {
  2003. is_invalid_value = true;
  2004. }
  2005. }
  2006. return def;
  2007. }
  2008. inline size_t get_header_value_u64(const Headers &headers,
  2009. const std::string &key, size_t def,
  2010. size_t id) {
  2011. auto dummy = false;
  2012. return get_header_value_u64(headers, key, def, id, dummy);
  2013. }
  2014. } // namespace detail
  2015. template <class Rep, class Period>
  2016. inline Server &
  2017. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2018. detail::duration_to_sec_and_usec(
  2019. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2020. return *this;
  2021. }
  2022. template <class Rep, class Period>
  2023. inline Server &
  2024. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2025. detail::duration_to_sec_and_usec(
  2026. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2027. return *this;
  2028. }
  2029. template <class Rep, class Period>
  2030. inline Server &
  2031. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2032. detail::duration_to_sec_and_usec(
  2033. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2034. return *this;
  2035. }
  2036. template <class Rep, class Period>
  2037. inline void ClientImpl::set_connection_timeout(
  2038. const std::chrono::duration<Rep, Period> &duration) {
  2039. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2040. set_connection_timeout(sec, usec);
  2041. });
  2042. }
  2043. template <class Rep, class Period>
  2044. inline void ClientImpl::set_read_timeout(
  2045. const std::chrono::duration<Rep, Period> &duration) {
  2046. detail::duration_to_sec_and_usec(
  2047. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2048. }
  2049. template <class Rep, class Period>
  2050. inline void ClientImpl::set_write_timeout(
  2051. const std::chrono::duration<Rep, Period> &duration) {
  2052. detail::duration_to_sec_and_usec(
  2053. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2054. }
  2055. template <class Rep, class Period>
  2056. inline void ClientImpl::set_max_timeout(
  2057. const std::chrono::duration<Rep, Period> &duration) {
  2058. auto msec =
  2059. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2060. set_max_timeout(msec);
  2061. }
  2062. template <class Rep, class Period>
  2063. inline void Client::set_connection_timeout(
  2064. const std::chrono::duration<Rep, Period> &duration) {
  2065. cli_->set_connection_timeout(duration);
  2066. }
  2067. template <class Rep, class Period>
  2068. inline void
  2069. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2070. cli_->set_read_timeout(duration);
  2071. }
  2072. template <class Rep, class Period>
  2073. inline void
  2074. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2075. cli_->set_write_timeout(duration);
  2076. }
  2077. inline void Client::set_max_timeout(time_t msec) {
  2078. cli_->set_max_timeout(msec);
  2079. }
  2080. template <class Rep, class Period>
  2081. inline void
  2082. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2083. cli_->set_max_timeout(duration);
  2084. }
  2085. /*
  2086. * Forward declarations and types that will be part of the .h file if split into
  2087. * .h + .cc.
  2088. */
  2089. std::string hosted_at(const std::string &hostname);
  2090. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2091. // JavaScript-style URL encoding/decoding functions
  2092. std::string encode_uri_component(const std::string &value);
  2093. std::string encode_uri(const std::string &value);
  2094. std::string decode_uri_component(const std::string &value);
  2095. std::string decode_uri(const std::string &value);
  2096. // RFC 3986 compliant URL component encoding/decoding functions
  2097. std::string encode_path_component(const std::string &component);
  2098. std::string decode_path_component(const std::string &component);
  2099. std::string encode_query_component(const std::string &component,
  2100. bool space_as_plus = true);
  2101. std::string decode_query_component(const std::string &component,
  2102. bool plus_as_space = true);
  2103. std::string append_query_params(const std::string &path, const Params &params);
  2104. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2105. std::pair<std::string, std::string>
  2106. make_basic_authentication_header(const std::string &username,
  2107. const std::string &password,
  2108. bool is_proxy = false);
  2109. namespace detail {
  2110. #if defined(_WIN32)
  2111. inline std::wstring u8string_to_wstring(const char *s) {
  2112. if (!s) { return std::wstring(); }
  2113. auto len = static_cast<int>(strlen(s));
  2114. if (!len) { return std::wstring(); }
  2115. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2116. if (!wlen) { return std::wstring(); }
  2117. std::wstring ws;
  2118. ws.resize(wlen);
  2119. wlen = ::MultiByteToWideChar(
  2120. CP_UTF8, 0, s, len,
  2121. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2122. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2123. return ws;
  2124. }
  2125. #endif
  2126. struct FileStat {
  2127. FileStat(const std::string &path);
  2128. bool is_file() const;
  2129. bool is_dir() const;
  2130. time_t mtime() const;
  2131. size_t size() const;
  2132. private:
  2133. #if defined(_WIN32)
  2134. struct _stat st_;
  2135. #else
  2136. struct stat st_;
  2137. #endif
  2138. int ret_ = -1;
  2139. };
  2140. std::string make_host_and_port_string(const std::string &host, int port,
  2141. bool is_ssl);
  2142. std::string trim_copy(const std::string &s);
  2143. void divide(
  2144. const char *data, std::size_t size, char d,
  2145. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2146. fn);
  2147. void divide(
  2148. const std::string &str, char d,
  2149. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2150. fn);
  2151. void split(const char *b, const char *e, char d,
  2152. std::function<void(const char *, const char *)> fn);
  2153. void split(const char *b, const char *e, char d, size_t m,
  2154. std::function<void(const char *, const char *)> fn);
  2155. bool process_client_socket(
  2156. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2157. time_t write_timeout_sec, time_t write_timeout_usec,
  2158. time_t max_timeout_msec,
  2159. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2160. std::function<bool(Stream &)> callback);
  2161. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2162. int port, int address_family, bool tcp_nodelay,
  2163. bool ipv6_v6only, SocketOptions socket_options,
  2164. time_t connection_timeout_sec,
  2165. time_t connection_timeout_usec,
  2166. time_t read_timeout_sec, time_t read_timeout_usec,
  2167. time_t write_timeout_sec,
  2168. time_t write_timeout_usec,
  2169. const std::string &intf, Error &error);
  2170. const char *get_header_value(const Headers &headers, const std::string &key,
  2171. const char *def, size_t id);
  2172. std::string params_to_query_str(const Params &params);
  2173. void parse_query_text(const char *data, std::size_t size, Params &params);
  2174. void parse_query_text(const std::string &s, Params &params);
  2175. bool parse_multipart_boundary(const std::string &content_type,
  2176. std::string &boundary);
  2177. bool parse_range_header(const std::string &s, Ranges &ranges);
  2178. bool parse_accept_header(const std::string &s,
  2179. std::vector<std::string> &content_types);
  2180. int close_socket(socket_t sock);
  2181. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2182. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2183. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2184. EncodingType encoding_type(const Request &req, const Response &res);
  2185. class BufferStream final : public Stream {
  2186. public:
  2187. BufferStream() = default;
  2188. ~BufferStream() override = default;
  2189. bool is_readable() const override;
  2190. bool wait_readable() const override;
  2191. bool wait_writable() const override;
  2192. ssize_t read(char *ptr, size_t size) override;
  2193. ssize_t write(const char *ptr, size_t size) override;
  2194. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2195. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2196. socket_t socket() const override;
  2197. time_t duration() const override;
  2198. const std::string &get_buffer() const;
  2199. private:
  2200. std::string buffer;
  2201. size_t position = 0;
  2202. };
  2203. class compressor {
  2204. public:
  2205. virtual ~compressor() = default;
  2206. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2207. virtual bool compress(const char *data, size_t data_length, bool last,
  2208. Callback callback) = 0;
  2209. };
  2210. class decompressor {
  2211. public:
  2212. virtual ~decompressor() = default;
  2213. virtual bool is_valid() const = 0;
  2214. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2215. virtual bool decompress(const char *data, size_t data_length,
  2216. Callback callback) = 0;
  2217. };
  2218. class nocompressor final : public compressor {
  2219. public:
  2220. ~nocompressor() override = default;
  2221. bool compress(const char *data, size_t data_length, bool /*last*/,
  2222. Callback callback) override;
  2223. };
  2224. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2225. class gzip_compressor final : public compressor {
  2226. public:
  2227. gzip_compressor();
  2228. ~gzip_compressor() override;
  2229. bool compress(const char *data, size_t data_length, bool last,
  2230. Callback callback) override;
  2231. private:
  2232. bool is_valid_ = false;
  2233. z_stream strm_;
  2234. };
  2235. class gzip_decompressor final : public decompressor {
  2236. public:
  2237. gzip_decompressor();
  2238. ~gzip_decompressor() override;
  2239. bool is_valid() const override;
  2240. bool decompress(const char *data, size_t data_length,
  2241. Callback callback) override;
  2242. private:
  2243. bool is_valid_ = false;
  2244. z_stream strm_;
  2245. };
  2246. #endif
  2247. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2248. class brotli_compressor final : public compressor {
  2249. public:
  2250. brotli_compressor();
  2251. ~brotli_compressor();
  2252. bool compress(const char *data, size_t data_length, bool last,
  2253. Callback callback) override;
  2254. private:
  2255. BrotliEncoderState *state_ = nullptr;
  2256. };
  2257. class brotli_decompressor final : public decompressor {
  2258. public:
  2259. brotli_decompressor();
  2260. ~brotli_decompressor();
  2261. bool is_valid() const override;
  2262. bool decompress(const char *data, size_t data_length,
  2263. Callback callback) override;
  2264. private:
  2265. BrotliDecoderResult decoder_r;
  2266. BrotliDecoderState *decoder_s = nullptr;
  2267. };
  2268. #endif
  2269. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2270. class zstd_compressor : public compressor {
  2271. public:
  2272. zstd_compressor();
  2273. ~zstd_compressor();
  2274. bool compress(const char *data, size_t data_length, bool last,
  2275. Callback callback) override;
  2276. private:
  2277. ZSTD_CCtx *ctx_ = nullptr;
  2278. };
  2279. class zstd_decompressor : public decompressor {
  2280. public:
  2281. zstd_decompressor();
  2282. ~zstd_decompressor();
  2283. bool is_valid() const override;
  2284. bool decompress(const char *data, size_t data_length,
  2285. Callback callback) override;
  2286. private:
  2287. ZSTD_DCtx *ctx_ = nullptr;
  2288. };
  2289. #endif
  2290. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2291. // to store data. The call can set memory on stack for performance.
  2292. class stream_line_reader {
  2293. public:
  2294. stream_line_reader(Stream &strm, char *fixed_buffer,
  2295. size_t fixed_buffer_size);
  2296. const char *ptr() const;
  2297. size_t size() const;
  2298. bool end_with_crlf() const;
  2299. bool getline();
  2300. private:
  2301. void append(char c);
  2302. Stream &strm_;
  2303. char *fixed_buffer_;
  2304. const size_t fixed_buffer_size_;
  2305. size_t fixed_buffer_used_size_ = 0;
  2306. std::string growable_buffer_;
  2307. };
  2308. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2309. const Headers &src_headers);
  2310. struct ChunkedDecoder {
  2311. Stream &strm;
  2312. size_t chunk_remaining = 0;
  2313. bool finished = false;
  2314. char line_buf[64];
  2315. size_t last_chunk_total = 0;
  2316. size_t last_chunk_offset = 0;
  2317. explicit ChunkedDecoder(Stream &s);
  2318. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2319. size_t &out_chunk_total);
  2320. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2321. };
  2322. class mmap {
  2323. public:
  2324. mmap(const char *path);
  2325. ~mmap();
  2326. bool open(const char *path);
  2327. void close();
  2328. bool is_open() const;
  2329. size_t size() const;
  2330. const char *data() const;
  2331. private:
  2332. #if defined(_WIN32)
  2333. HANDLE hFile_ = NULL;
  2334. HANDLE hMapping_ = NULL;
  2335. #else
  2336. int fd_ = -1;
  2337. #endif
  2338. size_t size_ = 0;
  2339. void *addr_ = nullptr;
  2340. bool is_open_empty_file = false;
  2341. };
  2342. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2343. namespace fields {
  2344. bool is_token_char(char c);
  2345. bool is_token(const std::string &s);
  2346. bool is_field_name(const std::string &s);
  2347. bool is_vchar(char c);
  2348. bool is_obs_text(char c);
  2349. bool is_field_vchar(char c);
  2350. bool is_field_content(const std::string &s);
  2351. bool is_field_value(const std::string &s);
  2352. } // namespace fields
  2353. } // namespace detail
  2354. /*
  2355. * TLS Abstraction Layer Declarations
  2356. */
  2357. #ifdef CPPHTTPLIB_SSL_ENABLED
  2358. // TLS abstraction layer - backend-specific type declarations
  2359. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2360. namespace tls {
  2361. namespace impl {
  2362. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2363. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2364. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2365. struct MbedTlsContext {
  2366. mbedtls_ssl_config conf;
  2367. mbedtls_entropy_context entropy;
  2368. mbedtls_ctr_drbg_context ctr_drbg;
  2369. mbedtls_x509_crt ca_chain;
  2370. mbedtls_x509_crt own_cert;
  2371. mbedtls_pk_context own_key;
  2372. bool is_server = false;
  2373. bool verify_client = false;
  2374. bool has_verify_callback = false;
  2375. MbedTlsContext();
  2376. ~MbedTlsContext();
  2377. MbedTlsContext(const MbedTlsContext &) = delete;
  2378. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2379. };
  2380. } // namespace impl
  2381. } // namespace tls
  2382. #endif
  2383. #endif // CPPHTTPLIB_SSL_ENABLED
  2384. namespace stream {
  2385. class Result {
  2386. public:
  2387. Result() : chunk_size_(8192) {}
  2388. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192)
  2389. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  2390. Result(Result &&other) noexcept
  2391. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  2392. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  2393. finished_(other.finished_) {
  2394. other.current_size_ = 0;
  2395. other.finished_ = true;
  2396. }
  2397. Result &operator=(Result &&other) noexcept {
  2398. if (this != &other) {
  2399. handle_ = std::move(other.handle_);
  2400. buffer_ = std::move(other.buffer_);
  2401. current_size_ = other.current_size_;
  2402. chunk_size_ = other.chunk_size_;
  2403. finished_ = other.finished_;
  2404. other.current_size_ = 0;
  2405. other.finished_ = true;
  2406. }
  2407. return *this;
  2408. }
  2409. Result(const Result &) = delete;
  2410. Result &operator=(const Result &) = delete;
  2411. // Check if the result is valid (connection succeeded and response received)
  2412. bool is_valid() const { return handle_.is_valid(); }
  2413. explicit operator bool() const { return is_valid(); }
  2414. // Response status code
  2415. int status() const {
  2416. return handle_.response ? handle_.response->status : -1;
  2417. }
  2418. // Response headers
  2419. const Headers &headers() const {
  2420. static const Headers empty_headers;
  2421. return handle_.response ? handle_.response->headers : empty_headers;
  2422. }
  2423. std::string get_header_value(const std::string &key,
  2424. const char *def = "") const {
  2425. return handle_.response ? handle_.response->get_header_value(key, def)
  2426. : def;
  2427. }
  2428. bool has_header(const std::string &key) const {
  2429. return handle_.response ? handle_.response->has_header(key) : false;
  2430. }
  2431. // Error information
  2432. Error error() const { return handle_.error; }
  2433. Error read_error() const { return handle_.get_read_error(); }
  2434. bool has_read_error() const { return handle_.has_read_error(); }
  2435. // Streaming iteration API
  2436. // Call next() to read the next chunk, then access data via data()/size()
  2437. // Returns true if data was read, false when stream is exhausted
  2438. bool next() {
  2439. if (!handle_.is_valid() || finished_) { return false; }
  2440. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  2441. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  2442. if (n > 0) {
  2443. current_size_ = static_cast<size_t>(n);
  2444. return true;
  2445. }
  2446. current_size_ = 0;
  2447. finished_ = true;
  2448. return false;
  2449. }
  2450. // Pointer to current chunk data (valid after next() returns true)
  2451. const char *data() const { return buffer_.data(); }
  2452. // Size of current chunk (valid after next() returns true)
  2453. size_t size() const { return current_size_; }
  2454. // Convenience method: read all remaining data into a string
  2455. std::string read_all() {
  2456. std::string result;
  2457. while (next()) {
  2458. result.append(data(), size());
  2459. }
  2460. return result;
  2461. }
  2462. private:
  2463. ClientImpl::StreamHandle handle_;
  2464. std::string buffer_;
  2465. size_t current_size_ = 0;
  2466. size_t chunk_size_;
  2467. bool finished_ = false;
  2468. };
  2469. // GET
  2470. template <typename ClientType>
  2471. inline Result Get(ClientType &cli, const std::string &path,
  2472. size_t chunk_size = 8192) {
  2473. return Result{cli.open_stream("GET", path), chunk_size};
  2474. }
  2475. template <typename ClientType>
  2476. inline Result Get(ClientType &cli, const std::string &path,
  2477. const Headers &headers, size_t chunk_size = 8192) {
  2478. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2479. }
  2480. template <typename ClientType>
  2481. inline Result Get(ClientType &cli, const std::string &path,
  2482. const Params &params, size_t chunk_size = 8192) {
  2483. return Result{cli.open_stream("GET", path, params), chunk_size};
  2484. }
  2485. template <typename ClientType>
  2486. inline Result Get(ClientType &cli, const std::string &path,
  2487. const Params &params, const Headers &headers,
  2488. size_t chunk_size = 8192) {
  2489. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2490. }
  2491. // POST
  2492. template <typename ClientType>
  2493. inline Result Post(ClientType &cli, const std::string &path,
  2494. const std::string &body, const std::string &content_type,
  2495. size_t chunk_size = 8192) {
  2496. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2497. chunk_size};
  2498. }
  2499. template <typename ClientType>
  2500. inline Result Post(ClientType &cli, const std::string &path,
  2501. const Headers &headers, const std::string &body,
  2502. const std::string &content_type, size_t chunk_size = 8192) {
  2503. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2504. chunk_size};
  2505. }
  2506. template <typename ClientType>
  2507. inline Result Post(ClientType &cli, const std::string &path,
  2508. const Params &params, const std::string &body,
  2509. const std::string &content_type, size_t chunk_size = 8192) {
  2510. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2511. chunk_size};
  2512. }
  2513. template <typename ClientType>
  2514. inline Result Post(ClientType &cli, const std::string &path,
  2515. const Params &params, const Headers &headers,
  2516. const std::string &body, const std::string &content_type,
  2517. size_t chunk_size = 8192) {
  2518. return Result{
  2519. cli.open_stream("POST", path, params, headers, body, content_type),
  2520. chunk_size};
  2521. }
  2522. // PUT
  2523. template <typename ClientType>
  2524. inline Result Put(ClientType &cli, const std::string &path,
  2525. const std::string &body, const std::string &content_type,
  2526. size_t chunk_size = 8192) {
  2527. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2528. chunk_size};
  2529. }
  2530. template <typename ClientType>
  2531. inline Result Put(ClientType &cli, const std::string &path,
  2532. const Headers &headers, const std::string &body,
  2533. const std::string &content_type, size_t chunk_size = 8192) {
  2534. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2535. chunk_size};
  2536. }
  2537. template <typename ClientType>
  2538. inline Result Put(ClientType &cli, const std::string &path,
  2539. const Params &params, const std::string &body,
  2540. const std::string &content_type, size_t chunk_size = 8192) {
  2541. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2542. chunk_size};
  2543. }
  2544. template <typename ClientType>
  2545. inline Result Put(ClientType &cli, const std::string &path,
  2546. const Params &params, const Headers &headers,
  2547. const std::string &body, const std::string &content_type,
  2548. size_t chunk_size = 8192) {
  2549. return Result{
  2550. cli.open_stream("PUT", path, params, headers, body, content_type),
  2551. chunk_size};
  2552. }
  2553. // PATCH
  2554. template <typename ClientType>
  2555. inline Result Patch(ClientType &cli, const std::string &path,
  2556. const std::string &body, const std::string &content_type,
  2557. size_t chunk_size = 8192) {
  2558. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2559. chunk_size};
  2560. }
  2561. template <typename ClientType>
  2562. inline Result Patch(ClientType &cli, const std::string &path,
  2563. const Headers &headers, const std::string &body,
  2564. const std::string &content_type, size_t chunk_size = 8192) {
  2565. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2566. chunk_size};
  2567. }
  2568. template <typename ClientType>
  2569. inline Result Patch(ClientType &cli, const std::string &path,
  2570. const Params &params, const std::string &body,
  2571. const std::string &content_type, size_t chunk_size = 8192) {
  2572. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2573. chunk_size};
  2574. }
  2575. template <typename ClientType>
  2576. inline Result Patch(ClientType &cli, const std::string &path,
  2577. const Params &params, const Headers &headers,
  2578. const std::string &body, const std::string &content_type,
  2579. size_t chunk_size = 8192) {
  2580. return Result{
  2581. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2582. chunk_size};
  2583. }
  2584. // DELETE
  2585. template <typename ClientType>
  2586. inline Result Delete(ClientType &cli, const std::string &path,
  2587. size_t chunk_size = 8192) {
  2588. return Result{cli.open_stream("DELETE", path), chunk_size};
  2589. }
  2590. template <typename ClientType>
  2591. inline Result Delete(ClientType &cli, const std::string &path,
  2592. const Headers &headers, size_t chunk_size = 8192) {
  2593. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2594. }
  2595. template <typename ClientType>
  2596. inline Result Delete(ClientType &cli, const std::string &path,
  2597. const std::string &body, const std::string &content_type,
  2598. size_t chunk_size = 8192) {
  2599. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2600. chunk_size};
  2601. }
  2602. template <typename ClientType>
  2603. inline Result Delete(ClientType &cli, const std::string &path,
  2604. const Headers &headers, const std::string &body,
  2605. const std::string &content_type,
  2606. size_t chunk_size = 8192) {
  2607. return Result{
  2608. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2609. chunk_size};
  2610. }
  2611. template <typename ClientType>
  2612. inline Result Delete(ClientType &cli, const std::string &path,
  2613. const Params &params, size_t chunk_size = 8192) {
  2614. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2615. }
  2616. template <typename ClientType>
  2617. inline Result Delete(ClientType &cli, const std::string &path,
  2618. const Params &params, const Headers &headers,
  2619. size_t chunk_size = 8192) {
  2620. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2621. }
  2622. template <typename ClientType>
  2623. inline Result Delete(ClientType &cli, const std::string &path,
  2624. const Params &params, const std::string &body,
  2625. const std::string &content_type,
  2626. size_t chunk_size = 8192) {
  2627. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2628. chunk_size};
  2629. }
  2630. template <typename ClientType>
  2631. inline Result Delete(ClientType &cli, const std::string &path,
  2632. const Params &params, const Headers &headers,
  2633. const std::string &body, const std::string &content_type,
  2634. size_t chunk_size = 8192) {
  2635. return Result{
  2636. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2637. chunk_size};
  2638. }
  2639. // HEAD
  2640. template <typename ClientType>
  2641. inline Result Head(ClientType &cli, const std::string &path,
  2642. size_t chunk_size = 8192) {
  2643. return Result{cli.open_stream("HEAD", path), chunk_size};
  2644. }
  2645. template <typename ClientType>
  2646. inline Result Head(ClientType &cli, const std::string &path,
  2647. const Headers &headers, size_t chunk_size = 8192) {
  2648. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2649. }
  2650. template <typename ClientType>
  2651. inline Result Head(ClientType &cli, const std::string &path,
  2652. const Params &params, size_t chunk_size = 8192) {
  2653. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2654. }
  2655. template <typename ClientType>
  2656. inline Result Head(ClientType &cli, const std::string &path,
  2657. const Params &params, const Headers &headers,
  2658. size_t chunk_size = 8192) {
  2659. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2660. }
  2661. // OPTIONS
  2662. template <typename ClientType>
  2663. inline Result Options(ClientType &cli, const std::string &path,
  2664. size_t chunk_size = 8192) {
  2665. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2666. }
  2667. template <typename ClientType>
  2668. inline Result Options(ClientType &cli, const std::string &path,
  2669. const Headers &headers, size_t chunk_size = 8192) {
  2670. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2671. }
  2672. template <typename ClientType>
  2673. inline Result Options(ClientType &cli, const std::string &path,
  2674. const Params &params, size_t chunk_size = 8192) {
  2675. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2676. }
  2677. template <typename ClientType>
  2678. inline Result Options(ClientType &cli, const std::string &path,
  2679. const Params &params, const Headers &headers,
  2680. size_t chunk_size = 8192) {
  2681. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2682. }
  2683. } // namespace stream
  2684. namespace sse {
  2685. struct SSEMessage {
  2686. std::string event; // Event type (default: "message")
  2687. std::string data; // Event payload
  2688. std::string id; // Event ID for Last-Event-ID header
  2689. SSEMessage() : event("message") {}
  2690. void clear() {
  2691. event = "message";
  2692. data.clear();
  2693. id.clear();
  2694. }
  2695. };
  2696. class SSEClient {
  2697. public:
  2698. using MessageHandler = std::function<void(const SSEMessage &)>;
  2699. using ErrorHandler = std::function<void(Error)>;
  2700. using OpenHandler = std::function<void()>;
  2701. SSEClient(Client &client, const std::string &path)
  2702. : client_(client), path_(path) {}
  2703. SSEClient(Client &client, const std::string &path, const Headers &headers)
  2704. : client_(client), path_(path), headers_(headers) {}
  2705. ~SSEClient() { stop(); }
  2706. SSEClient(const SSEClient &) = delete;
  2707. SSEClient &operator=(const SSEClient &) = delete;
  2708. // Event handlers
  2709. SSEClient &on_message(MessageHandler handler) {
  2710. on_message_ = std::move(handler);
  2711. return *this;
  2712. }
  2713. SSEClient &on_event(const std::string &type, MessageHandler handler) {
  2714. event_handlers_[type] = std::move(handler);
  2715. return *this;
  2716. }
  2717. SSEClient &on_open(OpenHandler handler) {
  2718. on_open_ = std::move(handler);
  2719. return *this;
  2720. }
  2721. SSEClient &on_error(ErrorHandler handler) {
  2722. on_error_ = std::move(handler);
  2723. return *this;
  2724. }
  2725. SSEClient &set_reconnect_interval(int ms) {
  2726. reconnect_interval_ms_ = ms;
  2727. return *this;
  2728. }
  2729. SSEClient &set_max_reconnect_attempts(int n) {
  2730. max_reconnect_attempts_ = n;
  2731. return *this;
  2732. }
  2733. // State accessors
  2734. bool is_connected() const { return connected_.load(); }
  2735. const std::string &last_event_id() const { return last_event_id_; }
  2736. // Blocking start - runs event loop with auto-reconnect
  2737. void start() {
  2738. running_.store(true);
  2739. run_event_loop();
  2740. }
  2741. // Non-blocking start - runs in background thread
  2742. void start_async() {
  2743. running_.store(true);
  2744. async_thread_ = std::thread([this]() { run_event_loop(); });
  2745. }
  2746. // Stop the client (thread-safe)
  2747. void stop() {
  2748. running_.store(false);
  2749. client_.stop(); // Cancel any pending operations
  2750. if (async_thread_.joinable()) { async_thread_.join(); }
  2751. }
  2752. private:
  2753. // Parse a single SSE field line
  2754. // Returns true if this line ends an event (blank line)
  2755. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms) {
  2756. // Blank line signals end of event
  2757. if (line.empty() || line == "\r") { return true; }
  2758. // Lines starting with ':' are comments (ignored)
  2759. if (!line.empty() && line[0] == ':') { return false; }
  2760. // Find the colon separator
  2761. auto colon_pos = line.find(':');
  2762. if (colon_pos == std::string::npos) {
  2763. // Line with no colon is treated as field name with empty value
  2764. return false;
  2765. }
  2766. auto field = line.substr(0, colon_pos);
  2767. std::string value;
  2768. // Value starts after colon, skip optional single space
  2769. if (colon_pos + 1 < line.size()) {
  2770. auto value_start = colon_pos + 1;
  2771. if (line[value_start] == ' ') { value_start++; }
  2772. value = line.substr(value_start);
  2773. // Remove trailing \r if present
  2774. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  2775. }
  2776. // Handle known fields
  2777. if (field == "event") {
  2778. msg.event = value;
  2779. } else if (field == "data") {
  2780. // Multiple data lines are concatenated with newlines
  2781. if (!msg.data.empty()) { msg.data += "\n"; }
  2782. msg.data += value;
  2783. } else if (field == "id") {
  2784. // Empty id is valid (clears the last event ID)
  2785. msg.id = value;
  2786. } else if (field == "retry") {
  2787. // Parse retry interval in milliseconds
  2788. {
  2789. int v = 0;
  2790. auto res =
  2791. detail::from_chars(value.data(), value.data() + value.size(), v);
  2792. if (res.ec == std::errc{}) { retry_ms = v; }
  2793. }
  2794. }
  2795. // Unknown fields are ignored per SSE spec
  2796. return false;
  2797. }
  2798. // Main event loop with auto-reconnect
  2799. void run_event_loop() {
  2800. auto reconnect_count = 0;
  2801. while (running_.load()) {
  2802. // Build headers, including Last-Event-ID if we have one
  2803. auto request_headers = headers_;
  2804. if (!last_event_id_.empty()) {
  2805. request_headers.emplace("Last-Event-ID", last_event_id_);
  2806. }
  2807. // Open streaming connection
  2808. auto result = stream::Get(client_, path_, request_headers);
  2809. // Connection error handling
  2810. if (!result) {
  2811. connected_.store(false);
  2812. if (on_error_) { on_error_(result.error()); }
  2813. if (!should_reconnect(reconnect_count)) { break; }
  2814. wait_for_reconnect();
  2815. reconnect_count++;
  2816. continue;
  2817. }
  2818. if (result.status() != 200) {
  2819. connected_.store(false);
  2820. // For certain errors, don't reconnect
  2821. if (result.status() == 204 || // No Content - server wants us to stop
  2822. result.status() == 404 || // Not Found
  2823. result.status() == 401 || // Unauthorized
  2824. result.status() == 403) { // Forbidden
  2825. if (on_error_) { on_error_(Error::Connection); }
  2826. break;
  2827. }
  2828. if (on_error_) { on_error_(Error::Connection); }
  2829. if (!should_reconnect(reconnect_count)) { break; }
  2830. wait_for_reconnect();
  2831. reconnect_count++;
  2832. continue;
  2833. }
  2834. // Connection successful
  2835. connected_.store(true);
  2836. reconnect_count = 0;
  2837. if (on_open_) { on_open_(); }
  2838. // Event receiving loop
  2839. std::string buffer;
  2840. SSEMessage current_msg;
  2841. while (running_.load() && result.next()) {
  2842. buffer.append(result.data(), result.size());
  2843. // Process complete lines in the buffer
  2844. size_t line_start = 0;
  2845. size_t newline_pos;
  2846. while ((newline_pos = buffer.find('\n', line_start)) !=
  2847. std::string::npos) {
  2848. auto line = buffer.substr(line_start, newline_pos - line_start);
  2849. line_start = newline_pos + 1;
  2850. // Parse the line and check if event is complete
  2851. auto event_complete =
  2852. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  2853. if (event_complete && !current_msg.data.empty()) {
  2854. // Update last_event_id for reconnection
  2855. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  2856. // Dispatch event to appropriate handler
  2857. dispatch_event(current_msg);
  2858. current_msg.clear();
  2859. }
  2860. }
  2861. // Keep unprocessed data in buffer
  2862. buffer.erase(0, line_start);
  2863. }
  2864. // Connection ended
  2865. connected_.store(false);
  2866. if (!running_.load()) { break; }
  2867. // Check for read errors
  2868. if (result.has_read_error()) {
  2869. if (on_error_) { on_error_(result.read_error()); }
  2870. }
  2871. if (!should_reconnect(reconnect_count)) { break; }
  2872. wait_for_reconnect();
  2873. reconnect_count++;
  2874. }
  2875. connected_.store(false);
  2876. }
  2877. // Dispatch event to appropriate handler
  2878. void dispatch_event(const SSEMessage &msg) {
  2879. // Check for specific event type handler first
  2880. auto it = event_handlers_.find(msg.event);
  2881. if (it != event_handlers_.end()) {
  2882. it->second(msg);
  2883. return;
  2884. }
  2885. // Fall back to generic message handler
  2886. if (on_message_) { on_message_(msg); }
  2887. }
  2888. // Check if we should attempt to reconnect
  2889. bool should_reconnect(int count) const {
  2890. if (!running_.load()) { return false; }
  2891. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  2892. return count < max_reconnect_attempts_;
  2893. }
  2894. // Wait for reconnect interval
  2895. void wait_for_reconnect() {
  2896. // Use small increments to check running_ flag frequently
  2897. auto waited = 0;
  2898. while (running_.load() && waited < reconnect_interval_ms_) {
  2899. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2900. waited += 100;
  2901. }
  2902. }
  2903. // Client and path
  2904. Client &client_;
  2905. std::string path_;
  2906. Headers headers_;
  2907. // Callbacks
  2908. MessageHandler on_message_;
  2909. std::map<std::string, MessageHandler> event_handlers_;
  2910. OpenHandler on_open_;
  2911. ErrorHandler on_error_;
  2912. // Configuration
  2913. int reconnect_interval_ms_ = 3000;
  2914. int max_reconnect_attempts_ = 0; // 0 = unlimited
  2915. // State
  2916. std::atomic<bool> running_{false};
  2917. std::atomic<bool> connected_{false};
  2918. std::string last_event_id_;
  2919. // Async support
  2920. std::thread async_thread_;
  2921. };
  2922. } // namespace sse
  2923. // ----------------------------------------------------------------------------
  2924. /*
  2925. * Implementation that will be part of the .cc file if split into .h + .cc.
  2926. */
  2927. #ifdef CPPHTTPLIB_SSL_ENABLED
  2928. /*
  2929. * TLS abstraction layer - internal function declarations
  2930. * These are implementation details and not part of the public API.
  2931. */
  2932. namespace tls {
  2933. // Client context
  2934. ctx_t create_client_context();
  2935. void free_context(ctx_t ctx);
  2936. bool set_min_version(ctx_t ctx, Version version);
  2937. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  2938. bool load_ca_file(ctx_t ctx, const char *file_path);
  2939. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  2940. bool load_system_certs(ctx_t ctx);
  2941. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  2942. const char *password);
  2943. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  2944. const char *key_path, const char *password);
  2945. // Server context
  2946. ctx_t create_server_context();
  2947. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  2948. const char *password);
  2949. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  2950. const char *key_path, const char *password);
  2951. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  2952. void set_verify_client(ctx_t ctx, bool require);
  2953. // Session management
  2954. session_t create_session(ctx_t ctx, socket_t sock);
  2955. void free_session(session_t session);
  2956. bool set_sni(session_t session, const char *hostname);
  2957. bool set_hostname(session_t session, const char *hostname);
  2958. // Handshake (non-blocking capable)
  2959. TlsError connect(session_t session);
  2960. TlsError accept(session_t session);
  2961. // Handshake with timeout (blocking until timeout)
  2962. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  2963. time_t timeout_usec, TlsError *err);
  2964. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  2965. time_t timeout_usec, TlsError *err);
  2966. // I/O (non-blocking capable)
  2967. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  2968. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  2969. int pending(const_session_t session);
  2970. void shutdown(session_t session, bool graceful);
  2971. // Connection state
  2972. bool is_peer_closed(session_t session, socket_t sock);
  2973. // Certificate verification
  2974. cert_t get_peer_cert(const_session_t session);
  2975. void free_cert(cert_t cert);
  2976. bool verify_hostname(cert_t cert, const char *hostname);
  2977. uint64_t hostname_mismatch_code();
  2978. long get_verify_result(const_session_t session);
  2979. // Certificate introspection
  2980. std::string get_cert_subject_cn(cert_t cert);
  2981. std::string get_cert_issuer_name(cert_t cert);
  2982. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  2983. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  2984. std::string get_cert_serial(cert_t cert);
  2985. const char *get_sni(const_session_t session);
  2986. // CA store management
  2987. ca_store_t create_ca_store(const char *pem, size_t len);
  2988. void free_ca_store(ca_store_t store);
  2989. bool set_ca_store(ctx_t ctx, ca_store_t store);
  2990. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  2991. std::vector<std::string> get_ca_names(ctx_t ctx);
  2992. // Dynamic certificate update (for servers)
  2993. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  2994. const char *password);
  2995. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  2996. // Certificate verification callback
  2997. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  2998. long get_verify_error(const_session_t session);
  2999. std::string verify_error_string(long error_code);
  3000. // TlsError information
  3001. uint64_t peek_error();
  3002. uint64_t get_error();
  3003. std::string error_string(uint64_t code);
  3004. } // namespace tls
  3005. #endif // CPPHTTPLIB_SSL_ENABLED
  3006. /*
  3007. * Group 1: detail namespace - Non-SSL utilities
  3008. */
  3009. namespace detail {
  3010. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3011. const void *optval, socklen_t optlen) {
  3012. return setsockopt(sock, level, optname,
  3013. #ifdef _WIN32
  3014. reinterpret_cast<const char *>(optval),
  3015. #else
  3016. optval,
  3017. #endif
  3018. optlen) == 0;
  3019. }
  3020. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  3021. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  3022. }
  3023. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3024. time_t sec, time_t usec) {
  3025. #ifdef _WIN32
  3026. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3027. #else
  3028. timeval timeout;
  3029. timeout.tv_sec = static_cast<long>(sec);
  3030. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3031. #endif
  3032. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3033. }
  3034. inline bool is_hex(char c, int &v) {
  3035. if (isdigit(c)) {
  3036. v = c - '0';
  3037. return true;
  3038. } else if ('A' <= c && c <= 'F') {
  3039. v = c - 'A' + 10;
  3040. return true;
  3041. } else if ('a' <= c && c <= 'f') {
  3042. v = c - 'a' + 10;
  3043. return true;
  3044. }
  3045. return false;
  3046. }
  3047. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3048. int &val) {
  3049. if (i >= s.size()) { return false; }
  3050. val = 0;
  3051. for (; cnt; i++, cnt--) {
  3052. if (!s[i]) { return false; }
  3053. auto v = 0;
  3054. if (is_hex(s[i], v)) {
  3055. val = val * 16 + v;
  3056. } else {
  3057. return false;
  3058. }
  3059. }
  3060. return true;
  3061. }
  3062. inline std::string from_i_to_hex(size_t n) {
  3063. static const auto charset = "0123456789abcdef";
  3064. std::string ret;
  3065. do {
  3066. ret = charset[n & 15] + ret;
  3067. n >>= 4;
  3068. } while (n > 0);
  3069. return ret;
  3070. }
  3071. inline std::string compute_etag(const FileStat &fs) {
  3072. if (!fs.is_file()) { return std::string(); }
  3073. // If mtime cannot be determined (negative value indicates an error
  3074. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3075. // value like 0 could collide with a real file that legitimately has
  3076. // mtime == 0 (epoch) and lead to misleading validators.
  3077. auto mtime_raw = fs.mtime();
  3078. if (mtime_raw < 0) { return std::string(); }
  3079. auto mtime = static_cast<size_t>(mtime_raw);
  3080. auto size = fs.size();
  3081. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3082. from_i_to_hex(size) + "\"";
  3083. }
  3084. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3085. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3086. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3087. inline std::string file_mtime_to_http_date(time_t mtime) {
  3088. if (mtime < 0) { return std::string(); }
  3089. struct tm tm_buf;
  3090. #ifdef _WIN32
  3091. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3092. #else
  3093. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3094. #endif
  3095. char buf[64];
  3096. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3097. return std::string();
  3098. }
  3099. return std::string(buf);
  3100. }
  3101. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3102. inline time_t parse_http_date(const std::string &date_str) {
  3103. struct tm tm_buf;
  3104. // Create a classic locale object once for all parsing attempts
  3105. const std::locale classic_locale = std::locale::classic();
  3106. // Try to parse using std::get_time (C++11, cross-platform)
  3107. auto try_parse = [&](const char *fmt) -> bool {
  3108. std::istringstream ss(date_str);
  3109. ss.imbue(classic_locale);
  3110. memset(&tm_buf, 0, sizeof(tm_buf));
  3111. ss >> std::get_time(&tm_buf, fmt);
  3112. return !ss.fail();
  3113. };
  3114. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3115. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3116. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3117. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3118. // asctime format: "Sun Nov 6 08:49:37 1994"
  3119. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3120. return static_cast<time_t>(-1);
  3121. }
  3122. }
  3123. }
  3124. #ifdef _WIN32
  3125. return _mkgmtime(&tm_buf);
  3126. #elif defined _AIX
  3127. return mktime(&tm_buf);
  3128. #else
  3129. return timegm(&tm_buf);
  3130. #endif
  3131. }
  3132. inline bool is_weak_etag(const std::string &s) {
  3133. // Check if the string is a weak ETag (starts with 'W/"')
  3134. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3135. }
  3136. inline bool is_strong_etag(const std::string &s) {
  3137. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3138. // chars)
  3139. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3140. }
  3141. inline size_t to_utf8(int code, char *buff) {
  3142. if (code < 0x0080) {
  3143. buff[0] = static_cast<char>(code & 0x7F);
  3144. return 1;
  3145. } else if (code < 0x0800) {
  3146. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3147. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3148. return 2;
  3149. } else if (code < 0xD800) {
  3150. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3151. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3152. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3153. return 3;
  3154. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3155. return 0;
  3156. } else if (code < 0x10000) {
  3157. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3158. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3159. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3160. return 3;
  3161. } else if (code < 0x110000) {
  3162. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3163. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3164. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3165. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3166. return 4;
  3167. }
  3168. // NOTREACHED
  3169. return 0;
  3170. }
  3171. // NOTE: This code came up with the following stackoverflow post:
  3172. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3173. inline std::string base64_encode(const std::string &in) {
  3174. static const auto lookup =
  3175. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3176. std::string out;
  3177. out.reserve(in.size());
  3178. auto val = 0;
  3179. auto valb = -6;
  3180. for (auto c : in) {
  3181. val = (val << 8) + static_cast<uint8_t>(c);
  3182. valb += 8;
  3183. while (valb >= 0) {
  3184. out.push_back(lookup[(val >> valb) & 0x3F]);
  3185. valb -= 6;
  3186. }
  3187. }
  3188. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3189. while (out.size() % 4) {
  3190. out.push_back('=');
  3191. }
  3192. return out;
  3193. }
  3194. inline bool is_valid_path(const std::string &path) {
  3195. size_t level = 0;
  3196. size_t i = 0;
  3197. // Skip slash
  3198. while (i < path.size() && path[i] == '/') {
  3199. i++;
  3200. }
  3201. while (i < path.size()) {
  3202. // Read component
  3203. auto beg = i;
  3204. while (i < path.size() && path[i] != '/') {
  3205. if (path[i] == '\0') {
  3206. return false;
  3207. } else if (path[i] == '\\') {
  3208. return false;
  3209. }
  3210. i++;
  3211. }
  3212. auto len = i - beg;
  3213. assert(len > 0);
  3214. if (!path.compare(beg, len, ".")) {
  3215. ;
  3216. } else if (!path.compare(beg, len, "..")) {
  3217. if (level == 0) { return false; }
  3218. level--;
  3219. } else {
  3220. level++;
  3221. }
  3222. // Skip slash
  3223. while (i < path.size() && path[i] == '/') {
  3224. i++;
  3225. }
  3226. }
  3227. return true;
  3228. }
  3229. inline FileStat::FileStat(const std::string &path) {
  3230. #if defined(_WIN32)
  3231. auto wpath = u8string_to_wstring(path.c_str());
  3232. ret_ = _wstat(wpath.c_str(), &st_);
  3233. #else
  3234. ret_ = stat(path.c_str(), &st_);
  3235. #endif
  3236. }
  3237. inline bool FileStat::is_file() const {
  3238. return ret_ >= 0 && S_ISREG(st_.st_mode);
  3239. }
  3240. inline bool FileStat::is_dir() const {
  3241. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  3242. }
  3243. inline time_t FileStat::mtime() const {
  3244. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  3245. : static_cast<time_t>(-1);
  3246. }
  3247. inline size_t FileStat::size() const {
  3248. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  3249. }
  3250. inline std::string encode_path(const std::string &s) {
  3251. std::string result;
  3252. result.reserve(s.size());
  3253. for (size_t i = 0; s[i]; i++) {
  3254. switch (s[i]) {
  3255. case ' ': result += "%20"; break;
  3256. case '+': result += "%2B"; break;
  3257. case '\r': result += "%0D"; break;
  3258. case '\n': result += "%0A"; break;
  3259. case '\'': result += "%27"; break;
  3260. case ',': result += "%2C"; break;
  3261. // case ':': result += "%3A"; break; // ok? probably...
  3262. case ';': result += "%3B"; break;
  3263. default:
  3264. auto c = static_cast<uint8_t>(s[i]);
  3265. if (c >= 0x80) {
  3266. result += '%';
  3267. char hex[4];
  3268. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  3269. assert(len == 2);
  3270. result.append(hex, static_cast<size_t>(len));
  3271. } else {
  3272. result += s[i];
  3273. }
  3274. break;
  3275. }
  3276. }
  3277. return result;
  3278. }
  3279. inline std::string file_extension(const std::string &path) {
  3280. std::smatch m;
  3281. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  3282. if (std::regex_search(path, m, re)) { return m[1].str(); }
  3283. return std::string();
  3284. }
  3285. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  3286. template <typename T>
  3287. inline bool parse_header(const char *beg, const char *end, T fn);
  3288. template <typename T>
  3289. inline bool parse_header(const char *beg, const char *end, T fn) {
  3290. // Skip trailing spaces and tabs.
  3291. while (beg < end && is_space_or_tab(end[-1])) {
  3292. end--;
  3293. }
  3294. auto p = beg;
  3295. while (p < end && *p != ':') {
  3296. p++;
  3297. }
  3298. auto name = std::string(beg, p);
  3299. if (!detail::fields::is_field_name(name)) { return false; }
  3300. if (p == end) { return false; }
  3301. auto key_end = p;
  3302. if (*p++ != ':') { return false; }
  3303. while (p < end && is_space_or_tab(*p)) {
  3304. p++;
  3305. }
  3306. if (p <= end) {
  3307. auto key_len = key_end - beg;
  3308. if (!key_len) { return false; }
  3309. auto key = std::string(beg, key_end);
  3310. auto val = std::string(p, end);
  3311. if (!detail::fields::is_field_value(val)) { return false; }
  3312. if (case_ignore::equal(key, "Location") ||
  3313. case_ignore::equal(key, "Referer")) {
  3314. fn(key, val);
  3315. } else {
  3316. fn(key, decode_path_component(val));
  3317. }
  3318. return true;
  3319. }
  3320. return false;
  3321. }
  3322. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3323. const Headers &src_headers) {
  3324. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3325. // transfer coding is complete when a chunk with a chunk-size of zero is
  3326. // received, possibly followed by a trailer section, and finally terminated by
  3327. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3328. //
  3329. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3330. // doesn't care for the existence of the final CRLF. In other words, it seems
  3331. // to be ok whether the final CRLF exists or not in the chunked data.
  3332. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3333. //
  3334. // According to the reference code in RFC 9112, cpp-httplib now allows
  3335. // chunked transfer coding data without the final CRLF.
  3336. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3337. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3338. "transfer-encoding",
  3339. "content-length",
  3340. "host",
  3341. "authorization",
  3342. "www-authenticate",
  3343. "proxy-authenticate",
  3344. "proxy-authorization",
  3345. "cookie",
  3346. "set-cookie",
  3347. "cache-control",
  3348. "expect",
  3349. "max-forwards",
  3350. "pragma",
  3351. "range",
  3352. "te",
  3353. "age",
  3354. "expires",
  3355. "date",
  3356. "location",
  3357. "retry-after",
  3358. "vary",
  3359. "warning",
  3360. "content-encoding",
  3361. "content-type",
  3362. "content-range",
  3363. "trailer"};
  3364. case_ignore::unordered_set<std::string> declared_trailers;
  3365. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  3366. if (trailer_header && std::strlen(trailer_header)) {
  3367. auto len = std::strlen(trailer_header);
  3368. split(trailer_header, trailer_header + len, ',',
  3369. [&](const char *b, const char *e) {
  3370. const char *kbeg = b;
  3371. const char *kend = e;
  3372. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  3373. ++kbeg;
  3374. }
  3375. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  3376. --kend;
  3377. }
  3378. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  3379. if (!key.empty() &&
  3380. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  3381. declared_trailers.insert(key);
  3382. }
  3383. });
  3384. }
  3385. size_t trailer_header_count = 0;
  3386. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3387. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3388. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3389. constexpr auto line_terminator_len = 2;
  3390. auto line_beg = line_reader.ptr();
  3391. auto line_end =
  3392. line_reader.ptr() + line_reader.size() - line_terminator_len;
  3393. if (!parse_header(line_beg, line_end,
  3394. [&](const std::string &key, const std::string &val) {
  3395. if (declared_trailers.find(key) !=
  3396. declared_trailers.end()) {
  3397. dest.emplace(key, val);
  3398. trailer_header_count++;
  3399. }
  3400. })) {
  3401. return false;
  3402. }
  3403. if (!line_reader.getline()) { return false; }
  3404. }
  3405. return true;
  3406. }
  3407. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  3408. size_t right) {
  3409. while (b + left < e && is_space_or_tab(b[left])) {
  3410. left++;
  3411. }
  3412. while (right > 0 && is_space_or_tab(b[right - 1])) {
  3413. right--;
  3414. }
  3415. return std::make_pair(left, right);
  3416. }
  3417. inline std::string trim_copy(const std::string &s) {
  3418. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  3419. return s.substr(r.first, r.second - r.first);
  3420. }
  3421. inline std::string trim_double_quotes_copy(const std::string &s) {
  3422. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  3423. return s.substr(1, s.size() - 2);
  3424. }
  3425. return s;
  3426. }
  3427. inline void
  3428. divide(const char *data, std::size_t size, char d,
  3429. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3430. fn) {
  3431. const auto it = std::find(data, data + size, d);
  3432. const auto found = static_cast<std::size_t>(it != data + size);
  3433. const auto lhs_data = data;
  3434. const auto lhs_size = static_cast<std::size_t>(it - data);
  3435. const auto rhs_data = it + found;
  3436. const auto rhs_size = size - lhs_size - found;
  3437. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  3438. }
  3439. inline void
  3440. divide(const std::string &str, char d,
  3441. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3442. fn) {
  3443. divide(str.data(), str.size(), d, std::move(fn));
  3444. }
  3445. inline void split(const char *b, const char *e, char d,
  3446. std::function<void(const char *, const char *)> fn) {
  3447. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  3448. }
  3449. inline void split(const char *b, const char *e, char d, size_t m,
  3450. std::function<void(const char *, const char *)> fn) {
  3451. size_t i = 0;
  3452. size_t beg = 0;
  3453. size_t count = 1;
  3454. while (e ? (b + i < e) : (b[i] != '\0')) {
  3455. if (b[i] == d && count < m) {
  3456. auto r = trim(b, e, beg, i);
  3457. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3458. beg = i + 1;
  3459. count++;
  3460. }
  3461. i++;
  3462. }
  3463. if (i) {
  3464. auto r = trim(b, e, beg, i);
  3465. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3466. }
  3467. }
  3468. inline bool split_find(const char *b, const char *e, char d, size_t m,
  3469. std::function<bool(const char *, const char *)> fn) {
  3470. size_t i = 0;
  3471. size_t beg = 0;
  3472. size_t count = 1;
  3473. while (e ? (b + i < e) : (b[i] != '\0')) {
  3474. if (b[i] == d && count < m) {
  3475. auto r = trim(b, e, beg, i);
  3476. if (r.first < r.second) {
  3477. auto found = fn(&b[r.first], &b[r.second]);
  3478. if (found) { return true; }
  3479. }
  3480. beg = i + 1;
  3481. count++;
  3482. }
  3483. i++;
  3484. }
  3485. if (i) {
  3486. auto r = trim(b, e, beg, i);
  3487. if (r.first < r.second) {
  3488. auto found = fn(&b[r.first], &b[r.second]);
  3489. if (found) { return true; }
  3490. }
  3491. }
  3492. return false;
  3493. }
  3494. inline bool split_find(const char *b, const char *e, char d,
  3495. std::function<bool(const char *, const char *)> fn) {
  3496. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  3497. std::move(fn));
  3498. }
  3499. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  3500. size_t fixed_buffer_size)
  3501. : strm_(strm), fixed_buffer_(fixed_buffer),
  3502. fixed_buffer_size_(fixed_buffer_size) {}
  3503. inline const char *stream_line_reader::ptr() const {
  3504. if (growable_buffer_.empty()) {
  3505. return fixed_buffer_;
  3506. } else {
  3507. return growable_buffer_.data();
  3508. }
  3509. }
  3510. inline size_t stream_line_reader::size() const {
  3511. if (growable_buffer_.empty()) {
  3512. return fixed_buffer_used_size_;
  3513. } else {
  3514. return growable_buffer_.size();
  3515. }
  3516. }
  3517. inline bool stream_line_reader::end_with_crlf() const {
  3518. auto end = ptr() + size();
  3519. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  3520. }
  3521. inline bool stream_line_reader::getline() {
  3522. fixed_buffer_used_size_ = 0;
  3523. growable_buffer_.clear();
  3524. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3525. char prev_byte = 0;
  3526. #endif
  3527. for (size_t i = 0;; i++) {
  3528. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  3529. // Treat exceptionally long lines as an error to
  3530. // prevent infinite loops/memory exhaustion
  3531. return false;
  3532. }
  3533. char byte;
  3534. auto n = strm_.read(&byte, 1);
  3535. if (n < 0) {
  3536. return false;
  3537. } else if (n == 0) {
  3538. if (i == 0) {
  3539. return false;
  3540. } else {
  3541. break;
  3542. }
  3543. }
  3544. append(byte);
  3545. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3546. if (byte == '\n') { break; }
  3547. #else
  3548. if (prev_byte == '\r' && byte == '\n') { break; }
  3549. prev_byte = byte;
  3550. #endif
  3551. }
  3552. return true;
  3553. }
  3554. inline void stream_line_reader::append(char c) {
  3555. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  3556. fixed_buffer_[fixed_buffer_used_size_++] = c;
  3557. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  3558. } else {
  3559. if (growable_buffer_.empty()) {
  3560. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  3561. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  3562. }
  3563. growable_buffer_ += c;
  3564. }
  3565. }
  3566. inline mmap::mmap(const char *path) { open(path); }
  3567. inline mmap::~mmap() { close(); }
  3568. inline bool mmap::open(const char *path) {
  3569. close();
  3570. #if defined(_WIN32)
  3571. auto wpath = u8string_to_wstring(path);
  3572. if (wpath.empty()) { return false; }
  3573. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  3574. OPEN_EXISTING, NULL);
  3575. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  3576. LARGE_INTEGER size{};
  3577. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  3578. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  3579. // See:
  3580. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  3581. if (static_cast<ULONGLONG>(size.QuadPart) >
  3582. (std::numeric_limits<decltype(size_)>::max)()) {
  3583. // `size_t` might be 32-bits, on 32-bits Windows.
  3584. return false;
  3585. }
  3586. size_ = static_cast<size_t>(size.QuadPart);
  3587. hMapping_ =
  3588. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  3589. // Special treatment for an empty file...
  3590. if (hMapping_ == NULL && size_ == 0) {
  3591. close();
  3592. is_open_empty_file = true;
  3593. return true;
  3594. }
  3595. if (hMapping_ == NULL) {
  3596. close();
  3597. return false;
  3598. }
  3599. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  3600. if (addr_ == nullptr) {
  3601. close();
  3602. return false;
  3603. }
  3604. #else
  3605. fd_ = ::open(path, O_RDONLY);
  3606. if (fd_ == -1) { return false; }
  3607. struct stat sb;
  3608. if (fstat(fd_, &sb) == -1) {
  3609. close();
  3610. return false;
  3611. }
  3612. size_ = static_cast<size_t>(sb.st_size);
  3613. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  3614. // Special treatment for an empty file...
  3615. if (addr_ == MAP_FAILED && size_ == 0) {
  3616. close();
  3617. is_open_empty_file = true;
  3618. return false;
  3619. }
  3620. #endif
  3621. return true;
  3622. }
  3623. inline bool mmap::is_open() const {
  3624. return is_open_empty_file ? true : addr_ != nullptr;
  3625. }
  3626. inline size_t mmap::size() const { return size_; }
  3627. inline const char *mmap::data() const {
  3628. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  3629. }
  3630. inline void mmap::close() {
  3631. #if defined(_WIN32)
  3632. if (addr_) {
  3633. ::UnmapViewOfFile(addr_);
  3634. addr_ = nullptr;
  3635. }
  3636. if (hMapping_) {
  3637. ::CloseHandle(hMapping_);
  3638. hMapping_ = NULL;
  3639. }
  3640. if (hFile_ != INVALID_HANDLE_VALUE) {
  3641. ::CloseHandle(hFile_);
  3642. hFile_ = INVALID_HANDLE_VALUE;
  3643. }
  3644. is_open_empty_file = false;
  3645. #else
  3646. if (addr_ != nullptr) {
  3647. munmap(addr_, size_);
  3648. addr_ = nullptr;
  3649. }
  3650. if (fd_ != -1) {
  3651. ::close(fd_);
  3652. fd_ = -1;
  3653. }
  3654. #endif
  3655. size_ = 0;
  3656. }
  3657. inline int close_socket(socket_t sock) {
  3658. #ifdef _WIN32
  3659. return closesocket(sock);
  3660. #else
  3661. return close(sock);
  3662. #endif
  3663. }
  3664. template <typename T> inline ssize_t handle_EINTR(T fn) {
  3665. ssize_t res = 0;
  3666. while (true) {
  3667. res = fn();
  3668. if (res < 0 && errno == EINTR) {
  3669. std::this_thread::sleep_for(std::chrono::microseconds{1});
  3670. continue;
  3671. }
  3672. break;
  3673. }
  3674. return res;
  3675. }
  3676. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  3677. return handle_EINTR([&]() {
  3678. return recv(sock,
  3679. #ifdef _WIN32
  3680. static_cast<char *>(ptr), static_cast<int>(size),
  3681. #else
  3682. ptr, size,
  3683. #endif
  3684. flags);
  3685. });
  3686. }
  3687. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  3688. int flags) {
  3689. return handle_EINTR([&]() {
  3690. return send(sock,
  3691. #ifdef _WIN32
  3692. static_cast<const char *>(ptr), static_cast<int>(size),
  3693. #else
  3694. ptr, size,
  3695. #endif
  3696. flags);
  3697. });
  3698. }
  3699. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  3700. #ifdef _WIN32
  3701. return ::WSAPoll(fds, nfds, timeout);
  3702. #else
  3703. return ::poll(fds, nfds, timeout);
  3704. #endif
  3705. }
  3706. template <bool Read>
  3707. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  3708. #ifdef __APPLE__
  3709. if (sock >= FD_SETSIZE) { return -1; }
  3710. fd_set fds, *rfds, *wfds;
  3711. FD_ZERO(&fds);
  3712. FD_SET(sock, &fds);
  3713. rfds = (Read ? &fds : nullptr);
  3714. wfds = (Read ? nullptr : &fds);
  3715. timeval tv;
  3716. tv.tv_sec = static_cast<long>(sec);
  3717. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3718. return handle_EINTR([&]() {
  3719. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  3720. });
  3721. #else
  3722. struct pollfd pfd;
  3723. pfd.fd = sock;
  3724. pfd.events = (Read ? POLLIN : POLLOUT);
  3725. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3726. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  3727. #endif
  3728. }
  3729. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  3730. return select_impl<true>(sock, sec, usec);
  3731. }
  3732. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  3733. return select_impl<false>(sock, sec, usec);
  3734. }
  3735. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  3736. time_t usec) {
  3737. #ifdef __APPLE__
  3738. if (sock >= FD_SETSIZE) { return Error::Connection; }
  3739. fd_set fdsr, fdsw;
  3740. FD_ZERO(&fdsr);
  3741. FD_ZERO(&fdsw);
  3742. FD_SET(sock, &fdsr);
  3743. FD_SET(sock, &fdsw);
  3744. timeval tv;
  3745. tv.tv_sec = static_cast<long>(sec);
  3746. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3747. auto ret = handle_EINTR([&]() {
  3748. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  3749. });
  3750. if (ret == 0) { return Error::ConnectionTimeout; }
  3751. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  3752. auto error = 0;
  3753. socklen_t len = sizeof(error);
  3754. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3755. reinterpret_cast<char *>(&error), &len);
  3756. auto successful = res >= 0 && !error;
  3757. return successful ? Error::Success : Error::Connection;
  3758. }
  3759. return Error::Connection;
  3760. #else
  3761. struct pollfd pfd_read;
  3762. pfd_read.fd = sock;
  3763. pfd_read.events = POLLIN | POLLOUT;
  3764. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3765. auto poll_res =
  3766. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  3767. if (poll_res == 0) { return Error::ConnectionTimeout; }
  3768. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  3769. auto error = 0;
  3770. socklen_t len = sizeof(error);
  3771. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3772. reinterpret_cast<char *>(&error), &len);
  3773. auto successful = res >= 0 && !error;
  3774. return successful ? Error::Success : Error::Connection;
  3775. }
  3776. return Error::Connection;
  3777. #endif
  3778. }
  3779. inline bool is_socket_alive(socket_t sock) {
  3780. const auto val = detail::select_read(sock, 0, 0);
  3781. if (val == 0) {
  3782. return true;
  3783. } else if (val < 0 && errno == EBADF) {
  3784. return false;
  3785. }
  3786. char buf[1];
  3787. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  3788. }
  3789. class SocketStream final : public Stream {
  3790. public:
  3791. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3792. time_t write_timeout_sec, time_t write_timeout_usec,
  3793. time_t max_timeout_msec = 0,
  3794. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3795. (std::chrono::steady_clock::time_point::min)());
  3796. ~SocketStream() override;
  3797. bool is_readable() const override;
  3798. bool wait_readable() const override;
  3799. bool wait_writable() const override;
  3800. ssize_t read(char *ptr, size_t size) override;
  3801. ssize_t write(const char *ptr, size_t size) override;
  3802. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3803. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3804. socket_t socket() const override;
  3805. time_t duration() const override;
  3806. private:
  3807. socket_t sock_;
  3808. time_t read_timeout_sec_;
  3809. time_t read_timeout_usec_;
  3810. time_t write_timeout_sec_;
  3811. time_t write_timeout_usec_;
  3812. time_t max_timeout_msec_;
  3813. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3814. std::vector<char> read_buff_;
  3815. size_t read_buff_off_ = 0;
  3816. size_t read_buff_content_size_ = 0;
  3817. static const size_t read_buff_size_ = 1024l * 4;
  3818. };
  3819. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3820. time_t keep_alive_timeout_sec) {
  3821. using namespace std::chrono;
  3822. const auto interval_usec =
  3823. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  3824. // Avoid expensive `steady_clock::now()` call for the first time
  3825. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  3826. const auto start = steady_clock::now() - microseconds{interval_usec};
  3827. const auto timeout = seconds{keep_alive_timeout_sec};
  3828. while (true) {
  3829. if (svr_sock == INVALID_SOCKET) {
  3830. break; // Server socket is closed
  3831. }
  3832. auto val = select_read(sock, 0, interval_usec);
  3833. if (val < 0) {
  3834. break; // Ssocket error
  3835. } else if (val == 0) {
  3836. if (steady_clock::now() - start > timeout) {
  3837. break; // Timeout
  3838. }
  3839. } else {
  3840. return true; // Ready for read
  3841. }
  3842. }
  3843. return false;
  3844. }
  3845. template <typename T>
  3846. inline bool
  3847. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3848. size_t keep_alive_max_count,
  3849. time_t keep_alive_timeout_sec, T callback) {
  3850. assert(keep_alive_max_count > 0);
  3851. auto ret = false;
  3852. auto count = keep_alive_max_count;
  3853. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  3854. auto close_connection = count == 1;
  3855. auto connection_closed = false;
  3856. ret = callback(close_connection, connection_closed);
  3857. if (!ret || connection_closed) { break; }
  3858. count--;
  3859. }
  3860. return ret;
  3861. }
  3862. template <typename T>
  3863. inline bool
  3864. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3865. size_t keep_alive_max_count,
  3866. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  3867. time_t read_timeout_usec, time_t write_timeout_sec,
  3868. time_t write_timeout_usec, T callback) {
  3869. return process_server_socket_core(
  3870. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  3871. [&](bool close_connection, bool &connection_closed) {
  3872. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3873. write_timeout_sec, write_timeout_usec);
  3874. return callback(strm, close_connection, connection_closed);
  3875. });
  3876. }
  3877. inline bool process_client_socket(
  3878. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3879. time_t write_timeout_sec, time_t write_timeout_usec,
  3880. time_t max_timeout_msec,
  3881. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3882. std::function<bool(Stream &)> callback) {
  3883. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3884. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  3885. start_time);
  3886. return callback(strm);
  3887. }
  3888. inline int shutdown_socket(socket_t sock) {
  3889. #ifdef _WIN32
  3890. return shutdown(sock, SD_BOTH);
  3891. #else
  3892. return shutdown(sock, SHUT_RDWR);
  3893. #endif
  3894. }
  3895. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  3896. if (s.size() > 1 && s[0] == '\0') {
  3897. auto ret = s;
  3898. ret[0] = '@';
  3899. return ret;
  3900. }
  3901. return s;
  3902. }
  3903. inline std::string
  3904. unescape_abstract_namespace_unix_domain(const std::string &s) {
  3905. if (s.size() > 1 && s[0] == '@') {
  3906. auto ret = s;
  3907. ret[0] = '\0';
  3908. return ret;
  3909. }
  3910. return s;
  3911. }
  3912. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  3913. const struct addrinfo *hints,
  3914. struct addrinfo **res, time_t timeout_sec) {
  3915. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  3916. if (timeout_sec <= 0) {
  3917. // No timeout specified, use standard getaddrinfo
  3918. return getaddrinfo(node, service, hints, res);
  3919. }
  3920. #ifdef _WIN32
  3921. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  3922. OVERLAPPED overlapped = {0};
  3923. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  3924. if (!event) { return EAI_FAIL; }
  3925. overlapped.hEvent = event;
  3926. PADDRINFOEXW result_addrinfo = nullptr;
  3927. HANDLE cancel_handle = nullptr;
  3928. ADDRINFOEXW hints_ex = {0};
  3929. if (hints) {
  3930. hints_ex.ai_flags = hints->ai_flags;
  3931. hints_ex.ai_family = hints->ai_family;
  3932. hints_ex.ai_socktype = hints->ai_socktype;
  3933. hints_ex.ai_protocol = hints->ai_protocol;
  3934. }
  3935. auto wnode = u8string_to_wstring(node);
  3936. auto wservice = u8string_to_wstring(service);
  3937. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  3938. hints ? &hints_ex : nullptr, &result_addrinfo,
  3939. nullptr, &overlapped, nullptr, &cancel_handle);
  3940. if (ret == WSA_IO_PENDING) {
  3941. auto wait_result =
  3942. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  3943. if (wait_result == WAIT_TIMEOUT) {
  3944. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  3945. ::CloseHandle(event);
  3946. return EAI_AGAIN;
  3947. }
  3948. DWORD bytes_returned;
  3949. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  3950. &bytes_returned, FALSE)) {
  3951. ::CloseHandle(event);
  3952. return ::WSAGetLastError();
  3953. }
  3954. }
  3955. ::CloseHandle(event);
  3956. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  3957. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  3958. return 0;
  3959. }
  3960. return ret;
  3961. #elif TARGET_OS_MAC
  3962. if (!node) { return EAI_NONAME; }
  3963. // macOS implementation using CFHost API for asynchronous DNS resolution
  3964. CFStringRef hostname_ref = CFStringCreateWithCString(
  3965. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  3966. if (!hostname_ref) { return EAI_MEMORY; }
  3967. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  3968. CFRelease(hostname_ref);
  3969. if (!host_ref) { return EAI_MEMORY; }
  3970. // Set up context for callback
  3971. struct CFHostContext {
  3972. bool completed = false;
  3973. bool success = false;
  3974. CFArrayRef addresses = nullptr;
  3975. std::mutex mutex;
  3976. std::condition_variable cv;
  3977. } context;
  3978. CFHostClientContext client_context;
  3979. memset(&client_context, 0, sizeof(client_context));
  3980. client_context.info = &context;
  3981. // Set callback
  3982. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  3983. const CFStreamError *error, void *info) {
  3984. auto ctx = static_cast<CFHostContext *>(info);
  3985. std::lock_guard<std::mutex> lock(ctx->mutex);
  3986. if (error && error->error != 0) {
  3987. ctx->success = false;
  3988. } else {
  3989. Boolean hasBeenResolved;
  3990. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  3991. if (ctx->addresses && hasBeenResolved) {
  3992. CFRetain(ctx->addresses);
  3993. ctx->success = true;
  3994. } else {
  3995. ctx->success = false;
  3996. }
  3997. }
  3998. ctx->completed = true;
  3999. ctx->cv.notify_one();
  4000. };
  4001. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4002. CFRelease(host_ref);
  4003. return EAI_SYSTEM;
  4004. }
  4005. // Schedule on run loop
  4006. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4007. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4008. // Start resolution
  4009. CFStreamError stream_error;
  4010. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4011. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4012. CFRelease(host_ref);
  4013. return EAI_FAIL;
  4014. }
  4015. // Wait for completion with timeout
  4016. auto timeout_time =
  4017. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4018. bool timed_out = false;
  4019. {
  4020. std::unique_lock<std::mutex> lock(context.mutex);
  4021. while (!context.completed) {
  4022. auto now = std::chrono::steady_clock::now();
  4023. if (now >= timeout_time) {
  4024. timed_out = true;
  4025. break;
  4026. }
  4027. // Run the runloop for a short time
  4028. lock.unlock();
  4029. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4030. lock.lock();
  4031. }
  4032. }
  4033. // Clean up
  4034. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4035. CFHostSetClient(host_ref, nullptr, nullptr);
  4036. if (timed_out || !context.completed) {
  4037. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4038. CFRelease(host_ref);
  4039. return EAI_AGAIN;
  4040. }
  4041. if (!context.success || !context.addresses) {
  4042. CFRelease(host_ref);
  4043. return EAI_NODATA;
  4044. }
  4045. // Convert CFArray to addrinfo
  4046. CFIndex count = CFArrayGetCount(context.addresses);
  4047. if (count == 0) {
  4048. CFRelease(context.addresses);
  4049. CFRelease(host_ref);
  4050. return EAI_NODATA;
  4051. }
  4052. struct addrinfo *result_addrinfo = nullptr;
  4053. struct addrinfo **current = &result_addrinfo;
  4054. for (CFIndex i = 0; i < count; i++) {
  4055. CFDataRef addr_data =
  4056. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4057. if (!addr_data) continue;
  4058. const struct sockaddr *sockaddr_ptr =
  4059. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4060. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4061. // Allocate addrinfo structure
  4062. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4063. if (!*current) {
  4064. freeaddrinfo(result_addrinfo);
  4065. CFRelease(context.addresses);
  4066. CFRelease(host_ref);
  4067. return EAI_MEMORY;
  4068. }
  4069. memset(*current, 0, sizeof(struct addrinfo));
  4070. // Set up addrinfo fields
  4071. (*current)->ai_family = sockaddr_ptr->sa_family;
  4072. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4073. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4074. (*current)->ai_addrlen = sockaddr_len;
  4075. // Copy sockaddr
  4076. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4077. if (!(*current)->ai_addr) {
  4078. freeaddrinfo(result_addrinfo);
  4079. CFRelease(context.addresses);
  4080. CFRelease(host_ref);
  4081. return EAI_MEMORY;
  4082. }
  4083. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4084. // Set port if service is specified
  4085. if (service && strlen(service) > 0) {
  4086. int port = atoi(service);
  4087. if (port > 0) {
  4088. if (sockaddr_ptr->sa_family == AF_INET) {
  4089. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4090. ->sin_port = htons(static_cast<uint16_t>(port));
  4091. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4092. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4093. ->sin6_port = htons(static_cast<uint16_t>(port));
  4094. }
  4095. }
  4096. }
  4097. current = &((*current)->ai_next);
  4098. }
  4099. CFRelease(context.addresses);
  4100. CFRelease(host_ref);
  4101. *res = result_addrinfo;
  4102. return 0;
  4103. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  4104. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  4105. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  4106. struct gaicb request;
  4107. struct gaicb *requests[1] = {&request};
  4108. struct sigevent sevp;
  4109. struct timespec timeout;
  4110. // Initialize the request structure
  4111. memset(&request, 0, sizeof(request));
  4112. request.ar_name = node;
  4113. request.ar_service = service;
  4114. request.ar_request = hints;
  4115. // Set up timeout
  4116. timeout.tv_sec = timeout_sec;
  4117. timeout.tv_nsec = 0;
  4118. // Initialize sigevent structure (not used, but required)
  4119. memset(&sevp, 0, sizeof(sevp));
  4120. sevp.sigev_notify = SIGEV_NONE;
  4121. // Start asynchronous resolution
  4122. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  4123. if (start_result != 0) { return start_result; }
  4124. // Wait for completion with timeout
  4125. int wait_result =
  4126. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  4127. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  4128. // Completed successfully, get the result
  4129. int gai_result = gai_error(&request);
  4130. if (gai_result == 0) {
  4131. *res = request.ar_result;
  4132. return 0;
  4133. } else {
  4134. // Clean up on error
  4135. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  4136. return gai_result;
  4137. }
  4138. } else if (wait_result == EAI_AGAIN) {
  4139. // Timeout occurred, cancel the request
  4140. gai_cancel(&request);
  4141. return EAI_AGAIN;
  4142. } else {
  4143. // Other error occurred
  4144. gai_cancel(&request);
  4145. return wait_result;
  4146. }
  4147. #else
  4148. // Fallback implementation using thread-based timeout for other Unix systems
  4149. struct GetAddrInfoState {
  4150. ~GetAddrInfoState() {
  4151. if (info) { freeaddrinfo(info); }
  4152. }
  4153. std::mutex mutex;
  4154. std::condition_variable result_cv;
  4155. bool completed = false;
  4156. int result = EAI_SYSTEM;
  4157. std::string node;
  4158. std::string service;
  4159. struct addrinfo hints;
  4160. struct addrinfo *info = nullptr;
  4161. };
  4162. // Allocate on the heap, so the resolver thread can keep using the data.
  4163. auto state = std::make_shared<GetAddrInfoState>();
  4164. if (node) { state->node = node; }
  4165. state->service = service;
  4166. state->hints = *hints;
  4167. std::thread resolve_thread([state]() {
  4168. auto thread_result =
  4169. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4170. &state->info);
  4171. std::lock_guard<std::mutex> lock(state->mutex);
  4172. state->result = thread_result;
  4173. state->completed = true;
  4174. state->result_cv.notify_one();
  4175. });
  4176. // Wait for completion or timeout
  4177. std::unique_lock<std::mutex> lock(state->mutex);
  4178. auto finished =
  4179. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4180. [&] { return state->completed; });
  4181. if (finished) {
  4182. // Operation completed within timeout
  4183. resolve_thread.join();
  4184. *res = state->info;
  4185. state->info = nullptr; // Pass ownership to caller
  4186. return state->result;
  4187. } else {
  4188. // Timeout occurred
  4189. resolve_thread.detach(); // Let the thread finish in background
  4190. return EAI_AGAIN; // Return timeout error
  4191. }
  4192. #endif
  4193. #else
  4194. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4195. return getaddrinfo(node, service, hints, res);
  4196. #endif
  4197. }
  4198. template <typename BindOrConnect>
  4199. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4200. int address_family, int socket_flags, bool tcp_nodelay,
  4201. bool ipv6_v6only, SocketOptions socket_options,
  4202. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4203. // Get address info
  4204. const char *node = nullptr;
  4205. struct addrinfo hints;
  4206. struct addrinfo *result;
  4207. memset(&hints, 0, sizeof(struct addrinfo));
  4208. hints.ai_socktype = SOCK_STREAM;
  4209. hints.ai_protocol = IPPROTO_IP;
  4210. if (!ip.empty()) {
  4211. node = ip.c_str();
  4212. // Ask getaddrinfo to convert IP in c-string to address
  4213. hints.ai_family = AF_UNSPEC;
  4214. hints.ai_flags = AI_NUMERICHOST;
  4215. } else {
  4216. if (!host.empty()) { node = host.c_str(); }
  4217. hints.ai_family = address_family;
  4218. hints.ai_flags = socket_flags;
  4219. }
  4220. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  4221. if (hints.ai_family == AF_UNIX) {
  4222. const auto addrlen = host.length();
  4223. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  4224. #ifdef SOCK_CLOEXEC
  4225. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  4226. hints.ai_protocol);
  4227. #else
  4228. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4229. #endif
  4230. if (sock != INVALID_SOCKET) {
  4231. sockaddr_un addr{};
  4232. addr.sun_family = AF_UNIX;
  4233. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  4234. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  4235. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  4236. hints.ai_addrlen = static_cast<socklen_t>(
  4237. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  4238. #ifndef SOCK_CLOEXEC
  4239. #ifndef _WIN32
  4240. fcntl(sock, F_SETFD, FD_CLOEXEC);
  4241. #endif
  4242. #endif
  4243. if (socket_options) { socket_options(sock); }
  4244. #ifdef _WIN32
  4245. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  4246. // remove the option.
  4247. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  4248. #endif
  4249. bool dummy;
  4250. if (!bind_or_connect(sock, hints, dummy)) {
  4251. close_socket(sock);
  4252. sock = INVALID_SOCKET;
  4253. }
  4254. }
  4255. return sock;
  4256. }
  4257. #endif
  4258. auto service = std::to_string(port);
  4259. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  4260. timeout_sec)) {
  4261. #if defined __linux__ && !defined __ANDROID__
  4262. res_init();
  4263. #endif
  4264. return INVALID_SOCKET;
  4265. }
  4266. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4267. for (auto rp = result; rp; rp = rp->ai_next) {
  4268. // Create a socket
  4269. #ifdef _WIN32
  4270. auto sock =
  4271. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  4272. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  4273. /**
  4274. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  4275. * and above the socket creation fails on older Windows Systems.
  4276. *
  4277. * Let's try to create a socket the old way in this case.
  4278. *
  4279. * Reference:
  4280. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  4281. *
  4282. * WSA_FLAG_NO_HANDLE_INHERIT:
  4283. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  4284. * SP1, and later
  4285. *
  4286. */
  4287. if (sock == INVALID_SOCKET) {
  4288. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4289. }
  4290. #else
  4291. #ifdef SOCK_CLOEXEC
  4292. auto sock =
  4293. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  4294. #else
  4295. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4296. #endif
  4297. #endif
  4298. if (sock == INVALID_SOCKET) { continue; }
  4299. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  4300. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  4301. close_socket(sock);
  4302. continue;
  4303. }
  4304. #endif
  4305. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  4306. if (rp->ai_family == AF_INET6) {
  4307. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  4308. }
  4309. if (socket_options) { socket_options(sock); }
  4310. // bind or connect
  4311. auto quit = false;
  4312. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  4313. close_socket(sock);
  4314. if (quit) { break; }
  4315. }
  4316. return INVALID_SOCKET;
  4317. }
  4318. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  4319. #ifdef _WIN32
  4320. auto flags = nonblocking ? 1UL : 0UL;
  4321. ioctlsocket(sock, FIONBIO, &flags);
  4322. #else
  4323. auto flags = fcntl(sock, F_GETFL, 0);
  4324. fcntl(sock, F_SETFL,
  4325. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  4326. #endif
  4327. }
  4328. inline bool is_connection_error() {
  4329. #ifdef _WIN32
  4330. return WSAGetLastError() != WSAEWOULDBLOCK;
  4331. #else
  4332. return errno != EINPROGRESS;
  4333. #endif
  4334. }
  4335. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  4336. struct addrinfo hints;
  4337. struct addrinfo *result;
  4338. memset(&hints, 0, sizeof(struct addrinfo));
  4339. hints.ai_family = AF_UNSPEC;
  4340. hints.ai_socktype = SOCK_STREAM;
  4341. hints.ai_protocol = 0;
  4342. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  4343. return false;
  4344. }
  4345. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4346. auto ret = false;
  4347. for (auto rp = result; rp; rp = rp->ai_next) {
  4348. const auto &ai = *rp;
  4349. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4350. ret = true;
  4351. break;
  4352. }
  4353. }
  4354. return ret;
  4355. }
  4356. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  4357. #define USE_IF2IP
  4358. #endif
  4359. #ifdef USE_IF2IP
  4360. inline std::string if2ip(int address_family, const std::string &ifn) {
  4361. struct ifaddrs *ifap;
  4362. getifaddrs(&ifap);
  4363. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  4364. std::string addr_candidate;
  4365. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  4366. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  4367. (AF_UNSPEC == address_family ||
  4368. ifa->ifa_addr->sa_family == address_family)) {
  4369. if (ifa->ifa_addr->sa_family == AF_INET) {
  4370. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  4371. char buf[INET_ADDRSTRLEN];
  4372. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  4373. return std::string(buf, INET_ADDRSTRLEN);
  4374. }
  4375. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  4376. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  4377. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  4378. char buf[INET6_ADDRSTRLEN] = {};
  4379. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  4380. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  4381. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  4382. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  4383. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  4384. } else {
  4385. return std::string(buf, INET6_ADDRSTRLEN);
  4386. }
  4387. }
  4388. }
  4389. }
  4390. }
  4391. }
  4392. return addr_candidate;
  4393. }
  4394. #endif
  4395. inline socket_t create_client_socket(
  4396. const std::string &host, const std::string &ip, int port,
  4397. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  4398. SocketOptions socket_options, time_t connection_timeout_sec,
  4399. time_t connection_timeout_usec, time_t read_timeout_sec,
  4400. time_t read_timeout_usec, time_t write_timeout_sec,
  4401. time_t write_timeout_usec, const std::string &intf, Error &error) {
  4402. auto sock = create_socket(
  4403. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  4404. std::move(socket_options),
  4405. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  4406. if (!intf.empty()) {
  4407. #ifdef USE_IF2IP
  4408. auto ip_from_if = if2ip(address_family, intf);
  4409. if (ip_from_if.empty()) { ip_from_if = intf; }
  4410. if (!bind_ip_address(sock2, ip_from_if)) {
  4411. error = Error::BindIPAddress;
  4412. return false;
  4413. }
  4414. #endif
  4415. }
  4416. set_nonblocking(sock2, true);
  4417. auto ret =
  4418. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  4419. if (ret < 0) {
  4420. if (is_connection_error()) {
  4421. error = Error::Connection;
  4422. return false;
  4423. }
  4424. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  4425. connection_timeout_usec);
  4426. if (error != Error::Success) {
  4427. if (error == Error::ConnectionTimeout) { quit = true; }
  4428. return false;
  4429. }
  4430. }
  4431. set_nonblocking(sock2, false);
  4432. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  4433. read_timeout_usec);
  4434. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  4435. write_timeout_usec);
  4436. error = Error::Success;
  4437. return true;
  4438. },
  4439. connection_timeout_sec); // Pass DNS timeout
  4440. if (sock != INVALID_SOCKET) {
  4441. error = Error::Success;
  4442. } else {
  4443. if (error == Error::Success) { error = Error::Connection; }
  4444. }
  4445. return sock;
  4446. }
  4447. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  4448. socklen_t addr_len, std::string &ip, int &port) {
  4449. if (addr.ss_family == AF_INET) {
  4450. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  4451. } else if (addr.ss_family == AF_INET6) {
  4452. port =
  4453. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  4454. } else {
  4455. return false;
  4456. }
  4457. std::array<char, NI_MAXHOST> ipstr{};
  4458. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  4459. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  4460. 0, NI_NUMERICHOST)) {
  4461. return false;
  4462. }
  4463. ip = ipstr.data();
  4464. return true;
  4465. }
  4466. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4467. struct sockaddr_storage addr;
  4468. socklen_t addr_len = sizeof(addr);
  4469. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4470. &addr_len)) {
  4471. get_ip_and_port(addr, addr_len, ip, port);
  4472. }
  4473. }
  4474. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4475. struct sockaddr_storage addr;
  4476. socklen_t addr_len = sizeof(addr);
  4477. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4478. &addr_len)) {
  4479. #ifndef _WIN32
  4480. if (addr.ss_family == AF_UNIX) {
  4481. #if defined(__linux__)
  4482. struct ucred ucred;
  4483. socklen_t len = sizeof(ucred);
  4484. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  4485. port = ucred.pid;
  4486. }
  4487. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  4488. pid_t pid;
  4489. socklen_t len = sizeof(pid);
  4490. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  4491. port = pid;
  4492. }
  4493. #endif
  4494. return;
  4495. }
  4496. #endif
  4497. get_ip_and_port(addr, addr_len, ip, port);
  4498. }
  4499. }
  4500. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  4501. unsigned int h) {
  4502. return (l == 0)
  4503. ? h
  4504. : str2tag_core(
  4505. s + 1, l - 1,
  4506. // Unsets the 6 high bits of h, therefore no overflow happens
  4507. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  4508. h * 33) ^
  4509. static_cast<unsigned char>(*s));
  4510. }
  4511. inline unsigned int str2tag(const std::string &s) {
  4512. return str2tag_core(s.data(), s.size(), 0);
  4513. }
  4514. namespace udl {
  4515. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  4516. return str2tag_core(s, l, 0);
  4517. }
  4518. } // namespace udl
  4519. inline std::string
  4520. find_content_type(const std::string &path,
  4521. const std::map<std::string, std::string> &user_data,
  4522. const std::string &default_content_type) {
  4523. auto ext = file_extension(path);
  4524. auto it = user_data.find(ext);
  4525. if (it != user_data.end()) { return it->second; }
  4526. using udl::operator""_t;
  4527. switch (str2tag(ext)) {
  4528. default: return default_content_type;
  4529. case "css"_t: return "text/css";
  4530. case "csv"_t: return "text/csv";
  4531. case "htm"_t:
  4532. case "html"_t: return "text/html";
  4533. case "js"_t:
  4534. case "mjs"_t: return "text/javascript";
  4535. case "txt"_t: return "text/plain";
  4536. case "vtt"_t: return "text/vtt";
  4537. case "apng"_t: return "image/apng";
  4538. case "avif"_t: return "image/avif";
  4539. case "bmp"_t: return "image/bmp";
  4540. case "gif"_t: return "image/gif";
  4541. case "png"_t: return "image/png";
  4542. case "svg"_t: return "image/svg+xml";
  4543. case "webp"_t: return "image/webp";
  4544. case "ico"_t: return "image/x-icon";
  4545. case "tif"_t: return "image/tiff";
  4546. case "tiff"_t: return "image/tiff";
  4547. case "jpg"_t:
  4548. case "jpeg"_t: return "image/jpeg";
  4549. case "mp4"_t: return "video/mp4";
  4550. case "mpeg"_t: return "video/mpeg";
  4551. case "webm"_t: return "video/webm";
  4552. case "mp3"_t: return "audio/mp3";
  4553. case "mpga"_t: return "audio/mpeg";
  4554. case "weba"_t: return "audio/webm";
  4555. case "wav"_t: return "audio/wave";
  4556. case "otf"_t: return "font/otf";
  4557. case "ttf"_t: return "font/ttf";
  4558. case "woff"_t: return "font/woff";
  4559. case "woff2"_t: return "font/woff2";
  4560. case "7z"_t: return "application/x-7z-compressed";
  4561. case "atom"_t: return "application/atom+xml";
  4562. case "pdf"_t: return "application/pdf";
  4563. case "json"_t: return "application/json";
  4564. case "rss"_t: return "application/rss+xml";
  4565. case "tar"_t: return "application/x-tar";
  4566. case "xht"_t:
  4567. case "xhtml"_t: return "application/xhtml+xml";
  4568. case "xslt"_t: return "application/xslt+xml";
  4569. case "xml"_t: return "application/xml";
  4570. case "gz"_t: return "application/gzip";
  4571. case "zip"_t: return "application/zip";
  4572. case "wasm"_t: return "application/wasm";
  4573. }
  4574. }
  4575. inline bool can_compress_content_type(const std::string &content_type) {
  4576. using udl::operator""_t;
  4577. auto tag = str2tag(content_type);
  4578. switch (tag) {
  4579. case "image/svg+xml"_t:
  4580. case "application/javascript"_t:
  4581. case "application/json"_t:
  4582. case "application/xml"_t:
  4583. case "application/protobuf"_t:
  4584. case "application/xhtml+xml"_t: return true;
  4585. case "text/event-stream"_t: return false;
  4586. default: return !content_type.rfind("text/", 0);
  4587. }
  4588. }
  4589. inline EncodingType encoding_type(const Request &req, const Response &res) {
  4590. auto ret =
  4591. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  4592. if (!ret) { return EncodingType::None; }
  4593. const auto &s = req.get_header_value("Accept-Encoding");
  4594. (void)(s);
  4595. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4596. // TODO: 'Accept-Encoding' has br, not br;q=0
  4597. ret = s.find("br") != std::string::npos;
  4598. if (ret) { return EncodingType::Brotli; }
  4599. #endif
  4600. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4601. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  4602. ret = s.find("gzip") != std::string::npos;
  4603. if (ret) { return EncodingType::Gzip; }
  4604. #endif
  4605. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4606. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  4607. ret = s.find("zstd") != std::string::npos;
  4608. if (ret) { return EncodingType::Zstd; }
  4609. #endif
  4610. return EncodingType::None;
  4611. }
  4612. inline bool nocompressor::compress(const char *data, size_t data_length,
  4613. bool /*last*/, Callback callback) {
  4614. if (!data_length) { return true; }
  4615. return callback(data, data_length);
  4616. }
  4617. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4618. inline gzip_compressor::gzip_compressor() {
  4619. std::memset(&strm_, 0, sizeof(strm_));
  4620. strm_.zalloc = Z_NULL;
  4621. strm_.zfree = Z_NULL;
  4622. strm_.opaque = Z_NULL;
  4623. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  4624. Z_DEFAULT_STRATEGY) == Z_OK;
  4625. }
  4626. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  4627. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  4628. bool last, Callback callback) {
  4629. assert(is_valid_);
  4630. do {
  4631. constexpr size_t max_avail_in =
  4632. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4633. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4634. (std::min)(data_length, max_avail_in));
  4635. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4636. data_length -= strm_.avail_in;
  4637. data += strm_.avail_in;
  4638. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  4639. auto ret = Z_OK;
  4640. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4641. do {
  4642. strm_.avail_out = static_cast<uInt>(buff.size());
  4643. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4644. ret = deflate(&strm_, flush);
  4645. if (ret == Z_STREAM_ERROR) { return false; }
  4646. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4647. return false;
  4648. }
  4649. } while (strm_.avail_out == 0);
  4650. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  4651. (flush == Z_NO_FLUSH && ret == Z_OK));
  4652. assert(strm_.avail_in == 0);
  4653. } while (data_length > 0);
  4654. return true;
  4655. }
  4656. inline gzip_decompressor::gzip_decompressor() {
  4657. std::memset(&strm_, 0, sizeof(strm_));
  4658. strm_.zalloc = Z_NULL;
  4659. strm_.zfree = Z_NULL;
  4660. strm_.opaque = Z_NULL;
  4661. // 15 is the value of wbits, which should be at the maximum possible value
  4662. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  4663. // that the stream type should be automatically detected either gzip or
  4664. // deflate.
  4665. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  4666. }
  4667. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  4668. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  4669. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  4670. Callback callback) {
  4671. assert(is_valid_);
  4672. auto ret = Z_OK;
  4673. do {
  4674. constexpr size_t max_avail_in =
  4675. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4676. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4677. (std::min)(data_length, max_avail_in));
  4678. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4679. data_length -= strm_.avail_in;
  4680. data += strm_.avail_in;
  4681. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4682. while (strm_.avail_in > 0 && ret == Z_OK) {
  4683. strm_.avail_out = static_cast<uInt>(buff.size());
  4684. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4685. ret = inflate(&strm_, Z_NO_FLUSH);
  4686. assert(ret != Z_STREAM_ERROR);
  4687. switch (ret) {
  4688. case Z_NEED_DICT:
  4689. case Z_DATA_ERROR:
  4690. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  4691. }
  4692. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4693. return false;
  4694. }
  4695. }
  4696. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  4697. } while (data_length > 0);
  4698. return true;
  4699. }
  4700. #endif
  4701. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4702. inline brotli_compressor::brotli_compressor() {
  4703. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  4704. }
  4705. inline brotli_compressor::~brotli_compressor() {
  4706. BrotliEncoderDestroyInstance(state_);
  4707. }
  4708. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  4709. bool last, Callback callback) {
  4710. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4711. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  4712. auto available_in = data_length;
  4713. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4714. for (;;) {
  4715. if (last) {
  4716. if (BrotliEncoderIsFinished(state_)) { break; }
  4717. } else {
  4718. if (!available_in) { break; }
  4719. }
  4720. auto available_out = buff.size();
  4721. auto next_out = buff.data();
  4722. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  4723. &available_out, &next_out, nullptr)) {
  4724. return false;
  4725. }
  4726. auto output_bytes = buff.size() - available_out;
  4727. if (output_bytes) {
  4728. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  4729. }
  4730. }
  4731. return true;
  4732. }
  4733. inline brotli_decompressor::brotli_decompressor() {
  4734. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  4735. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  4736. : BROTLI_DECODER_RESULT_ERROR;
  4737. }
  4738. inline brotli_decompressor::~brotli_decompressor() {
  4739. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  4740. }
  4741. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  4742. inline bool brotli_decompressor::decompress(const char *data,
  4743. size_t data_length,
  4744. Callback callback) {
  4745. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4746. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  4747. return 0;
  4748. }
  4749. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4750. size_t avail_in = data_length;
  4751. size_t total_out;
  4752. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  4753. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4754. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  4755. char *next_out = buff.data();
  4756. size_t avail_out = buff.size();
  4757. decoder_r = BrotliDecoderDecompressStream(
  4758. decoder_s, &avail_in, &next_in, &avail_out,
  4759. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  4760. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  4761. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  4762. }
  4763. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4764. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  4765. }
  4766. #endif
  4767. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4768. inline zstd_compressor::zstd_compressor() {
  4769. ctx_ = ZSTD_createCCtx();
  4770. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  4771. }
  4772. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  4773. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  4774. bool last, Callback callback) {
  4775. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4776. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  4777. ZSTD_inBuffer input = {data, data_length, 0};
  4778. bool finished;
  4779. do {
  4780. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4781. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  4782. if (ZSTD_isError(remaining)) { return false; }
  4783. if (!callback(buff.data(), output.pos)) { return false; }
  4784. finished = last ? (remaining == 0) : (input.pos == input.size);
  4785. } while (!finished);
  4786. return true;
  4787. }
  4788. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  4789. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  4790. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  4791. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  4792. Callback callback) {
  4793. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4794. ZSTD_inBuffer input = {data, data_length, 0};
  4795. while (input.pos < input.size) {
  4796. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4797. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  4798. if (ZSTD_isError(remaining)) { return false; }
  4799. if (!callback(buff.data(), output.pos)) { return false; }
  4800. }
  4801. return true;
  4802. }
  4803. #endif
  4804. inline std::unique_ptr<decompressor>
  4805. create_decompressor(const std::string &encoding) {
  4806. std::unique_ptr<decompressor> decompressor;
  4807. if (encoding == "gzip" || encoding == "deflate") {
  4808. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4809. decompressor = detail::make_unique<gzip_decompressor>();
  4810. #endif
  4811. } else if (encoding.find("br") != std::string::npos) {
  4812. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4813. decompressor = detail::make_unique<brotli_decompressor>();
  4814. #endif
  4815. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  4816. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4817. decompressor = detail::make_unique<zstd_decompressor>();
  4818. #endif
  4819. }
  4820. return decompressor;
  4821. }
  4822. inline bool is_prohibited_header_name(const std::string &name) {
  4823. using udl::operator""_t;
  4824. switch (str2tag(name)) {
  4825. case "REMOTE_ADDR"_t:
  4826. case "REMOTE_PORT"_t:
  4827. case "LOCAL_ADDR"_t:
  4828. case "LOCAL_PORT"_t: return true;
  4829. default: return false;
  4830. }
  4831. }
  4832. inline bool has_header(const Headers &headers, const std::string &key) {
  4833. if (is_prohibited_header_name(key)) { return false; }
  4834. return headers.find(key) != headers.end();
  4835. }
  4836. inline const char *get_header_value(const Headers &headers,
  4837. const std::string &key, const char *def,
  4838. size_t id) {
  4839. if (is_prohibited_header_name(key)) {
  4840. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4841. std::string msg = "Prohibited header name '" + key + "' is specified.";
  4842. throw std::invalid_argument(msg);
  4843. #else
  4844. return "";
  4845. #endif
  4846. }
  4847. auto rng = headers.equal_range(key);
  4848. auto it = rng.first;
  4849. std::advance(it, static_cast<ssize_t>(id));
  4850. if (it != rng.second) { return it->second.c_str(); }
  4851. return def;
  4852. }
  4853. inline bool read_headers(Stream &strm, Headers &headers) {
  4854. const auto bufsiz = 2048;
  4855. char buf[bufsiz];
  4856. stream_line_reader line_reader(strm, buf, bufsiz);
  4857. size_t header_count = 0;
  4858. for (;;) {
  4859. if (!line_reader.getline()) { return false; }
  4860. // Check if the line ends with CRLF.
  4861. auto line_terminator_len = 2;
  4862. if (line_reader.end_with_crlf()) {
  4863. // Blank line indicates end of headers.
  4864. if (line_reader.size() == 2) { break; }
  4865. } else {
  4866. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4867. // Blank line indicates end of headers.
  4868. if (line_reader.size() == 1) { break; }
  4869. line_terminator_len = 1;
  4870. #else
  4871. continue; // Skip invalid line.
  4872. #endif
  4873. }
  4874. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4875. // Check header count limit
  4876. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4877. // Exclude line terminator
  4878. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  4879. if (!parse_header(line_reader.ptr(), end,
  4880. [&](const std::string &key, const std::string &val) {
  4881. headers.emplace(key, val);
  4882. })) {
  4883. return false;
  4884. }
  4885. header_count++;
  4886. }
  4887. return true;
  4888. }
  4889. inline bool read_content_with_length(Stream &strm, size_t len,
  4890. DownloadProgress progress,
  4891. ContentReceiverWithProgress out) {
  4892. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4893. detail::BodyReader br;
  4894. br.stream = &strm;
  4895. br.content_length = len;
  4896. br.chunked = false;
  4897. br.bytes_read = 0;
  4898. br.last_error = Error::Success;
  4899. size_t r = 0;
  4900. while (r < len) {
  4901. auto read_len = static_cast<size_t>(len - r);
  4902. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  4903. auto n = detail::read_body_content(&strm, br, buf, to_read);
  4904. if (n <= 0) { return false; }
  4905. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  4906. r += static_cast<size_t>(n);
  4907. if (progress) {
  4908. if (!progress(r, len)) { return false; }
  4909. }
  4910. }
  4911. return true;
  4912. }
  4913. inline void skip_content_with_length(Stream &strm, size_t len) {
  4914. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4915. size_t r = 0;
  4916. while (r < len) {
  4917. auto read_len = static_cast<size_t>(len - r);
  4918. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  4919. if (n <= 0) { return; }
  4920. r += static_cast<size_t>(n);
  4921. }
  4922. }
  4923. enum class ReadContentResult {
  4924. Success, // Successfully read the content
  4925. PayloadTooLarge, // The content exceeds the specified payload limit
  4926. Error // An error occurred while reading the content
  4927. };
  4928. inline ReadContentResult
  4929. read_content_without_length(Stream &strm, size_t payload_max_length,
  4930. ContentReceiverWithProgress out) {
  4931. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4932. size_t r = 0;
  4933. for (;;) {
  4934. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  4935. if (n == 0) { return ReadContentResult::Success; }
  4936. if (n < 0) { return ReadContentResult::Error; }
  4937. // Check if adding this data would exceed the payload limit
  4938. if (r > payload_max_length ||
  4939. payload_max_length - r < static_cast<size_t>(n)) {
  4940. return ReadContentResult::PayloadTooLarge;
  4941. }
  4942. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  4943. return ReadContentResult::Error;
  4944. }
  4945. r += static_cast<size_t>(n);
  4946. }
  4947. return ReadContentResult::Success;
  4948. }
  4949. template <typename T>
  4950. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  4951. size_t payload_max_length,
  4952. ContentReceiverWithProgress out) {
  4953. detail::ChunkedDecoder dec(strm);
  4954. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4955. size_t total_len = 0;
  4956. for (;;) {
  4957. size_t chunk_offset = 0;
  4958. size_t chunk_total = 0;
  4959. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  4960. if (n < 0) { return ReadContentResult::Error; }
  4961. if (n == 0) {
  4962. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  4963. return ReadContentResult::Error;
  4964. }
  4965. return ReadContentResult::Success;
  4966. }
  4967. if (total_len > payload_max_length ||
  4968. payload_max_length - total_len < static_cast<size_t>(n)) {
  4969. return ReadContentResult::PayloadTooLarge;
  4970. }
  4971. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  4972. return ReadContentResult::Error;
  4973. }
  4974. total_len += static_cast<size_t>(n);
  4975. }
  4976. }
  4977. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  4978. return case_ignore::equal(
  4979. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  4980. }
  4981. template <typename T, typename U>
  4982. bool prepare_content_receiver(T &x, int &status,
  4983. ContentReceiverWithProgress receiver,
  4984. bool decompress, U callback) {
  4985. if (decompress) {
  4986. std::string encoding = x.get_header_value("Content-Encoding");
  4987. std::unique_ptr<decompressor> decompressor;
  4988. if (!encoding.empty()) {
  4989. decompressor = detail::create_decompressor(encoding);
  4990. if (!decompressor) {
  4991. // Unsupported encoding or no support compiled in
  4992. status = StatusCode::UnsupportedMediaType_415;
  4993. return false;
  4994. }
  4995. }
  4996. if (decompressor) {
  4997. if (decompressor->is_valid()) {
  4998. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  4999. size_t off, size_t len) {
  5000. return decompressor->decompress(buf, n,
  5001. [&](const char *buf2, size_t n2) {
  5002. return receiver(buf2, n2, off, len);
  5003. });
  5004. };
  5005. return callback(std::move(out));
  5006. } else {
  5007. status = StatusCode::InternalServerError_500;
  5008. return false;
  5009. }
  5010. }
  5011. }
  5012. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  5013. size_t len) {
  5014. return receiver(buf, n, off, len);
  5015. };
  5016. return callback(std::move(out));
  5017. }
  5018. template <typename T>
  5019. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  5020. DownloadProgress progress,
  5021. ContentReceiverWithProgress receiver, bool decompress) {
  5022. return prepare_content_receiver(
  5023. x, status, std::move(receiver), decompress,
  5024. [&](const ContentReceiverWithProgress &out) {
  5025. auto ret = true;
  5026. auto exceed_payload_max_length = false;
  5027. if (is_chunked_transfer_encoding(x.headers)) {
  5028. auto result = read_content_chunked(strm, x, payload_max_length, out);
  5029. if (result == ReadContentResult::Success) {
  5030. ret = true;
  5031. } else if (result == ReadContentResult::PayloadTooLarge) {
  5032. exceed_payload_max_length = true;
  5033. ret = false;
  5034. } else {
  5035. ret = false;
  5036. }
  5037. } else if (!has_header(x.headers, "Content-Length")) {
  5038. auto result =
  5039. read_content_without_length(strm, payload_max_length, out);
  5040. if (result == ReadContentResult::Success) {
  5041. ret = true;
  5042. } else if (result == ReadContentResult::PayloadTooLarge) {
  5043. exceed_payload_max_length = true;
  5044. ret = false;
  5045. } else {
  5046. ret = false;
  5047. }
  5048. } else {
  5049. auto is_invalid_value = false;
  5050. auto len = get_header_value_u64(x.headers, "Content-Length",
  5051. (std::numeric_limits<size_t>::max)(),
  5052. 0, is_invalid_value);
  5053. if (is_invalid_value) {
  5054. ret = false;
  5055. } else if (len > payload_max_length) {
  5056. exceed_payload_max_length = true;
  5057. skip_content_with_length(strm, len);
  5058. ret = false;
  5059. } else if (len > 0) {
  5060. ret = read_content_with_length(strm, len, std::move(progress), out);
  5061. }
  5062. }
  5063. if (!ret) {
  5064. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  5065. : StatusCode::BadRequest_400;
  5066. }
  5067. return ret;
  5068. });
  5069. }
  5070. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  5071. const std::string &path) {
  5072. std::string s = method;
  5073. s += ' ';
  5074. s += path;
  5075. s += " HTTP/1.1\r\n";
  5076. return strm.write(s.data(), s.size());
  5077. }
  5078. inline ssize_t write_response_line(Stream &strm, int status) {
  5079. std::string s = "HTTP/1.1 ";
  5080. s += std::to_string(status);
  5081. s += ' ';
  5082. s += httplib::status_message(status);
  5083. s += "\r\n";
  5084. return strm.write(s.data(), s.size());
  5085. }
  5086. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  5087. ssize_t write_len = 0;
  5088. for (const auto &x : headers) {
  5089. std::string s;
  5090. s = x.first;
  5091. s += ": ";
  5092. s += x.second;
  5093. s += "\r\n";
  5094. auto len = strm.write(s.data(), s.size());
  5095. if (len < 0) { return len; }
  5096. write_len += len;
  5097. }
  5098. auto len = strm.write("\r\n");
  5099. if (len < 0) { return len; }
  5100. write_len += len;
  5101. return write_len;
  5102. }
  5103. inline bool write_data(Stream &strm, const char *d, size_t l) {
  5104. size_t offset = 0;
  5105. while (offset < l) {
  5106. auto length = strm.write(d + offset, l - offset);
  5107. if (length < 0) { return false; }
  5108. offset += static_cast<size_t>(length);
  5109. }
  5110. return true;
  5111. }
  5112. template <typename T>
  5113. inline bool write_content_with_progress(Stream &strm,
  5114. const ContentProvider &content_provider,
  5115. size_t offset, size_t length,
  5116. T is_shutting_down,
  5117. const UploadProgress &upload_progress,
  5118. Error &error) {
  5119. size_t end_offset = offset + length;
  5120. size_t start_offset = offset;
  5121. auto ok = true;
  5122. DataSink data_sink;
  5123. data_sink.write = [&](const char *d, size_t l) -> bool {
  5124. if (ok) {
  5125. if (write_data(strm, d, l)) {
  5126. offset += l;
  5127. if (upload_progress && length > 0) {
  5128. size_t current_written = offset - start_offset;
  5129. if (!upload_progress(current_written, length)) {
  5130. ok = false;
  5131. return false;
  5132. }
  5133. }
  5134. } else {
  5135. ok = false;
  5136. }
  5137. }
  5138. return ok;
  5139. };
  5140. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5141. while (offset < end_offset && !is_shutting_down()) {
  5142. if (!strm.wait_writable()) {
  5143. error = Error::Write;
  5144. return false;
  5145. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  5146. error = Error::Canceled;
  5147. return false;
  5148. } else if (!ok) {
  5149. error = Error::Write;
  5150. return false;
  5151. }
  5152. }
  5153. error = Error::Success;
  5154. return true;
  5155. }
  5156. template <typename T>
  5157. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5158. size_t offset, size_t length, T is_shutting_down,
  5159. Error &error) {
  5160. return write_content_with_progress<T>(strm, content_provider, offset, length,
  5161. is_shutting_down, nullptr, error);
  5162. }
  5163. template <typename T>
  5164. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5165. size_t offset, size_t length,
  5166. const T &is_shutting_down) {
  5167. auto error = Error::Success;
  5168. return write_content(strm, content_provider, offset, length, is_shutting_down,
  5169. error);
  5170. }
  5171. template <typename T>
  5172. inline bool
  5173. write_content_without_length(Stream &strm,
  5174. const ContentProvider &content_provider,
  5175. const T &is_shutting_down) {
  5176. size_t offset = 0;
  5177. auto data_available = true;
  5178. auto ok = true;
  5179. DataSink data_sink;
  5180. data_sink.write = [&](const char *d, size_t l) -> bool {
  5181. if (ok) {
  5182. offset += l;
  5183. if (!write_data(strm, d, l)) { ok = false; }
  5184. }
  5185. return ok;
  5186. };
  5187. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5188. data_sink.done = [&](void) { data_available = false; };
  5189. while (data_available && !is_shutting_down()) {
  5190. if (!strm.wait_writable()) {
  5191. return false;
  5192. } else if (!content_provider(offset, 0, data_sink)) {
  5193. return false;
  5194. } else if (!ok) {
  5195. return false;
  5196. }
  5197. }
  5198. return true;
  5199. }
  5200. template <typename T, typename U>
  5201. inline bool
  5202. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  5203. const T &is_shutting_down, U &compressor, Error &error) {
  5204. size_t offset = 0;
  5205. auto data_available = true;
  5206. auto ok = true;
  5207. DataSink data_sink;
  5208. data_sink.write = [&](const char *d, size_t l) -> bool {
  5209. if (ok) {
  5210. data_available = l > 0;
  5211. offset += l;
  5212. std::string payload;
  5213. if (compressor.compress(d, l, false,
  5214. [&](const char *data, size_t data_len) {
  5215. payload.append(data, data_len);
  5216. return true;
  5217. })) {
  5218. if (!payload.empty()) {
  5219. // Emit chunked response header and footer for each chunk
  5220. auto chunk =
  5221. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5222. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  5223. }
  5224. } else {
  5225. ok = false;
  5226. }
  5227. }
  5228. return ok;
  5229. };
  5230. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5231. auto done_with_trailer = [&](const Headers *trailer) {
  5232. if (!ok) { return; }
  5233. data_available = false;
  5234. std::string payload;
  5235. if (!compressor.compress(nullptr, 0, true,
  5236. [&](const char *data, size_t data_len) {
  5237. payload.append(data, data_len);
  5238. return true;
  5239. })) {
  5240. ok = false;
  5241. return;
  5242. }
  5243. if (!payload.empty()) {
  5244. // Emit chunked response header and footer for each chunk
  5245. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5246. if (!write_data(strm, chunk.data(), chunk.size())) {
  5247. ok = false;
  5248. return;
  5249. }
  5250. }
  5251. constexpr const char done_marker[] = "0\r\n";
  5252. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  5253. // Trailer
  5254. if (trailer) {
  5255. for (const auto &kv : *trailer) {
  5256. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  5257. if (!write_data(strm, field_line.data(), field_line.size())) {
  5258. ok = false;
  5259. }
  5260. }
  5261. }
  5262. constexpr const char crlf[] = "\r\n";
  5263. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  5264. };
  5265. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  5266. data_sink.done_with_trailer = [&](const Headers &trailer) {
  5267. done_with_trailer(&trailer);
  5268. };
  5269. while (data_available && !is_shutting_down()) {
  5270. if (!strm.wait_writable()) {
  5271. error = Error::Write;
  5272. return false;
  5273. } else if (!content_provider(offset, 0, data_sink)) {
  5274. error = Error::Canceled;
  5275. return false;
  5276. } else if (!ok) {
  5277. error = Error::Write;
  5278. return false;
  5279. }
  5280. }
  5281. error = Error::Success;
  5282. return true;
  5283. }
  5284. template <typename T, typename U>
  5285. inline bool write_content_chunked(Stream &strm,
  5286. const ContentProvider &content_provider,
  5287. const T &is_shutting_down, U &compressor) {
  5288. auto error = Error::Success;
  5289. return write_content_chunked(strm, content_provider, is_shutting_down,
  5290. compressor, error);
  5291. }
  5292. template <typename T>
  5293. inline bool redirect(T &cli, Request &req, Response &res,
  5294. const std::string &path, const std::string &location,
  5295. Error &error) {
  5296. Request new_req = req;
  5297. new_req.path = path;
  5298. new_req.redirect_count_ -= 1;
  5299. if (res.status == StatusCode::SeeOther_303 &&
  5300. (req.method != "GET" && req.method != "HEAD")) {
  5301. new_req.method = "GET";
  5302. new_req.body.clear();
  5303. new_req.headers.clear();
  5304. }
  5305. Response new_res;
  5306. auto ret = cli.send(new_req, new_res, error);
  5307. if (ret) {
  5308. req = std::move(new_req);
  5309. res = std::move(new_res);
  5310. if (res.location.empty()) { res.location = location; }
  5311. }
  5312. return ret;
  5313. }
  5314. inline std::string params_to_query_str(const Params &params) {
  5315. std::string query;
  5316. for (auto it = params.begin(); it != params.end(); ++it) {
  5317. if (it != params.begin()) { query += '&'; }
  5318. query += encode_query_component(it->first);
  5319. query += '=';
  5320. query += encode_query_component(it->second);
  5321. }
  5322. return query;
  5323. }
  5324. inline void parse_query_text(const char *data, std::size_t size,
  5325. Params &params) {
  5326. std::set<std::string> cache;
  5327. split(data, data + size, '&', [&](const char *b, const char *e) {
  5328. std::string kv(b, e);
  5329. if (cache.find(kv) != cache.end()) { return; }
  5330. cache.insert(std::move(kv));
  5331. std::string key;
  5332. std::string val;
  5333. divide(b, static_cast<std::size_t>(e - b), '=',
  5334. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  5335. std::size_t rhs_size) {
  5336. key.assign(lhs_data, lhs_size);
  5337. val.assign(rhs_data, rhs_size);
  5338. });
  5339. if (!key.empty()) {
  5340. params.emplace(decode_query_component(key), decode_query_component(val));
  5341. }
  5342. });
  5343. }
  5344. inline void parse_query_text(const std::string &s, Params &params) {
  5345. parse_query_text(s.data(), s.size(), params);
  5346. }
  5347. // Normalize a query string by decoding and re-encoding each key/value pair
  5348. // while preserving the original parameter order. This avoids double-encoding
  5349. // and ensures consistent encoding without reordering (unlike Params which
  5350. // uses std::multimap and sorts keys).
  5351. inline std::string normalize_query_string(const std::string &query) {
  5352. std::string result;
  5353. split(query.data(), query.data() + query.size(), '&',
  5354. [&](const char *b, const char *e) {
  5355. std::string key;
  5356. std::string val;
  5357. divide(b, static_cast<std::size_t>(e - b), '=',
  5358. [&](const char *lhs_data, std::size_t lhs_size,
  5359. const char *rhs_data, std::size_t rhs_size) {
  5360. key.assign(lhs_data, lhs_size);
  5361. val.assign(rhs_data, rhs_size);
  5362. });
  5363. if (!key.empty()) {
  5364. auto dec_key = decode_query_component(key);
  5365. auto dec_val = decode_query_component(val);
  5366. if (!result.empty()) { result += '&'; }
  5367. result += encode_query_component(dec_key);
  5368. if (!val.empty() || std::find(b, e, '=') != e) {
  5369. result += '=';
  5370. result += encode_query_component(dec_val);
  5371. }
  5372. }
  5373. });
  5374. return result;
  5375. }
  5376. inline bool parse_multipart_boundary(const std::string &content_type,
  5377. std::string &boundary) {
  5378. auto boundary_keyword = "boundary=";
  5379. auto pos = content_type.find(boundary_keyword);
  5380. if (pos == std::string::npos) { return false; }
  5381. auto end = content_type.find(';', pos);
  5382. auto beg = pos + strlen(boundary_keyword);
  5383. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  5384. return !boundary.empty();
  5385. }
  5386. inline void parse_disposition_params(const std::string &s, Params &params) {
  5387. std::set<std::string> cache;
  5388. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  5389. std::string kv(b, e);
  5390. if (cache.find(kv) != cache.end()) { return; }
  5391. cache.insert(kv);
  5392. std::string key;
  5393. std::string val;
  5394. split(b, e, '=', [&](const char *b2, const char *e2) {
  5395. if (key.empty()) {
  5396. key.assign(b2, e2);
  5397. } else {
  5398. val.assign(b2, e2);
  5399. }
  5400. });
  5401. if (!key.empty()) {
  5402. params.emplace(trim_double_quotes_copy((key)),
  5403. trim_double_quotes_copy((val)));
  5404. }
  5405. });
  5406. }
  5407. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5408. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  5409. #else
  5410. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  5411. #endif
  5412. auto is_valid = [](const std::string &str) {
  5413. return std::all_of(str.cbegin(), str.cend(),
  5414. [](unsigned char c) { return std::isdigit(c); });
  5415. };
  5416. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  5417. const auto pos = static_cast<size_t>(6);
  5418. const auto len = static_cast<size_t>(s.size() - 6);
  5419. auto all_valid_ranges = true;
  5420. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  5421. if (!all_valid_ranges) { return; }
  5422. const auto it = std::find(b, e, '-');
  5423. if (it == e) {
  5424. all_valid_ranges = false;
  5425. return;
  5426. }
  5427. const auto lhs = std::string(b, it);
  5428. const auto rhs = std::string(it + 1, e);
  5429. if (!is_valid(lhs) || !is_valid(rhs)) {
  5430. all_valid_ranges = false;
  5431. return;
  5432. }
  5433. ssize_t first = -1;
  5434. if (!lhs.empty()) {
  5435. ssize_t v;
  5436. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  5437. if (res.ec == std::errc{}) { first = v; }
  5438. }
  5439. ssize_t last = -1;
  5440. if (!rhs.empty()) {
  5441. ssize_t v;
  5442. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  5443. if (res.ec == std::errc{}) { last = v; }
  5444. }
  5445. if ((first == -1 && last == -1) ||
  5446. (first != -1 && last != -1 && first > last)) {
  5447. all_valid_ranges = false;
  5448. return;
  5449. }
  5450. ranges.emplace_back(first, last);
  5451. });
  5452. return all_valid_ranges && !ranges.empty();
  5453. }
  5454. return false;
  5455. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5456. }
  5457. #else
  5458. } catch (...) { return false; }
  5459. #endif
  5460. inline bool parse_accept_header(const std::string &s,
  5461. std::vector<std::string> &content_types) {
  5462. content_types.clear();
  5463. // Empty string is considered valid (no preference)
  5464. if (s.empty()) { return true; }
  5465. // Check for invalid patterns: leading/trailing commas or consecutive commas
  5466. if (s.front() == ',' || s.back() == ',' ||
  5467. s.find(",,") != std::string::npos) {
  5468. return false;
  5469. }
  5470. struct AcceptEntry {
  5471. std::string media_type;
  5472. double quality;
  5473. int order; // Original order in header
  5474. };
  5475. std::vector<AcceptEntry> entries;
  5476. int order = 0;
  5477. bool has_invalid_entry = false;
  5478. // Split by comma and parse each entry
  5479. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5480. std::string entry(b, e);
  5481. entry = trim_copy(entry);
  5482. if (entry.empty()) {
  5483. has_invalid_entry = true;
  5484. return;
  5485. }
  5486. AcceptEntry accept_entry;
  5487. accept_entry.quality = 1.0; // Default quality
  5488. accept_entry.order = order++;
  5489. // Find q= parameter
  5490. auto q_pos = entry.find(";q=");
  5491. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  5492. if (q_pos != std::string::npos) {
  5493. // Extract media type (before q parameter)
  5494. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  5495. // Extract quality value
  5496. auto q_start = entry.find('=', q_pos) + 1;
  5497. auto q_end = entry.find(';', q_start);
  5498. if (q_end == std::string::npos) { q_end = entry.length(); }
  5499. std::string quality_str =
  5500. trim_copy(entry.substr(q_start, q_end - q_start));
  5501. if (quality_str.empty()) {
  5502. has_invalid_entry = true;
  5503. return;
  5504. }
  5505. {
  5506. double v = 0.0;
  5507. auto res = detail::from_chars(
  5508. quality_str.data(), quality_str.data() + quality_str.size(), v);
  5509. if (res.ec == std::errc{}) {
  5510. accept_entry.quality = v;
  5511. } else {
  5512. has_invalid_entry = true;
  5513. return;
  5514. }
  5515. }
  5516. // Check if quality is in valid range [0.0, 1.0]
  5517. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  5518. has_invalid_entry = true;
  5519. return;
  5520. }
  5521. } else {
  5522. // No quality parameter, use entire entry as media type
  5523. accept_entry.media_type = entry;
  5524. }
  5525. // Remove additional parameters from media type
  5526. auto param_pos = accept_entry.media_type.find(';');
  5527. if (param_pos != std::string::npos) {
  5528. accept_entry.media_type =
  5529. trim_copy(accept_entry.media_type.substr(0, param_pos));
  5530. }
  5531. // Basic validation of media type format
  5532. if (accept_entry.media_type.empty()) {
  5533. has_invalid_entry = true;
  5534. return;
  5535. }
  5536. // Check for basic media type format (should contain '/' or be '*')
  5537. if (accept_entry.media_type != "*" &&
  5538. accept_entry.media_type.find('/') == std::string::npos) {
  5539. has_invalid_entry = true;
  5540. return;
  5541. }
  5542. entries.push_back(std::move(accept_entry));
  5543. });
  5544. // Return false if any invalid entry was found
  5545. if (has_invalid_entry) { return false; }
  5546. // Sort by quality (descending), then by original order (ascending)
  5547. std::sort(entries.begin(), entries.end(),
  5548. [](const AcceptEntry &a, const AcceptEntry &b) {
  5549. if (a.quality != b.quality) {
  5550. return a.quality > b.quality; // Higher quality first
  5551. }
  5552. return a.order < b.order; // Earlier order first for same quality
  5553. });
  5554. // Extract sorted media types
  5555. content_types.reserve(entries.size());
  5556. for (auto &entry : entries) {
  5557. content_types.push_back(std::move(entry.media_type));
  5558. }
  5559. return true;
  5560. }
  5561. class FormDataParser {
  5562. public:
  5563. FormDataParser() = default;
  5564. void set_boundary(std::string &&boundary) {
  5565. boundary_ = std::move(boundary);
  5566. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  5567. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  5568. }
  5569. bool is_valid() const { return is_valid_; }
  5570. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  5571. const ContentReceiver &content_callback) {
  5572. buf_append(buf, n);
  5573. while (buf_size() > 0) {
  5574. switch (state_) {
  5575. case 0: { // Initial boundary
  5576. auto pos = buf_find(dash_boundary_crlf_);
  5577. if (pos == buf_size()) { return true; }
  5578. buf_erase(pos + dash_boundary_crlf_.size());
  5579. state_ = 1;
  5580. break;
  5581. }
  5582. case 1: { // New entry
  5583. clear_file_info();
  5584. state_ = 2;
  5585. break;
  5586. }
  5587. case 2: { // Headers
  5588. auto pos = buf_find(crlf_);
  5589. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5590. while (pos < buf_size()) {
  5591. // Empty line
  5592. if (pos == 0) {
  5593. if (!header_callback(file_)) {
  5594. is_valid_ = false;
  5595. return false;
  5596. }
  5597. buf_erase(crlf_.size());
  5598. state_ = 3;
  5599. break;
  5600. }
  5601. const auto header = buf_head(pos);
  5602. if (!parse_header(header.data(), header.data() + header.size(),
  5603. [&](const std::string &, const std::string &) {})) {
  5604. is_valid_ = false;
  5605. return false;
  5606. }
  5607. // Parse and emplace space trimmed headers into a map
  5608. if (!parse_header(
  5609. header.data(), header.data() + header.size(),
  5610. [&](const std::string &key, const std::string &val) {
  5611. file_.headers.emplace(key, val);
  5612. })) {
  5613. is_valid_ = false;
  5614. return false;
  5615. }
  5616. constexpr const char header_content_type[] = "Content-Type:";
  5617. if (start_with_case_ignore(header, header_content_type)) {
  5618. file_.content_type =
  5619. trim_copy(header.substr(str_len(header_content_type)));
  5620. } else {
  5621. thread_local const std::regex re_content_disposition(
  5622. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  5623. std::regex_constants::icase);
  5624. std::smatch m;
  5625. if (std::regex_match(header, m, re_content_disposition)) {
  5626. Params params;
  5627. parse_disposition_params(m[1], params);
  5628. auto it = params.find("name");
  5629. if (it != params.end()) {
  5630. file_.name = it->second;
  5631. } else {
  5632. is_valid_ = false;
  5633. return false;
  5634. }
  5635. it = params.find("filename");
  5636. if (it != params.end()) { file_.filename = it->second; }
  5637. it = params.find("filename*");
  5638. if (it != params.end()) {
  5639. // Only allow UTF-8 encoding...
  5640. thread_local const std::regex re_rfc5987_encoding(
  5641. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  5642. std::smatch m2;
  5643. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  5644. file_.filename = decode_path_component(m2[1]); // override...
  5645. } else {
  5646. is_valid_ = false;
  5647. return false;
  5648. }
  5649. }
  5650. }
  5651. }
  5652. buf_erase(pos + crlf_.size());
  5653. pos = buf_find(crlf_);
  5654. }
  5655. if (state_ != 3) { return true; }
  5656. break;
  5657. }
  5658. case 3: { // Body
  5659. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  5660. auto pos = buf_find(crlf_dash_boundary_);
  5661. if (pos < buf_size()) {
  5662. if (!content_callback(buf_data(), pos)) {
  5663. is_valid_ = false;
  5664. return false;
  5665. }
  5666. buf_erase(pos + crlf_dash_boundary_.size());
  5667. state_ = 4;
  5668. } else {
  5669. auto len = buf_size() - crlf_dash_boundary_.size();
  5670. if (len > 0) {
  5671. if (!content_callback(buf_data(), len)) {
  5672. is_valid_ = false;
  5673. return false;
  5674. }
  5675. buf_erase(len);
  5676. }
  5677. return true;
  5678. }
  5679. break;
  5680. }
  5681. case 4: { // Boundary
  5682. if (crlf_.size() > buf_size()) { return true; }
  5683. if (buf_start_with(crlf_)) {
  5684. buf_erase(crlf_.size());
  5685. state_ = 1;
  5686. } else {
  5687. if (dash_.size() > buf_size()) { return true; }
  5688. if (buf_start_with(dash_)) {
  5689. buf_erase(dash_.size());
  5690. is_valid_ = true;
  5691. buf_erase(buf_size()); // Remove epilogue
  5692. } else {
  5693. return true;
  5694. }
  5695. }
  5696. break;
  5697. }
  5698. }
  5699. }
  5700. return true;
  5701. }
  5702. private:
  5703. void clear_file_info() {
  5704. file_.name.clear();
  5705. file_.filename.clear();
  5706. file_.content_type.clear();
  5707. file_.headers.clear();
  5708. }
  5709. bool start_with_case_ignore(const std::string &a, const char *b) const {
  5710. const auto b_len = strlen(b);
  5711. if (a.size() < b_len) { return false; }
  5712. for (size_t i = 0; i < b_len; i++) {
  5713. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  5714. return false;
  5715. }
  5716. }
  5717. return true;
  5718. }
  5719. const std::string dash_ = "--";
  5720. const std::string crlf_ = "\r\n";
  5721. std::string boundary_;
  5722. std::string dash_boundary_crlf_;
  5723. std::string crlf_dash_boundary_;
  5724. size_t state_ = 0;
  5725. bool is_valid_ = false;
  5726. FormData file_;
  5727. // Buffer
  5728. bool start_with(const std::string &a, size_t spos, size_t epos,
  5729. const std::string &b) const {
  5730. if (epos - spos < b.size()) { return false; }
  5731. for (size_t i = 0; i < b.size(); i++) {
  5732. if (a[i + spos] != b[i]) { return false; }
  5733. }
  5734. return true;
  5735. }
  5736. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  5737. const char *buf_data() const { return &buf_[buf_spos_]; }
  5738. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  5739. bool buf_start_with(const std::string &s) const {
  5740. return start_with(buf_, buf_spos_, buf_epos_, s);
  5741. }
  5742. size_t buf_find(const std::string &s) const {
  5743. auto c = s.front();
  5744. size_t off = buf_spos_;
  5745. while (off < buf_epos_) {
  5746. auto pos = off;
  5747. while (true) {
  5748. if (pos == buf_epos_) { return buf_size(); }
  5749. if (buf_[pos] == c) { break; }
  5750. pos++;
  5751. }
  5752. auto remaining_size = buf_epos_ - pos;
  5753. if (s.size() > remaining_size) { return buf_size(); }
  5754. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  5755. off = pos + 1;
  5756. }
  5757. return buf_size();
  5758. }
  5759. void buf_append(const char *data, size_t n) {
  5760. auto remaining_size = buf_size();
  5761. if (remaining_size > 0 && buf_spos_ > 0) {
  5762. for (size_t i = 0; i < remaining_size; i++) {
  5763. buf_[i] = buf_[buf_spos_ + i];
  5764. }
  5765. }
  5766. buf_spos_ = 0;
  5767. buf_epos_ = remaining_size;
  5768. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  5769. for (size_t i = 0; i < n; i++) {
  5770. buf_[buf_epos_ + i] = data[i];
  5771. }
  5772. buf_epos_ += n;
  5773. }
  5774. void buf_erase(size_t size) { buf_spos_ += size; }
  5775. std::string buf_;
  5776. size_t buf_spos_ = 0;
  5777. size_t buf_epos_ = 0;
  5778. };
  5779. inline std::string random_string(size_t length) {
  5780. constexpr const char data[] =
  5781. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  5782. thread_local auto engine([]() {
  5783. // std::random_device might actually be deterministic on some
  5784. // platforms, but due to lack of support in the c++ standard library,
  5785. // doing better requires either some ugly hacks or breaking portability.
  5786. std::random_device seed_gen;
  5787. // Request 128 bits of entropy for initialization
  5788. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  5789. return std::mt19937(seed_sequence);
  5790. }());
  5791. std::string result;
  5792. for (size_t i = 0; i < length; i++) {
  5793. result += data[engine() % (sizeof(data) - 1)];
  5794. }
  5795. return result;
  5796. }
  5797. inline std::string make_multipart_data_boundary() {
  5798. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  5799. }
  5800. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  5801. auto valid = true;
  5802. for (size_t i = 0; i < boundary.size(); i++) {
  5803. auto c = boundary[i];
  5804. if (!std::isalnum(c) && c != '-' && c != '_') {
  5805. valid = false;
  5806. break;
  5807. }
  5808. }
  5809. return valid;
  5810. }
  5811. template <typename T>
  5812. inline std::string
  5813. serialize_multipart_formdata_item_begin(const T &item,
  5814. const std::string &boundary) {
  5815. std::string body = "--" + boundary + "\r\n";
  5816. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5817. if (!item.filename.empty()) {
  5818. body += "; filename=\"" + item.filename + "\"";
  5819. }
  5820. body += "\r\n";
  5821. if (!item.content_type.empty()) {
  5822. body += "Content-Type: " + item.content_type + "\r\n";
  5823. }
  5824. body += "\r\n";
  5825. return body;
  5826. }
  5827. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  5828. inline std::string
  5829. serialize_multipart_formdata_finish(const std::string &boundary) {
  5830. return "--" + boundary + "--\r\n";
  5831. }
  5832. inline std::string
  5833. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  5834. return "multipart/form-data; boundary=" + boundary;
  5835. }
  5836. inline std::string
  5837. serialize_multipart_formdata(const UploadFormDataItems &items,
  5838. const std::string &boundary, bool finish = true) {
  5839. std::string body;
  5840. for (const auto &item : items) {
  5841. body += serialize_multipart_formdata_item_begin(item, boundary);
  5842. body += item.content + serialize_multipart_formdata_item_end();
  5843. }
  5844. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  5845. return body;
  5846. }
  5847. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  5848. if (ranges.size() <= 1) return;
  5849. // Sort ranges by start position
  5850. std::sort(ranges.begin(), ranges.end(),
  5851. [](const Range &a, const Range &b) { return a.first < b.first; });
  5852. Ranges coalesced;
  5853. coalesced.reserve(ranges.size());
  5854. for (auto &r : ranges) {
  5855. auto first_pos = r.first;
  5856. auto last_pos = r.second;
  5857. // Handle special cases like in range_error
  5858. if (first_pos == -1 && last_pos == -1) {
  5859. first_pos = 0;
  5860. last_pos = static_cast<ssize_t>(content_length);
  5861. }
  5862. if (first_pos == -1) {
  5863. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  5864. last_pos = static_cast<ssize_t>(content_length) - 1;
  5865. }
  5866. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  5867. last_pos = static_cast<ssize_t>(content_length) - 1;
  5868. }
  5869. // Skip invalid ranges
  5870. if (!(0 <= first_pos && first_pos <= last_pos &&
  5871. last_pos < static_cast<ssize_t>(content_length))) {
  5872. continue;
  5873. }
  5874. // Coalesce with previous range if overlapping or adjacent (but not
  5875. // identical)
  5876. if (!coalesced.empty()) {
  5877. auto &prev = coalesced.back();
  5878. // Check if current range overlaps or is adjacent to previous range
  5879. // but don't coalesce identical ranges (allow duplicates)
  5880. if (first_pos <= prev.second + 1 &&
  5881. !(first_pos == prev.first && last_pos == prev.second)) {
  5882. // Extend the previous range
  5883. prev.second = (std::max)(prev.second, last_pos);
  5884. continue;
  5885. }
  5886. }
  5887. // Add new range
  5888. coalesced.emplace_back(first_pos, last_pos);
  5889. }
  5890. ranges = std::move(coalesced);
  5891. }
  5892. inline bool range_error(Request &req, Response &res) {
  5893. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  5894. ssize_t content_len = static_cast<ssize_t>(
  5895. res.content_length_ ? res.content_length_ : res.body.size());
  5896. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  5897. size_t overwrapping_count = 0;
  5898. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  5899. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  5900. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  5901. // Too many ranges
  5902. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  5903. for (auto &r : req.ranges) {
  5904. auto &first_pos = r.first;
  5905. auto &last_pos = r.second;
  5906. if (first_pos == -1 && last_pos == -1) {
  5907. first_pos = 0;
  5908. last_pos = content_len;
  5909. }
  5910. if (first_pos == -1) {
  5911. first_pos = content_len - last_pos;
  5912. last_pos = content_len - 1;
  5913. }
  5914. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  5915. // A client can limit the number of bytes requested without knowing the
  5916. // size of the selected representation. If the last-pos value is absent,
  5917. // or if the value is greater than or equal to the current length of the
  5918. // representation data, the byte range is interpreted as the remainder of
  5919. // the representation (i.e., the server replaces the value of last-pos
  5920. // with a value that is one less than the current length of the selected
  5921. // representation).
  5922. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  5923. if (last_pos == -1 || last_pos >= content_len) {
  5924. last_pos = content_len - 1;
  5925. }
  5926. // Range must be within content length
  5927. if (!(0 <= first_pos && first_pos <= last_pos &&
  5928. last_pos <= content_len - 1)) {
  5929. return true;
  5930. }
  5931. // Request must not have more than two overlapping ranges
  5932. for (const auto &processed_range : processed_ranges) {
  5933. if (!(last_pos < processed_range.first ||
  5934. first_pos > processed_range.second)) {
  5935. overwrapping_count++;
  5936. if (overwrapping_count > 2) { return true; }
  5937. break; // Only count once per range
  5938. }
  5939. }
  5940. processed_ranges.emplace_back(first_pos, last_pos);
  5941. }
  5942. // After validation, coalesce overlapping ranges as per RFC 9110
  5943. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  5944. }
  5945. return false;
  5946. }
  5947. inline std::pair<size_t, size_t>
  5948. get_range_offset_and_length(Range r, size_t content_length) {
  5949. assert(r.first != -1 && r.second != -1);
  5950. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  5951. assert(r.first <= r.second &&
  5952. r.second < static_cast<ssize_t>(content_length));
  5953. (void)(content_length);
  5954. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  5955. }
  5956. inline std::string make_content_range_header_field(
  5957. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  5958. auto st = offset_and_length.first;
  5959. auto ed = st + offset_and_length.second - 1;
  5960. std::string field = "bytes ";
  5961. field += std::to_string(st);
  5962. field += '-';
  5963. field += std::to_string(ed);
  5964. field += '/';
  5965. field += std::to_string(content_length);
  5966. return field;
  5967. }
  5968. template <typename SToken, typename CToken, typename Content>
  5969. bool process_multipart_ranges_data(const Request &req,
  5970. const std::string &boundary,
  5971. const std::string &content_type,
  5972. size_t content_length, SToken stoken,
  5973. CToken ctoken, Content content) {
  5974. for (size_t i = 0; i < req.ranges.size(); i++) {
  5975. ctoken("--");
  5976. stoken(boundary);
  5977. ctoken("\r\n");
  5978. if (!content_type.empty()) {
  5979. ctoken("Content-Type: ");
  5980. stoken(content_type);
  5981. ctoken("\r\n");
  5982. }
  5983. auto offset_and_length =
  5984. get_range_offset_and_length(req.ranges[i], content_length);
  5985. ctoken("Content-Range: ");
  5986. stoken(make_content_range_header_field(offset_and_length, content_length));
  5987. ctoken("\r\n");
  5988. ctoken("\r\n");
  5989. if (!content(offset_and_length.first, offset_and_length.second)) {
  5990. return false;
  5991. }
  5992. ctoken("\r\n");
  5993. }
  5994. ctoken("--");
  5995. stoken(boundary);
  5996. ctoken("--");
  5997. return true;
  5998. }
  5999. inline void make_multipart_ranges_data(const Request &req, Response &res,
  6000. const std::string &boundary,
  6001. const std::string &content_type,
  6002. size_t content_length,
  6003. std::string &data) {
  6004. process_multipart_ranges_data(
  6005. req, boundary, content_type, content_length,
  6006. [&](const std::string &token) { data += token; },
  6007. [&](const std::string &token) { data += token; },
  6008. [&](size_t offset, size_t length) {
  6009. assert(offset + length <= content_length);
  6010. data += res.body.substr(offset, length);
  6011. return true;
  6012. });
  6013. }
  6014. inline size_t get_multipart_ranges_data_length(const Request &req,
  6015. const std::string &boundary,
  6016. const std::string &content_type,
  6017. size_t content_length) {
  6018. size_t data_length = 0;
  6019. process_multipart_ranges_data(
  6020. req, boundary, content_type, content_length,
  6021. [&](const std::string &token) { data_length += token.size(); },
  6022. [&](const std::string &token) { data_length += token.size(); },
  6023. [&](size_t /*offset*/, size_t length) {
  6024. data_length += length;
  6025. return true;
  6026. });
  6027. return data_length;
  6028. }
  6029. template <typename T>
  6030. inline bool
  6031. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  6032. const std::string &boundary,
  6033. const std::string &content_type,
  6034. size_t content_length, const T &is_shutting_down) {
  6035. return process_multipart_ranges_data(
  6036. req, boundary, content_type, content_length,
  6037. [&](const std::string &token) { strm.write(token); },
  6038. [&](const std::string &token) { strm.write(token); },
  6039. [&](size_t offset, size_t length) {
  6040. return write_content(strm, res.content_provider_, offset, length,
  6041. is_shutting_down);
  6042. });
  6043. }
  6044. inline bool expect_content(const Request &req) {
  6045. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  6046. req.method == "DELETE") {
  6047. return true;
  6048. }
  6049. if (req.has_header("Content-Length") &&
  6050. req.get_header_value_u64("Content-Length") > 0) {
  6051. return true;
  6052. }
  6053. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  6054. return false;
  6055. }
  6056. inline bool has_crlf(const std::string &s) {
  6057. auto p = s.c_str();
  6058. while (*p) {
  6059. if (*p == '\r' || *p == '\n') { return true; }
  6060. p++;
  6061. }
  6062. return false;
  6063. }
  6064. #ifdef _WIN32
  6065. class WSInit {
  6066. public:
  6067. WSInit() {
  6068. WSADATA wsaData;
  6069. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  6070. }
  6071. ~WSInit() {
  6072. if (is_valid_) WSACleanup();
  6073. }
  6074. bool is_valid_ = false;
  6075. };
  6076. static WSInit wsinit_;
  6077. #endif
  6078. inline bool parse_www_authenticate(const Response &res,
  6079. std::map<std::string, std::string> &auth,
  6080. bool is_proxy) {
  6081. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  6082. if (res.has_header(auth_key)) {
  6083. thread_local auto re =
  6084. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  6085. auto s = res.get_header_value(auth_key);
  6086. auto pos = s.find(' ');
  6087. if (pos != std::string::npos) {
  6088. auto type = s.substr(0, pos);
  6089. if (type == "Basic") {
  6090. return false;
  6091. } else if (type == "Digest") {
  6092. s = s.substr(pos + 1);
  6093. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  6094. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  6095. const auto &m = *i;
  6096. auto key = s.substr(static_cast<size_t>(m.position(1)),
  6097. static_cast<size_t>(m.length(1)));
  6098. auto val = m.length(2) > 0
  6099. ? s.substr(static_cast<size_t>(m.position(2)),
  6100. static_cast<size_t>(m.length(2)))
  6101. : s.substr(static_cast<size_t>(m.position(3)),
  6102. static_cast<size_t>(m.length(3)));
  6103. auth[std::move(key)] = std::move(val);
  6104. }
  6105. return true;
  6106. }
  6107. }
  6108. }
  6109. return false;
  6110. }
  6111. class ContentProviderAdapter {
  6112. public:
  6113. explicit ContentProviderAdapter(
  6114. ContentProviderWithoutLength &&content_provider)
  6115. : content_provider_(std::move(content_provider)) {}
  6116. bool operator()(size_t offset, size_t, DataSink &sink) {
  6117. return content_provider_(offset, sink);
  6118. }
  6119. private:
  6120. ContentProviderWithoutLength content_provider_;
  6121. };
  6122. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  6123. namespace fields {
  6124. inline bool is_token_char(char c) {
  6125. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  6126. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  6127. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  6128. }
  6129. inline bool is_token(const std::string &s) {
  6130. if (s.empty()) { return false; }
  6131. for (auto c : s) {
  6132. if (!is_token_char(c)) { return false; }
  6133. }
  6134. return true;
  6135. }
  6136. inline bool is_field_name(const std::string &s) { return is_token(s); }
  6137. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  6138. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  6139. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  6140. inline bool is_field_content(const std::string &s) {
  6141. if (s.empty()) { return true; }
  6142. if (s.size() == 1) {
  6143. return is_field_vchar(s[0]);
  6144. } else if (s.size() == 2) {
  6145. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  6146. } else {
  6147. size_t i = 0;
  6148. if (!is_field_vchar(s[i])) { return false; }
  6149. i++;
  6150. while (i < s.size() - 1) {
  6151. auto c = s[i++];
  6152. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  6153. } else {
  6154. return false;
  6155. }
  6156. }
  6157. return is_field_vchar(s[i]);
  6158. }
  6159. }
  6160. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  6161. } // namespace fields
  6162. } // namespace detail
  6163. /*
  6164. * Group 2: detail namespace - SSL common utilities
  6165. */
  6166. #ifdef CPPHTTPLIB_SSL_ENABLED
  6167. namespace detail {
  6168. class SSLSocketStream final : public Stream {
  6169. public:
  6170. SSLSocketStream(
  6171. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  6172. time_t read_timeout_usec, time_t write_timeout_sec,
  6173. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  6174. std::chrono::time_point<std::chrono::steady_clock> start_time =
  6175. (std::chrono::steady_clock::time_point::min)());
  6176. ~SSLSocketStream() override;
  6177. bool is_readable() const override;
  6178. bool wait_readable() const override;
  6179. bool wait_writable() const override;
  6180. ssize_t read(char *ptr, size_t size) override;
  6181. ssize_t write(const char *ptr, size_t size) override;
  6182. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  6183. void get_local_ip_and_port(std::string &ip, int &port) const override;
  6184. socket_t socket() const override;
  6185. time_t duration() const override;
  6186. private:
  6187. socket_t sock_;
  6188. tls::session_t session_;
  6189. time_t read_timeout_sec_;
  6190. time_t read_timeout_usec_;
  6191. time_t write_timeout_sec_;
  6192. time_t write_timeout_usec_;
  6193. time_t max_timeout_msec_;
  6194. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  6195. };
  6196. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6197. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  6198. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  6199. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  6200. unsigned int hash_length = 0;
  6201. unsigned char hash[EVP_MAX_MD_SIZE];
  6202. EVP_DigestInit_ex(context.get(), algo, nullptr);
  6203. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  6204. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  6205. std::stringstream ss;
  6206. for (auto i = 0u; i < hash_length; ++i) {
  6207. ss << std::hex << std::setw(2) << std::setfill('0')
  6208. << static_cast<unsigned int>(hash[i]);
  6209. }
  6210. return ss.str();
  6211. }
  6212. inline std::string MD5(const std::string &s) {
  6213. return message_digest(s, EVP_md5());
  6214. }
  6215. inline std::string SHA_256(const std::string &s) {
  6216. return message_digest(s, EVP_sha256());
  6217. }
  6218. inline std::string SHA_512(const std::string &s) {
  6219. return message_digest(s, EVP_sha512());
  6220. }
  6221. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  6222. namespace {
  6223. template <size_t N>
  6224. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  6225. std::stringstream ss;
  6226. for (size_t i = 0; i < N; ++i) {
  6227. ss << std::hex << std::setw(2) << std::setfill('0')
  6228. << static_cast<unsigned int>(hash[i]);
  6229. }
  6230. return ss.str();
  6231. }
  6232. } // namespace
  6233. inline std::string MD5(const std::string &s) {
  6234. unsigned char hash[16];
  6235. #ifdef CPPHTTPLIB_MBEDTLS_V3
  6236. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6237. hash);
  6238. #else
  6239. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6240. hash);
  6241. #endif
  6242. return hash_to_hex(hash);
  6243. }
  6244. inline std::string SHA_256(const std::string &s) {
  6245. unsigned char hash[32];
  6246. #ifdef CPPHTTPLIB_MBEDTLS_V3
  6247. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6248. hash, 0);
  6249. #else
  6250. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6251. s.size(), hash, 0);
  6252. #endif
  6253. return hash_to_hex(hash);
  6254. }
  6255. inline std::string SHA_512(const std::string &s) {
  6256. unsigned char hash[64];
  6257. #ifdef CPPHTTPLIB_MBEDTLS_V3
  6258. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  6259. hash, 0);
  6260. #else
  6261. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  6262. s.size(), hash, 0);
  6263. #endif
  6264. return hash_to_hex(hash);
  6265. }
  6266. #endif
  6267. inline bool is_ip_address(const std::string &host) {
  6268. struct in_addr addr4;
  6269. struct in6_addr addr6;
  6270. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  6271. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  6272. }
  6273. template <typename T>
  6274. inline bool process_server_socket_ssl(
  6275. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  6276. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  6277. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  6278. time_t write_timeout_usec, T callback) {
  6279. return process_server_socket_core(
  6280. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  6281. [&](bool close_connection, bool &connection_closed) {
  6282. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  6283. write_timeout_sec, write_timeout_usec);
  6284. return callback(strm, close_connection, connection_closed);
  6285. });
  6286. }
  6287. template <typename T>
  6288. inline bool process_client_socket_ssl(
  6289. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  6290. time_t read_timeout_usec, time_t write_timeout_sec,
  6291. time_t write_timeout_usec, time_t max_timeout_msec,
  6292. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  6293. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  6294. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  6295. start_time);
  6296. return callback(strm);
  6297. }
  6298. inline std::pair<std::string, std::string> make_digest_authentication_header(
  6299. const Request &req, const std::map<std::string, std::string> &auth,
  6300. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  6301. const std::string &password, bool is_proxy = false) {
  6302. std::string nc;
  6303. {
  6304. std::stringstream ss;
  6305. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  6306. nc = ss.str();
  6307. }
  6308. std::string qop;
  6309. if (auth.find("qop") != auth.end()) {
  6310. qop = auth.at("qop");
  6311. if (qop.find("auth-int") != std::string::npos) {
  6312. qop = "auth-int";
  6313. } else if (qop.find("auth") != std::string::npos) {
  6314. qop = "auth";
  6315. } else {
  6316. qop.clear();
  6317. }
  6318. }
  6319. std::string algo = "MD5";
  6320. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  6321. std::string response;
  6322. {
  6323. auto H = algo == "SHA-256" ? detail::SHA_256
  6324. : algo == "SHA-512" ? detail::SHA_512
  6325. : detail::MD5;
  6326. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  6327. auto A2 = req.method + ":" + req.path;
  6328. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  6329. if (qop.empty()) {
  6330. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  6331. } else {
  6332. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  6333. ":" + qop + ":" + H(A2));
  6334. }
  6335. }
  6336. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  6337. auto field = "Digest username=\"" + username + "\", realm=\"" +
  6338. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  6339. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  6340. (qop.empty() ? ", response=\""
  6341. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  6342. cnonce + "\", response=\"") +
  6343. response + "\"" +
  6344. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  6345. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6346. return std::make_pair(key, field);
  6347. }
  6348. inline bool match_hostname(const std::string &pattern,
  6349. const std::string &hostname) {
  6350. // Exact match (case-insensitive)
  6351. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  6352. // Split both pattern and hostname into components by '.'
  6353. std::vector<std::string> pattern_components;
  6354. if (!pattern.empty()) {
  6355. split(pattern.data(), pattern.data() + pattern.size(), '.',
  6356. [&](const char *b, const char *e) {
  6357. pattern_components.emplace_back(b, e);
  6358. });
  6359. }
  6360. std::vector<std::string> host_components;
  6361. if (!hostname.empty()) {
  6362. split(hostname.data(), hostname.data() + hostname.size(), '.',
  6363. [&](const char *b, const char *e) {
  6364. host_components.emplace_back(b, e);
  6365. });
  6366. }
  6367. // Component count must match
  6368. if (host_components.size() != pattern_components.size()) { return false; }
  6369. // Compare each component with wildcard support
  6370. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  6371. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  6372. auto itr = pattern_components.begin();
  6373. for (const auto &h : host_components) {
  6374. auto &p = *itr;
  6375. if (!detail::case_ignore::equal(p, h) && p != "*") {
  6376. bool partial_match = false;
  6377. if (!p.empty() && p[p.size() - 1] == '*') {
  6378. const auto prefix_length = p.size() - 1;
  6379. if (prefix_length == 0) {
  6380. partial_match = true;
  6381. } else if (h.size() >= prefix_length) {
  6382. partial_match =
  6383. std::equal(p.begin(),
  6384. p.begin() + static_cast<std::string::difference_type>(
  6385. prefix_length),
  6386. h.begin(), [](const char ca, const char cb) {
  6387. return detail::case_ignore::to_lower(ca) ==
  6388. detail::case_ignore::to_lower(cb);
  6389. });
  6390. }
  6391. }
  6392. if (!partial_match) { return false; }
  6393. }
  6394. ++itr;
  6395. }
  6396. return true;
  6397. }
  6398. } // namespace detail
  6399. #endif // CPPHTTPLIB_SSL_ENABLED
  6400. /*
  6401. * Group 3: httplib namespace - Non-SSL public API implementations
  6402. */
  6403. inline void default_socket_options(socket_t sock) {
  6404. detail::set_socket_opt(sock, SOL_SOCKET,
  6405. #ifdef SO_REUSEPORT
  6406. SO_REUSEPORT,
  6407. #else
  6408. SO_REUSEADDR,
  6409. #endif
  6410. 1);
  6411. }
  6412. inline std::string get_bearer_token_auth(const Request &req) {
  6413. if (req.has_header("Authorization")) {
  6414. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  6415. return req.get_header_value("Authorization")
  6416. .substr(bearer_header_prefix_len);
  6417. }
  6418. return "";
  6419. }
  6420. inline const char *status_message(int status) {
  6421. switch (status) {
  6422. case StatusCode::Continue_100: return "Continue";
  6423. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  6424. case StatusCode::Processing_102: return "Processing";
  6425. case StatusCode::EarlyHints_103: return "Early Hints";
  6426. case StatusCode::OK_200: return "OK";
  6427. case StatusCode::Created_201: return "Created";
  6428. case StatusCode::Accepted_202: return "Accepted";
  6429. case StatusCode::NonAuthoritativeInformation_203:
  6430. return "Non-Authoritative Information";
  6431. case StatusCode::NoContent_204: return "No Content";
  6432. case StatusCode::ResetContent_205: return "Reset Content";
  6433. case StatusCode::PartialContent_206: return "Partial Content";
  6434. case StatusCode::MultiStatus_207: return "Multi-Status";
  6435. case StatusCode::AlreadyReported_208: return "Already Reported";
  6436. case StatusCode::IMUsed_226: return "IM Used";
  6437. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  6438. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  6439. case StatusCode::Found_302: return "Found";
  6440. case StatusCode::SeeOther_303: return "See Other";
  6441. case StatusCode::NotModified_304: return "Not Modified";
  6442. case StatusCode::UseProxy_305: return "Use Proxy";
  6443. case StatusCode::unused_306: return "unused";
  6444. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  6445. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  6446. case StatusCode::BadRequest_400: return "Bad Request";
  6447. case StatusCode::Unauthorized_401: return "Unauthorized";
  6448. case StatusCode::PaymentRequired_402: return "Payment Required";
  6449. case StatusCode::Forbidden_403: return "Forbidden";
  6450. case StatusCode::NotFound_404: return "Not Found";
  6451. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  6452. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  6453. case StatusCode::ProxyAuthenticationRequired_407:
  6454. return "Proxy Authentication Required";
  6455. case StatusCode::RequestTimeout_408: return "Request Timeout";
  6456. case StatusCode::Conflict_409: return "Conflict";
  6457. case StatusCode::Gone_410: return "Gone";
  6458. case StatusCode::LengthRequired_411: return "Length Required";
  6459. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  6460. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  6461. case StatusCode::UriTooLong_414: return "URI Too Long";
  6462. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  6463. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  6464. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  6465. case StatusCode::ImATeapot_418: return "I'm a teapot";
  6466. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  6467. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  6468. case StatusCode::Locked_423: return "Locked";
  6469. case StatusCode::FailedDependency_424: return "Failed Dependency";
  6470. case StatusCode::TooEarly_425: return "Too Early";
  6471. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  6472. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  6473. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  6474. case StatusCode::RequestHeaderFieldsTooLarge_431:
  6475. return "Request Header Fields Too Large";
  6476. case StatusCode::UnavailableForLegalReasons_451:
  6477. return "Unavailable For Legal Reasons";
  6478. case StatusCode::NotImplemented_501: return "Not Implemented";
  6479. case StatusCode::BadGateway_502: return "Bad Gateway";
  6480. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  6481. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  6482. case StatusCode::HttpVersionNotSupported_505:
  6483. return "HTTP Version Not Supported";
  6484. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  6485. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  6486. case StatusCode::LoopDetected_508: return "Loop Detected";
  6487. case StatusCode::NotExtended_510: return "Not Extended";
  6488. case StatusCode::NetworkAuthenticationRequired_511:
  6489. return "Network Authentication Required";
  6490. default:
  6491. case StatusCode::InternalServerError_500: return "Internal Server Error";
  6492. }
  6493. }
  6494. inline std::string to_string(const Error error) {
  6495. switch (error) {
  6496. case Error::Success: return "Success (no error)";
  6497. case Error::Unknown: return "Unknown";
  6498. case Error::Connection: return "Could not establish connection";
  6499. case Error::BindIPAddress: return "Failed to bind IP address";
  6500. case Error::Read: return "Failed to read connection";
  6501. case Error::Write: return "Failed to write connection";
  6502. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  6503. case Error::Canceled: return "Connection handling canceled";
  6504. case Error::SSLConnection: return "SSL connection failed";
  6505. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  6506. case Error::SSLServerVerification: return "SSL server verification failed";
  6507. case Error::SSLServerHostnameVerification:
  6508. return "SSL server hostname verification failed";
  6509. case Error::UnsupportedMultipartBoundaryChars:
  6510. return "Unsupported HTTP multipart boundary characters";
  6511. case Error::Compression: return "Compression failed";
  6512. case Error::ConnectionTimeout: return "Connection timed out";
  6513. case Error::ProxyConnection: return "Proxy connection failed";
  6514. case Error::ConnectionClosed: return "Connection closed by server";
  6515. case Error::Timeout: return "Read timeout";
  6516. case Error::ResourceExhaustion: return "Resource exhaustion";
  6517. case Error::TooManyFormDataFiles: return "Too many form data files";
  6518. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  6519. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  6520. case Error::ExceedMaxSocketDescriptorCount:
  6521. return "Exceeded maximum socket descriptor count";
  6522. case Error::InvalidRequestLine: return "Invalid request line";
  6523. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  6524. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  6525. case Error::InvalidHeaders: return "Invalid headers";
  6526. case Error::MultipartParsing: return "Multipart parsing failed";
  6527. case Error::OpenFile: return "Failed to open file";
  6528. case Error::Listen: return "Failed to listen on socket";
  6529. case Error::GetSockName: return "Failed to get socket name";
  6530. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  6531. case Error::HTTPParsing: return "HTTP parsing failed";
  6532. case Error::InvalidRangeHeader: return "Invalid Range header";
  6533. default: break;
  6534. }
  6535. return "Invalid";
  6536. }
  6537. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  6538. os << to_string(obj);
  6539. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  6540. return os;
  6541. }
  6542. inline std::string hosted_at(const std::string &hostname) {
  6543. std::vector<std::string> addrs;
  6544. hosted_at(hostname, addrs);
  6545. if (addrs.empty()) { return std::string(); }
  6546. return addrs[0];
  6547. }
  6548. inline void hosted_at(const std::string &hostname,
  6549. std::vector<std::string> &addrs) {
  6550. struct addrinfo hints;
  6551. struct addrinfo *result;
  6552. memset(&hints, 0, sizeof(struct addrinfo));
  6553. hints.ai_family = AF_UNSPEC;
  6554. hints.ai_socktype = SOCK_STREAM;
  6555. hints.ai_protocol = 0;
  6556. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  6557. &result, 0)) {
  6558. #if defined __linux__ && !defined __ANDROID__
  6559. res_init();
  6560. #endif
  6561. return;
  6562. }
  6563. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6564. for (auto rp = result; rp; rp = rp->ai_next) {
  6565. const auto &addr =
  6566. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  6567. std::string ip;
  6568. auto dummy = -1;
  6569. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  6570. dummy)) {
  6571. addrs.emplace_back(std::move(ip));
  6572. }
  6573. }
  6574. }
  6575. inline std::string encode_uri_component(const std::string &value) {
  6576. std::ostringstream escaped;
  6577. escaped.fill('0');
  6578. escaped << std::hex;
  6579. for (auto c : value) {
  6580. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6581. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6582. c == ')') {
  6583. escaped << c;
  6584. } else {
  6585. escaped << std::uppercase;
  6586. escaped << '%' << std::setw(2)
  6587. << static_cast<int>(static_cast<unsigned char>(c));
  6588. escaped << std::nouppercase;
  6589. }
  6590. }
  6591. return escaped.str();
  6592. }
  6593. inline std::string encode_uri(const std::string &value) {
  6594. std::ostringstream escaped;
  6595. escaped.fill('0');
  6596. escaped << std::hex;
  6597. for (auto c : value) {
  6598. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6599. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6600. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  6601. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  6602. escaped << c;
  6603. } else {
  6604. escaped << std::uppercase;
  6605. escaped << '%' << std::setw(2)
  6606. << static_cast<int>(static_cast<unsigned char>(c));
  6607. escaped << std::nouppercase;
  6608. }
  6609. }
  6610. return escaped.str();
  6611. }
  6612. inline std::string decode_uri_component(const std::string &value) {
  6613. std::string result;
  6614. for (size_t i = 0; i < value.size(); i++) {
  6615. if (value[i] == '%' && i + 2 < value.size()) {
  6616. auto val = 0;
  6617. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6618. result += static_cast<char>(val);
  6619. i += 2;
  6620. } else {
  6621. result += value[i];
  6622. }
  6623. } else {
  6624. result += value[i];
  6625. }
  6626. }
  6627. return result;
  6628. }
  6629. inline std::string decode_uri(const std::string &value) {
  6630. std::string result;
  6631. for (size_t i = 0; i < value.size(); i++) {
  6632. if (value[i] == '%' && i + 2 < value.size()) {
  6633. auto val = 0;
  6634. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6635. result += static_cast<char>(val);
  6636. i += 2;
  6637. } else {
  6638. result += value[i];
  6639. }
  6640. } else {
  6641. result += value[i];
  6642. }
  6643. }
  6644. return result;
  6645. }
  6646. inline std::string encode_path_component(const std::string &component) {
  6647. std::string result;
  6648. result.reserve(component.size() * 3);
  6649. for (size_t i = 0; i < component.size(); i++) {
  6650. auto c = static_cast<unsigned char>(component[i]);
  6651. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  6652. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6653. result += static_cast<char>(c);
  6654. }
  6655. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  6656. // "," / ";" / "="
  6657. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  6658. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  6659. c == '=') {
  6660. result += static_cast<char>(c);
  6661. }
  6662. // Colon is allowed in path segments except first segment
  6663. else if (c == ':') {
  6664. result += static_cast<char>(c);
  6665. }
  6666. // @ is allowed in path
  6667. else if (c == '@') {
  6668. result += static_cast<char>(c);
  6669. } else {
  6670. result += '%';
  6671. char hex[3];
  6672. snprintf(hex, sizeof(hex), "%02X", c);
  6673. result.append(hex, 2);
  6674. }
  6675. }
  6676. return result;
  6677. }
  6678. inline std::string decode_path_component(const std::string &component) {
  6679. std::string result;
  6680. result.reserve(component.size());
  6681. for (size_t i = 0; i < component.size(); i++) {
  6682. if (component[i] == '%' && i + 1 < component.size()) {
  6683. if (component[i + 1] == 'u') {
  6684. // Unicode %uXXXX encoding
  6685. auto val = 0;
  6686. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  6687. // 4 digits Unicode codes
  6688. char buff[4];
  6689. size_t len = detail::to_utf8(val, buff);
  6690. if (len > 0) { result.append(buff, len); }
  6691. i += 5; // 'u0000'
  6692. } else {
  6693. result += component[i];
  6694. }
  6695. } else {
  6696. // Standard %XX encoding
  6697. auto val = 0;
  6698. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  6699. // 2 digits hex codes
  6700. result += static_cast<char>(val);
  6701. i += 2; // 'XX'
  6702. } else {
  6703. result += component[i];
  6704. }
  6705. }
  6706. } else {
  6707. result += component[i];
  6708. }
  6709. }
  6710. return result;
  6711. }
  6712. inline std::string encode_query_component(const std::string &component,
  6713. bool space_as_plus) {
  6714. std::string result;
  6715. result.reserve(component.size() * 3);
  6716. for (size_t i = 0; i < component.size(); i++) {
  6717. auto c = static_cast<unsigned char>(component[i]);
  6718. // Unreserved characters per RFC 3986
  6719. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6720. result += static_cast<char>(c);
  6721. }
  6722. // Space handling
  6723. else if (c == ' ') {
  6724. if (space_as_plus) {
  6725. result += '+';
  6726. } else {
  6727. result += "%20";
  6728. }
  6729. }
  6730. // Plus sign handling
  6731. else if (c == '+') {
  6732. if (space_as_plus) {
  6733. result += "%2B";
  6734. } else {
  6735. result += static_cast<char>(c);
  6736. }
  6737. }
  6738. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  6739. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  6740. c == '*' || c == ',' || c == ';') {
  6741. result += static_cast<char>(c);
  6742. }
  6743. // Colon and @ are allowed in query
  6744. else if (c == ':' || c == '@') {
  6745. result += static_cast<char>(c);
  6746. }
  6747. // Forward slash is allowed in query values
  6748. else if (c == '/') {
  6749. result += static_cast<char>(c);
  6750. }
  6751. // Question mark is allowed in query values (after first ?)
  6752. else if (c == '?') {
  6753. result += static_cast<char>(c);
  6754. } else {
  6755. result += '%';
  6756. char hex[3];
  6757. snprintf(hex, sizeof(hex), "%02X", c);
  6758. result.append(hex, 2);
  6759. }
  6760. }
  6761. return result;
  6762. }
  6763. inline std::string decode_query_component(const std::string &component,
  6764. bool plus_as_space) {
  6765. std::string result;
  6766. result.reserve(component.size());
  6767. for (size_t i = 0; i < component.size(); i++) {
  6768. if (component[i] == '%' && i + 2 < component.size()) {
  6769. std::string hex = component.substr(i + 1, 2);
  6770. char *end;
  6771. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  6772. if (end == hex.c_str() + 2) {
  6773. result += static_cast<char>(value);
  6774. i += 2;
  6775. } else {
  6776. result += component[i];
  6777. }
  6778. } else if (component[i] == '+' && plus_as_space) {
  6779. result += ' '; // + becomes space in form-urlencoded
  6780. } else {
  6781. result += component[i];
  6782. }
  6783. }
  6784. return result;
  6785. }
  6786. inline std::string append_query_params(const std::string &path,
  6787. const Params &params) {
  6788. std::string path_with_query = path;
  6789. thread_local const std::regex re("[^?]+\\?.*");
  6790. auto delm = std::regex_match(path, re) ? '&' : '?';
  6791. path_with_query += delm + detail::params_to_query_str(params);
  6792. return path_with_query;
  6793. }
  6794. // Header utilities
  6795. inline std::pair<std::string, std::string>
  6796. make_range_header(const Ranges &ranges) {
  6797. std::string field = "bytes=";
  6798. auto i = 0;
  6799. for (const auto &r : ranges) {
  6800. if (i != 0) { field += ", "; }
  6801. if (r.first != -1) { field += std::to_string(r.first); }
  6802. field += '-';
  6803. if (r.second != -1) { field += std::to_string(r.second); }
  6804. i++;
  6805. }
  6806. return std::make_pair("Range", std::move(field));
  6807. }
  6808. inline std::pair<std::string, std::string>
  6809. make_basic_authentication_header(const std::string &username,
  6810. const std::string &password, bool is_proxy) {
  6811. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  6812. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6813. return std::make_pair(key, std::move(field));
  6814. }
  6815. inline std::pair<std::string, std::string>
  6816. make_bearer_token_authentication_header(const std::string &token,
  6817. bool is_proxy = false) {
  6818. auto field = "Bearer " + token;
  6819. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6820. return std::make_pair(key, std::move(field));
  6821. }
  6822. // Request implementation
  6823. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  6824. size_t id) const {
  6825. return detail::get_header_value_u64(headers, key, def, id);
  6826. }
  6827. inline bool Request::has_header(const std::string &key) const {
  6828. return detail::has_header(headers, key);
  6829. }
  6830. inline std::string Request::get_header_value(const std::string &key,
  6831. const char *def, size_t id) const {
  6832. return detail::get_header_value(headers, key, def, id);
  6833. }
  6834. inline size_t Request::get_header_value_count(const std::string &key) const {
  6835. auto r = headers.equal_range(key);
  6836. return static_cast<size_t>(std::distance(r.first, r.second));
  6837. }
  6838. inline void Request::set_header(const std::string &key,
  6839. const std::string &val) {
  6840. if (detail::fields::is_field_name(key) &&
  6841. detail::fields::is_field_value(val)) {
  6842. headers.emplace(key, val);
  6843. }
  6844. }
  6845. inline bool Request::has_trailer(const std::string &key) const {
  6846. return trailers.find(key) != trailers.end();
  6847. }
  6848. inline std::string Request::get_trailer_value(const std::string &key,
  6849. size_t id) const {
  6850. auto rng = trailers.equal_range(key);
  6851. auto it = rng.first;
  6852. std::advance(it, static_cast<ssize_t>(id));
  6853. if (it != rng.second) { return it->second; }
  6854. return std::string();
  6855. }
  6856. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  6857. auto r = trailers.equal_range(key);
  6858. return static_cast<size_t>(std::distance(r.first, r.second));
  6859. }
  6860. inline bool Request::has_param(const std::string &key) const {
  6861. return params.find(key) != params.end();
  6862. }
  6863. inline std::string Request::get_param_value(const std::string &key,
  6864. size_t id) const {
  6865. auto rng = params.equal_range(key);
  6866. auto it = rng.first;
  6867. std::advance(it, static_cast<ssize_t>(id));
  6868. if (it != rng.second) { return it->second; }
  6869. return std::string();
  6870. }
  6871. inline size_t Request::get_param_value_count(const std::string &key) const {
  6872. auto r = params.equal_range(key);
  6873. return static_cast<size_t>(std::distance(r.first, r.second));
  6874. }
  6875. inline bool Request::is_multipart_form_data() const {
  6876. const auto &content_type = get_header_value("Content-Type");
  6877. return !content_type.rfind("multipart/form-data", 0);
  6878. }
  6879. // Multipart FormData implementation
  6880. inline std::string MultipartFormData::get_field(const std::string &key,
  6881. size_t id) const {
  6882. auto rng = fields.equal_range(key);
  6883. auto it = rng.first;
  6884. std::advance(it, static_cast<ssize_t>(id));
  6885. if (it != rng.second) { return it->second.content; }
  6886. return std::string();
  6887. }
  6888. inline std::vector<std::string>
  6889. MultipartFormData::get_fields(const std::string &key) const {
  6890. std::vector<std::string> values;
  6891. auto rng = fields.equal_range(key);
  6892. for (auto it = rng.first; it != rng.second; it++) {
  6893. values.push_back(it->second.content);
  6894. }
  6895. return values;
  6896. }
  6897. inline bool MultipartFormData::has_field(const std::string &key) const {
  6898. return fields.find(key) != fields.end();
  6899. }
  6900. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  6901. auto r = fields.equal_range(key);
  6902. return static_cast<size_t>(std::distance(r.first, r.second));
  6903. }
  6904. inline FormData MultipartFormData::get_file(const std::string &key,
  6905. size_t id) const {
  6906. auto rng = files.equal_range(key);
  6907. auto it = rng.first;
  6908. std::advance(it, static_cast<ssize_t>(id));
  6909. if (it != rng.second) { return it->second; }
  6910. return FormData();
  6911. }
  6912. inline std::vector<FormData>
  6913. MultipartFormData::get_files(const std::string &key) const {
  6914. std::vector<FormData> values;
  6915. auto rng = files.equal_range(key);
  6916. for (auto it = rng.first; it != rng.second; it++) {
  6917. values.push_back(it->second);
  6918. }
  6919. return values;
  6920. }
  6921. inline bool MultipartFormData::has_file(const std::string &key) const {
  6922. return files.find(key) != files.end();
  6923. }
  6924. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  6925. auto r = files.equal_range(key);
  6926. return static_cast<size_t>(std::distance(r.first, r.second));
  6927. }
  6928. // Response implementation
  6929. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  6930. size_t id) const {
  6931. return detail::get_header_value_u64(headers, key, def, id);
  6932. }
  6933. inline bool Response::has_header(const std::string &key) const {
  6934. return headers.find(key) != headers.end();
  6935. }
  6936. inline std::string Response::get_header_value(const std::string &key,
  6937. const char *def,
  6938. size_t id) const {
  6939. return detail::get_header_value(headers, key, def, id);
  6940. }
  6941. inline size_t Response::get_header_value_count(const std::string &key) const {
  6942. auto r = headers.equal_range(key);
  6943. return static_cast<size_t>(std::distance(r.first, r.second));
  6944. }
  6945. inline void Response::set_header(const std::string &key,
  6946. const std::string &val) {
  6947. if (detail::fields::is_field_name(key) &&
  6948. detail::fields::is_field_value(val)) {
  6949. headers.emplace(key, val);
  6950. }
  6951. }
  6952. inline bool Response::has_trailer(const std::string &key) const {
  6953. return trailers.find(key) != trailers.end();
  6954. }
  6955. inline std::string Response::get_trailer_value(const std::string &key,
  6956. size_t id) const {
  6957. auto rng = trailers.equal_range(key);
  6958. auto it = rng.first;
  6959. std::advance(it, static_cast<ssize_t>(id));
  6960. if (it != rng.second) { return it->second; }
  6961. return std::string();
  6962. }
  6963. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  6964. auto r = trailers.equal_range(key);
  6965. return static_cast<size_t>(std::distance(r.first, r.second));
  6966. }
  6967. inline void Response::set_redirect(const std::string &url, int stat) {
  6968. if (detail::fields::is_field_value(url)) {
  6969. set_header("Location", url);
  6970. if (300 <= stat && stat < 400) {
  6971. this->status = stat;
  6972. } else {
  6973. this->status = StatusCode::Found_302;
  6974. }
  6975. }
  6976. }
  6977. inline void Response::set_content(const char *s, size_t n,
  6978. const std::string &content_type) {
  6979. body.assign(s, n);
  6980. auto rng = headers.equal_range("Content-Type");
  6981. headers.erase(rng.first, rng.second);
  6982. set_header("Content-Type", content_type);
  6983. }
  6984. inline void Response::set_content(const std::string &s,
  6985. const std::string &content_type) {
  6986. set_content(s.data(), s.size(), content_type);
  6987. }
  6988. inline void Response::set_content(std::string &&s,
  6989. const std::string &content_type) {
  6990. body = std::move(s);
  6991. auto rng = headers.equal_range("Content-Type");
  6992. headers.erase(rng.first, rng.second);
  6993. set_header("Content-Type", content_type);
  6994. }
  6995. inline void Response::set_content_provider(
  6996. size_t in_length, const std::string &content_type, ContentProvider provider,
  6997. ContentProviderResourceReleaser resource_releaser) {
  6998. set_header("Content-Type", content_type);
  6999. content_length_ = in_length;
  7000. if (in_length > 0) { content_provider_ = std::move(provider); }
  7001. content_provider_resource_releaser_ = std::move(resource_releaser);
  7002. is_chunked_content_provider_ = false;
  7003. }
  7004. inline void Response::set_content_provider(
  7005. const std::string &content_type, ContentProviderWithoutLength provider,
  7006. ContentProviderResourceReleaser resource_releaser) {
  7007. set_header("Content-Type", content_type);
  7008. content_length_ = 0;
  7009. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  7010. content_provider_resource_releaser_ = std::move(resource_releaser);
  7011. is_chunked_content_provider_ = false;
  7012. }
  7013. inline void Response::set_chunked_content_provider(
  7014. const std::string &content_type, ContentProviderWithoutLength provider,
  7015. ContentProviderResourceReleaser resource_releaser) {
  7016. set_header("Content-Type", content_type);
  7017. content_length_ = 0;
  7018. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  7019. content_provider_resource_releaser_ = std::move(resource_releaser);
  7020. is_chunked_content_provider_ = true;
  7021. }
  7022. inline void Response::set_file_content(const std::string &path,
  7023. const std::string &content_type) {
  7024. file_content_path_ = path;
  7025. file_content_content_type_ = content_type;
  7026. }
  7027. inline void Response::set_file_content(const std::string &path) {
  7028. file_content_path_ = path;
  7029. }
  7030. // Result implementation
  7031. inline size_t Result::get_request_header_value_u64(const std::string &key,
  7032. size_t def,
  7033. size_t id) const {
  7034. return detail::get_header_value_u64(request_headers_, key, def, id);
  7035. }
  7036. inline bool Result::has_request_header(const std::string &key) const {
  7037. return request_headers_.find(key) != request_headers_.end();
  7038. }
  7039. inline std::string Result::get_request_header_value(const std::string &key,
  7040. const char *def,
  7041. size_t id) const {
  7042. return detail::get_header_value(request_headers_, key, def, id);
  7043. }
  7044. inline size_t
  7045. Result::get_request_header_value_count(const std::string &key) const {
  7046. auto r = request_headers_.equal_range(key);
  7047. return static_cast<size_t>(std::distance(r.first, r.second));
  7048. }
  7049. // Stream implementation
  7050. inline ssize_t Stream::write(const char *ptr) {
  7051. return write(ptr, strlen(ptr));
  7052. }
  7053. inline ssize_t Stream::write(const std::string &s) {
  7054. return write(s.data(), s.size());
  7055. }
  7056. // BodyReader implementation
  7057. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  7058. if (!stream) {
  7059. last_error = Error::Connection;
  7060. return -1;
  7061. }
  7062. if (eof) { return 0; }
  7063. if (!chunked) {
  7064. // Content-Length based reading
  7065. if (bytes_read >= content_length) {
  7066. eof = true;
  7067. return 0;
  7068. }
  7069. auto remaining = content_length - bytes_read;
  7070. auto to_read = (std::min)(len, remaining);
  7071. auto n = stream->read(buf, to_read);
  7072. if (n < 0) {
  7073. last_error = stream->get_error();
  7074. if (last_error == Error::Success) { last_error = Error::Read; }
  7075. eof = true;
  7076. return n;
  7077. }
  7078. if (n == 0) {
  7079. // Unexpected EOF before content_length
  7080. last_error = stream->get_error();
  7081. if (last_error == Error::Success) { last_error = Error::Read; }
  7082. eof = true;
  7083. return 0;
  7084. }
  7085. bytes_read += static_cast<size_t>(n);
  7086. if (bytes_read >= content_length) { eof = true; }
  7087. return n;
  7088. }
  7089. // Chunked transfer encoding: delegate to shared decoder instance.
  7090. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  7091. size_t chunk_offset = 0;
  7092. size_t chunk_total = 0;
  7093. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  7094. if (n < 0) {
  7095. last_error = stream->get_error();
  7096. if (last_error == Error::Success) { last_error = Error::Read; }
  7097. eof = true;
  7098. return n;
  7099. }
  7100. if (n == 0) {
  7101. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  7102. eof = true;
  7103. return 0;
  7104. }
  7105. bytes_read += static_cast<size_t>(n);
  7106. return n;
  7107. }
  7108. // ThreadPool implementation
  7109. inline ThreadPool::ThreadPool(size_t n, size_t mqr)
  7110. : shutdown_(false), max_queued_requests_(mqr) {
  7111. threads_.reserve(n);
  7112. while (n) {
  7113. threads_.emplace_back(worker(*this));
  7114. n--;
  7115. }
  7116. }
  7117. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  7118. {
  7119. std::unique_lock<std::mutex> lock(mutex_);
  7120. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  7121. return false;
  7122. }
  7123. jobs_.push_back(std::move(fn));
  7124. }
  7125. cond_.notify_one();
  7126. return true;
  7127. }
  7128. inline void ThreadPool::shutdown() {
  7129. // Stop all worker threads...
  7130. {
  7131. std::unique_lock<std::mutex> lock(mutex_);
  7132. shutdown_ = true;
  7133. }
  7134. cond_.notify_all();
  7135. // Join...
  7136. for (auto &t : threads_) {
  7137. t.join();
  7138. }
  7139. }
  7140. inline ThreadPool::worker::worker(ThreadPool &pool) : pool_(pool) {}
  7141. inline void ThreadPool::worker::operator()() {
  7142. for (;;) {
  7143. std::function<void()> fn;
  7144. {
  7145. std::unique_lock<std::mutex> lock(pool_.mutex_);
  7146. pool_.cond_.wait(lock,
  7147. [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  7148. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  7149. fn = pool_.jobs_.front();
  7150. pool_.jobs_.pop_front();
  7151. }
  7152. assert(true == static_cast<bool>(fn));
  7153. fn();
  7154. }
  7155. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  7156. !defined(LIBRESSL_VERSION_NUMBER)
  7157. OPENSSL_thread_stop();
  7158. #endif
  7159. }
  7160. /*
  7161. * Group 1 (continued): detail namespace - Stream implementations
  7162. */
  7163. namespace detail {
  7164. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  7165. time_t timeout_sec, time_t timeout_usec,
  7166. time_t &actual_timeout_sec,
  7167. time_t &actual_timeout_usec) {
  7168. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  7169. auto actual_timeout_msec =
  7170. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  7171. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  7172. actual_timeout_sec = actual_timeout_msec / 1000;
  7173. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  7174. }
  7175. // Socket stream implementation
  7176. inline SocketStream::SocketStream(
  7177. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  7178. time_t write_timeout_sec, time_t write_timeout_usec,
  7179. time_t max_timeout_msec,
  7180. std::chrono::time_point<std::chrono::steady_clock> start_time)
  7181. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  7182. read_timeout_usec_(read_timeout_usec),
  7183. write_timeout_sec_(write_timeout_sec),
  7184. write_timeout_usec_(write_timeout_usec),
  7185. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  7186. read_buff_(read_buff_size_, 0) {}
  7187. inline SocketStream::~SocketStream() = default;
  7188. inline bool SocketStream::is_readable() const {
  7189. return read_buff_off_ < read_buff_content_size_;
  7190. }
  7191. inline bool SocketStream::wait_readable() const {
  7192. if (max_timeout_msec_ <= 0) {
  7193. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  7194. }
  7195. time_t read_timeout_sec;
  7196. time_t read_timeout_usec;
  7197. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  7198. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  7199. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  7200. }
  7201. inline bool SocketStream::wait_writable() const {
  7202. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  7203. is_socket_alive(sock_);
  7204. }
  7205. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  7206. #ifdef _WIN32
  7207. size =
  7208. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7209. #else
  7210. size = (std::min)(size,
  7211. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  7212. #endif
  7213. if (read_buff_off_ < read_buff_content_size_) {
  7214. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  7215. if (size <= remaining_size) {
  7216. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  7217. read_buff_off_ += size;
  7218. return static_cast<ssize_t>(size);
  7219. } else {
  7220. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  7221. read_buff_off_ += remaining_size;
  7222. return static_cast<ssize_t>(remaining_size);
  7223. }
  7224. }
  7225. if (!wait_readable()) {
  7226. error_ = Error::Timeout;
  7227. return -1;
  7228. }
  7229. read_buff_off_ = 0;
  7230. read_buff_content_size_ = 0;
  7231. if (size < read_buff_size_) {
  7232. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  7233. CPPHTTPLIB_RECV_FLAGS);
  7234. if (n <= 0) {
  7235. if (n == 0) {
  7236. error_ = Error::ConnectionClosed;
  7237. } else {
  7238. error_ = Error::Read;
  7239. }
  7240. return n;
  7241. } else if (n <= static_cast<ssize_t>(size)) {
  7242. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  7243. return n;
  7244. } else {
  7245. memcpy(ptr, read_buff_.data(), size);
  7246. read_buff_off_ = size;
  7247. read_buff_content_size_ = static_cast<size_t>(n);
  7248. return static_cast<ssize_t>(size);
  7249. }
  7250. } else {
  7251. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  7252. if (n <= 0) {
  7253. if (n == 0) {
  7254. error_ = Error::ConnectionClosed;
  7255. } else {
  7256. error_ = Error::Read;
  7257. }
  7258. }
  7259. return n;
  7260. }
  7261. }
  7262. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  7263. if (!wait_writable()) { return -1; }
  7264. #if defined(_WIN32) && !defined(_WIN64)
  7265. size =
  7266. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  7267. #endif
  7268. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  7269. }
  7270. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  7271. int &port) const {
  7272. return detail::get_remote_ip_and_port(sock_, ip, port);
  7273. }
  7274. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  7275. int &port) const {
  7276. return detail::get_local_ip_and_port(sock_, ip, port);
  7277. }
  7278. inline socket_t SocketStream::socket() const { return sock_; }
  7279. inline time_t SocketStream::duration() const {
  7280. return std::chrono::duration_cast<std::chrono::milliseconds>(
  7281. std::chrono::steady_clock::now() - start_time_)
  7282. .count();
  7283. }
  7284. // Buffer stream implementation
  7285. inline bool BufferStream::is_readable() const { return true; }
  7286. inline bool BufferStream::wait_readable() const { return true; }
  7287. inline bool BufferStream::wait_writable() const { return true; }
  7288. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  7289. #if defined(_MSC_VER) && _MSC_VER < 1910
  7290. auto len_read = buffer._Copy_s(ptr, size, size, position);
  7291. #else
  7292. auto len_read = buffer.copy(ptr, size, position);
  7293. #endif
  7294. position += static_cast<size_t>(len_read);
  7295. return static_cast<ssize_t>(len_read);
  7296. }
  7297. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  7298. buffer.append(ptr, size);
  7299. return static_cast<ssize_t>(size);
  7300. }
  7301. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  7302. int & /*port*/) const {}
  7303. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  7304. int & /*port*/) const {}
  7305. inline socket_t BufferStream::socket() const { return 0; }
  7306. inline time_t BufferStream::duration() const { return 0; }
  7307. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  7308. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  7309. : MatcherBase(pattern) {
  7310. constexpr const char marker[] = "/:";
  7311. // One past the last ending position of a path param substring
  7312. std::size_t last_param_end = 0;
  7313. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7314. // Needed to ensure that parameter names are unique during matcher
  7315. // construction
  7316. // If exceptions are disabled, only last duplicate path
  7317. // parameter will be set
  7318. std::unordered_set<std::string> param_name_set;
  7319. #endif
  7320. while (true) {
  7321. const auto marker_pos = pattern.find(
  7322. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  7323. if (marker_pos == std::string::npos) { break; }
  7324. static_fragments_.push_back(
  7325. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  7326. const auto param_name_start = marker_pos + str_len(marker);
  7327. auto sep_pos = pattern.find(separator, param_name_start);
  7328. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  7329. auto param_name =
  7330. pattern.substr(param_name_start, sep_pos - param_name_start);
  7331. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7332. if (param_name_set.find(param_name) != param_name_set.cend()) {
  7333. std::string msg = "Encountered path parameter '" + param_name +
  7334. "' multiple times in route pattern '" + pattern + "'.";
  7335. throw std::invalid_argument(msg);
  7336. }
  7337. #endif
  7338. param_names_.push_back(std::move(param_name));
  7339. last_param_end = sep_pos + 1;
  7340. }
  7341. if (last_param_end < pattern.length()) {
  7342. static_fragments_.push_back(pattern.substr(last_param_end));
  7343. }
  7344. }
  7345. inline bool PathParamsMatcher::match(Request &request) const {
  7346. request.matches = std::smatch();
  7347. request.path_params.clear();
  7348. request.path_params.reserve(param_names_.size());
  7349. // One past the position at which the path matched the pattern last time
  7350. std::size_t starting_pos = 0;
  7351. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  7352. const auto &fragment = static_fragments_[i];
  7353. if (starting_pos + fragment.length() > request.path.length()) {
  7354. return false;
  7355. }
  7356. // Avoid unnecessary allocation by using strncmp instead of substr +
  7357. // comparison
  7358. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  7359. fragment.length()) != 0) {
  7360. return false;
  7361. }
  7362. starting_pos += fragment.length();
  7363. // Should only happen when we have a static fragment after a param
  7364. // Example: '/users/:id/subscriptions'
  7365. // The 'subscriptions' fragment here does not have a corresponding param
  7366. if (i >= param_names_.size()) { continue; }
  7367. auto sep_pos = request.path.find(separator, starting_pos);
  7368. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  7369. const auto &param_name = param_names_[i];
  7370. request.path_params.emplace(
  7371. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  7372. // Mark everything up to '/' as matched
  7373. starting_pos = sep_pos + 1;
  7374. }
  7375. // Returns false if the path is longer than the pattern
  7376. return starting_pos >= request.path.length();
  7377. }
  7378. inline bool RegexMatcher::match(Request &request) const {
  7379. request.path_params.clear();
  7380. return std::regex_match(request.path, request.matches, regex_);
  7381. }
  7382. // Enclose IPv6 address in brackets if needed
  7383. inline std::string prepare_host_string(const std::string &host) {
  7384. // Enclose IPv6 address in brackets (but not if already enclosed)
  7385. if (host.find(':') == std::string::npos ||
  7386. (!host.empty() && host[0] == '[')) {
  7387. // IPv4, hostname, or already bracketed IPv6
  7388. return host;
  7389. } else {
  7390. // IPv6 address without brackets
  7391. return "[" + host + "]";
  7392. }
  7393. }
  7394. inline std::string make_host_and_port_string(const std::string &host, int port,
  7395. bool is_ssl) {
  7396. auto result = prepare_host_string(host);
  7397. // Append port if not default
  7398. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  7399. ; // do nothing
  7400. } else {
  7401. result += ":" + std::to_string(port);
  7402. }
  7403. return result;
  7404. }
  7405. // Create "host:port" string always including port number (for CONNECT method)
  7406. inline std::string
  7407. make_host_and_port_string_always_port(const std::string &host, int port) {
  7408. return prepare_host_string(host) + ":" + std::to_string(port);
  7409. }
  7410. template <typename T>
  7411. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  7412. T header_writer, Error &error) {
  7413. for (const auto &h : headers) {
  7414. if (!detail::fields::is_field_name(h.first) ||
  7415. !detail::fields::is_field_value(h.second)) {
  7416. error = Error::InvalidHeaders;
  7417. return false;
  7418. }
  7419. }
  7420. if (header_writer(strm, headers) <= 0) {
  7421. error = Error::Write;
  7422. return false;
  7423. }
  7424. return true;
  7425. }
  7426. } // namespace detail
  7427. /*
  7428. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  7429. */
  7430. #ifdef CPPHTTPLIB_SSL_ENABLED
  7431. namespace detail {
  7432. // SSL socket stream implementation
  7433. inline SSLSocketStream::SSLSocketStream(
  7434. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7435. time_t read_timeout_usec, time_t write_timeout_sec,
  7436. time_t write_timeout_usec, time_t max_timeout_msec,
  7437. std::chrono::time_point<std::chrono::steady_clock> start_time)
  7438. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  7439. read_timeout_usec_(read_timeout_usec),
  7440. write_timeout_sec_(write_timeout_sec),
  7441. write_timeout_usec_(write_timeout_usec),
  7442. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  7443. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7444. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  7445. // Note: create_session() also clears this, but SSLClient currently
  7446. // uses ssl_new() which does not. Until full TLS API migration is complete,
  7447. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  7448. // SSL session was created.
  7449. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  7450. #endif
  7451. }
  7452. inline SSLSocketStream::~SSLSocketStream() = default;
  7453. inline bool SSLSocketStream::is_readable() const {
  7454. return tls::pending(session_) > 0;
  7455. }
  7456. inline bool SSLSocketStream::wait_readable() const {
  7457. if (max_timeout_msec_ <= 0) {
  7458. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  7459. }
  7460. time_t read_timeout_sec;
  7461. time_t read_timeout_usec;
  7462. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  7463. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  7464. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  7465. }
  7466. inline bool SSLSocketStream::wait_writable() const {
  7467. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  7468. is_socket_alive(sock_) && !tls::is_peer_closed(session_, sock_);
  7469. }
  7470. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  7471. if (tls::pending(session_) > 0) {
  7472. tls::TlsError err;
  7473. auto ret = tls::read(session_, ptr, size, err);
  7474. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  7475. error_ = Error::ConnectionClosed;
  7476. }
  7477. return ret;
  7478. } else if (wait_readable()) {
  7479. tls::TlsError err;
  7480. auto ret = tls::read(session_, ptr, size, err);
  7481. if (ret < 0) {
  7482. auto n = 1000;
  7483. #ifdef _WIN32
  7484. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  7485. (err.code == tls::ErrorCode::SyscallError &&
  7486. WSAGetLastError() == WSAETIMEDOUT))) {
  7487. #else
  7488. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  7489. #endif
  7490. if (tls::pending(session_) > 0) {
  7491. return tls::read(session_, ptr, size, err);
  7492. } else if (wait_readable()) {
  7493. std::this_thread::sleep_for(std::chrono::microseconds{10});
  7494. ret = tls::read(session_, ptr, size, err);
  7495. if (ret >= 0) { return ret; }
  7496. } else {
  7497. break;
  7498. }
  7499. }
  7500. assert(ret < 0);
  7501. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  7502. error_ = Error::ConnectionClosed;
  7503. }
  7504. return ret;
  7505. } else {
  7506. error_ = Error::Timeout;
  7507. return -1;
  7508. }
  7509. }
  7510. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  7511. if (wait_writable()) {
  7512. auto handle_size =
  7513. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  7514. tls::TlsError err;
  7515. auto ret = tls::write(session_, ptr, handle_size, err);
  7516. if (ret < 0) {
  7517. auto n = 1000;
  7518. #ifdef _WIN32
  7519. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  7520. (err.code == tls::ErrorCode::SyscallError &&
  7521. WSAGetLastError() == WSAETIMEDOUT))) {
  7522. #else
  7523. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  7524. #endif
  7525. if (wait_writable()) {
  7526. std::this_thread::sleep_for(std::chrono::microseconds{10});
  7527. ret = tls::write(session_, ptr, handle_size, err);
  7528. if (ret >= 0) { return ret; }
  7529. } else {
  7530. break;
  7531. }
  7532. }
  7533. assert(ret < 0);
  7534. }
  7535. return ret;
  7536. }
  7537. return -1;
  7538. }
  7539. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  7540. int &port) const {
  7541. detail::get_remote_ip_and_port(sock_, ip, port);
  7542. }
  7543. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  7544. int &port) const {
  7545. detail::get_local_ip_and_port(sock_, ip, port);
  7546. }
  7547. inline socket_t SSLSocketStream::socket() const { return sock_; }
  7548. inline time_t SSLSocketStream::duration() const {
  7549. return std::chrono::duration_cast<std::chrono::milliseconds>(
  7550. std::chrono::steady_clock::now() - start_time_)
  7551. .count();
  7552. }
  7553. } // namespace detail
  7554. #endif // CPPHTTPLIB_SSL_ENABLED
  7555. /*
  7556. * Group 4: Server implementation
  7557. */
  7558. // HTTP server implementation
  7559. inline Server::Server()
  7560. : new_task_queue(
  7561. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  7562. #ifndef _WIN32
  7563. signal(SIGPIPE, SIG_IGN);
  7564. #endif
  7565. }
  7566. inline Server::~Server() = default;
  7567. inline std::unique_ptr<detail::MatcherBase>
  7568. Server::make_matcher(const std::string &pattern) {
  7569. if (pattern.find("/:") != std::string::npos) {
  7570. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  7571. } else {
  7572. return detail::make_unique<detail::RegexMatcher>(pattern);
  7573. }
  7574. }
  7575. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  7576. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7577. return *this;
  7578. }
  7579. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  7580. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7581. return *this;
  7582. }
  7583. inline Server &Server::Post(const std::string &pattern,
  7584. HandlerWithContentReader handler) {
  7585. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7586. std::move(handler));
  7587. return *this;
  7588. }
  7589. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  7590. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7591. return *this;
  7592. }
  7593. inline Server &Server::Put(const std::string &pattern,
  7594. HandlerWithContentReader handler) {
  7595. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7596. std::move(handler));
  7597. return *this;
  7598. }
  7599. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  7600. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7601. return *this;
  7602. }
  7603. inline Server &Server::Patch(const std::string &pattern,
  7604. HandlerWithContentReader handler) {
  7605. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7606. std::move(handler));
  7607. return *this;
  7608. }
  7609. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  7610. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7611. return *this;
  7612. }
  7613. inline Server &Server::Delete(const std::string &pattern,
  7614. HandlerWithContentReader handler) {
  7615. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7616. std::move(handler));
  7617. return *this;
  7618. }
  7619. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  7620. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7621. return *this;
  7622. }
  7623. inline bool Server::set_base_dir(const std::string &dir,
  7624. const std::string &mount_point) {
  7625. return set_mount_point(mount_point, dir);
  7626. }
  7627. inline bool Server::set_mount_point(const std::string &mount_point,
  7628. const std::string &dir, Headers headers) {
  7629. detail::FileStat stat(dir);
  7630. if (stat.is_dir()) {
  7631. std::string mnt = !mount_point.empty() ? mount_point : "/";
  7632. if (!mnt.empty() && mnt[0] == '/') {
  7633. base_dirs_.push_back({std::move(mnt), dir, std::move(headers)});
  7634. return true;
  7635. }
  7636. }
  7637. return false;
  7638. }
  7639. inline bool Server::remove_mount_point(const std::string &mount_point) {
  7640. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  7641. if (it->mount_point == mount_point) {
  7642. base_dirs_.erase(it);
  7643. return true;
  7644. }
  7645. }
  7646. return false;
  7647. }
  7648. inline Server &
  7649. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  7650. const std::string &mime) {
  7651. file_extension_and_mimetype_map_[ext] = mime;
  7652. return *this;
  7653. }
  7654. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  7655. default_file_mimetype_ = mime;
  7656. return *this;
  7657. }
  7658. inline Server &Server::set_file_request_handler(Handler handler) {
  7659. file_request_handler_ = std::move(handler);
  7660. return *this;
  7661. }
  7662. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  7663. std::true_type) {
  7664. error_handler_ = std::move(handler);
  7665. return *this;
  7666. }
  7667. inline Server &Server::set_error_handler_core(Handler handler,
  7668. std::false_type) {
  7669. error_handler_ = [handler](const Request &req, Response &res) {
  7670. handler(req, res);
  7671. return HandlerResponse::Handled;
  7672. };
  7673. return *this;
  7674. }
  7675. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  7676. exception_handler_ = std::move(handler);
  7677. return *this;
  7678. }
  7679. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  7680. pre_routing_handler_ = std::move(handler);
  7681. return *this;
  7682. }
  7683. inline Server &Server::set_post_routing_handler(Handler handler) {
  7684. post_routing_handler_ = std::move(handler);
  7685. return *this;
  7686. }
  7687. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  7688. pre_request_handler_ = std::move(handler);
  7689. return *this;
  7690. }
  7691. inline Server &Server::set_logger(Logger logger) {
  7692. logger_ = std::move(logger);
  7693. return *this;
  7694. }
  7695. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  7696. error_logger_ = std::move(error_logger);
  7697. return *this;
  7698. }
  7699. inline Server &Server::set_pre_compression_logger(Logger logger) {
  7700. pre_compression_logger_ = std::move(logger);
  7701. return *this;
  7702. }
  7703. inline Server &
  7704. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  7705. expect_100_continue_handler_ = std::move(handler);
  7706. return *this;
  7707. }
  7708. inline Server &Server::set_address_family(int family) {
  7709. address_family_ = family;
  7710. return *this;
  7711. }
  7712. inline Server &Server::set_tcp_nodelay(bool on) {
  7713. tcp_nodelay_ = on;
  7714. return *this;
  7715. }
  7716. inline Server &Server::set_ipv6_v6only(bool on) {
  7717. ipv6_v6only_ = on;
  7718. return *this;
  7719. }
  7720. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  7721. socket_options_ = std::move(socket_options);
  7722. return *this;
  7723. }
  7724. inline Server &Server::set_default_headers(Headers headers) {
  7725. default_headers_ = std::move(headers);
  7726. return *this;
  7727. }
  7728. inline Server &Server::set_header_writer(
  7729. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7730. header_writer_ = writer;
  7731. return *this;
  7732. }
  7733. inline Server &
  7734. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  7735. trusted_proxies_ = proxies;
  7736. return *this;
  7737. }
  7738. inline Server &Server::set_keep_alive_max_count(size_t count) {
  7739. keep_alive_max_count_ = count;
  7740. return *this;
  7741. }
  7742. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  7743. keep_alive_timeout_sec_ = sec;
  7744. return *this;
  7745. }
  7746. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  7747. read_timeout_sec_ = sec;
  7748. read_timeout_usec_ = usec;
  7749. return *this;
  7750. }
  7751. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  7752. write_timeout_sec_ = sec;
  7753. write_timeout_usec_ = usec;
  7754. return *this;
  7755. }
  7756. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  7757. idle_interval_sec_ = sec;
  7758. idle_interval_usec_ = usec;
  7759. return *this;
  7760. }
  7761. inline Server &Server::set_payload_max_length(size_t length) {
  7762. payload_max_length_ = length;
  7763. return *this;
  7764. }
  7765. inline bool Server::bind_to_port(const std::string &host, int port,
  7766. int socket_flags) {
  7767. auto ret = bind_internal(host, port, socket_flags);
  7768. if (ret == -1) { is_decommissioned = true; }
  7769. return ret >= 0;
  7770. }
  7771. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  7772. auto ret = bind_internal(host, 0, socket_flags);
  7773. if (ret == -1) { is_decommissioned = true; }
  7774. return ret;
  7775. }
  7776. inline bool Server::listen_after_bind() { return listen_internal(); }
  7777. inline bool Server::listen(const std::string &host, int port,
  7778. int socket_flags) {
  7779. return bind_to_port(host, port, socket_flags) && listen_internal();
  7780. }
  7781. inline bool Server::is_running() const { return is_running_; }
  7782. inline void Server::wait_until_ready() const {
  7783. while (!is_running_ && !is_decommissioned) {
  7784. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7785. }
  7786. }
  7787. inline void Server::stop() {
  7788. if (is_running_) {
  7789. assert(svr_sock_ != INVALID_SOCKET);
  7790. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  7791. detail::shutdown_socket(sock);
  7792. detail::close_socket(sock);
  7793. }
  7794. is_decommissioned = false;
  7795. }
  7796. inline void Server::decommission() { is_decommissioned = true; }
  7797. inline bool Server::parse_request_line(const char *s, Request &req) const {
  7798. auto len = strlen(s);
  7799. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  7800. len -= 2;
  7801. {
  7802. size_t count = 0;
  7803. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  7804. switch (count) {
  7805. case 0: req.method = std::string(b, e); break;
  7806. case 1: req.target = std::string(b, e); break;
  7807. case 2: req.version = std::string(b, e); break;
  7808. default: break;
  7809. }
  7810. count++;
  7811. });
  7812. if (count != 3) { return false; }
  7813. }
  7814. thread_local const std::set<std::string> methods{
  7815. "GET", "HEAD", "POST", "PUT", "DELETE",
  7816. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7817. if (methods.find(req.method) == methods.end()) {
  7818. output_error_log(Error::InvalidHTTPMethod, &req);
  7819. return false;
  7820. }
  7821. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  7822. output_error_log(Error::InvalidHTTPVersion, &req);
  7823. return false;
  7824. }
  7825. {
  7826. // Skip URL fragment
  7827. for (size_t i = 0; i < req.target.size(); i++) {
  7828. if (req.target[i] == '#') {
  7829. req.target.erase(i);
  7830. break;
  7831. }
  7832. }
  7833. detail::divide(req.target, '?',
  7834. [&](const char *lhs_data, std::size_t lhs_size,
  7835. const char *rhs_data, std::size_t rhs_size) {
  7836. req.path =
  7837. decode_path_component(std::string(lhs_data, lhs_size));
  7838. detail::parse_query_text(rhs_data, rhs_size, req.params);
  7839. });
  7840. }
  7841. return true;
  7842. }
  7843. inline bool Server::write_response(Stream &strm, bool close_connection,
  7844. Request &req, Response &res) {
  7845. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  7846. // incorrectly to the error content.
  7847. req.ranges.clear();
  7848. return write_response_core(strm, close_connection, req, res, false);
  7849. }
  7850. inline bool Server::write_response_with_content(Stream &strm,
  7851. bool close_connection,
  7852. const Request &req,
  7853. Response &res) {
  7854. return write_response_core(strm, close_connection, req, res, true);
  7855. }
  7856. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  7857. const Request &req, Response &res,
  7858. bool need_apply_ranges) {
  7859. assert(res.status != -1);
  7860. if (400 <= res.status && error_handler_ &&
  7861. error_handler_(req, res) == HandlerResponse::Handled) {
  7862. need_apply_ranges = true;
  7863. }
  7864. std::string content_type;
  7865. std::string boundary;
  7866. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  7867. // Prepare additional headers
  7868. if (close_connection || req.get_header_value("Connection") == "close" ||
  7869. 400 <= res.status) { // Don't leave connections open after errors
  7870. res.set_header("Connection", "close");
  7871. } else {
  7872. std::string s = "timeout=";
  7873. s += std::to_string(keep_alive_timeout_sec_);
  7874. s += ", max=";
  7875. s += std::to_string(keep_alive_max_count_);
  7876. res.set_header("Keep-Alive", s);
  7877. }
  7878. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  7879. !res.has_header("Content-Type")) {
  7880. res.set_header("Content-Type", "text/plain");
  7881. }
  7882. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  7883. !res.has_header("Content-Length")) {
  7884. res.set_header("Content-Length", "0");
  7885. }
  7886. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  7887. res.set_header("Accept-Ranges", "bytes");
  7888. }
  7889. if (post_routing_handler_) { post_routing_handler_(req, res); }
  7890. // Response line and headers
  7891. {
  7892. detail::BufferStream bstrm;
  7893. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  7894. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  7895. // Flush buffer
  7896. auto &data = bstrm.get_buffer();
  7897. detail::write_data(strm, data.data(), data.size());
  7898. }
  7899. // Body
  7900. auto ret = true;
  7901. if (req.method != "HEAD") {
  7902. if (!res.body.empty()) {
  7903. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  7904. ret = false;
  7905. }
  7906. } else if (res.content_provider_) {
  7907. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  7908. res.content_provider_success_ = true;
  7909. } else {
  7910. ret = false;
  7911. }
  7912. }
  7913. }
  7914. // Log
  7915. output_log(req, res);
  7916. return ret;
  7917. }
  7918. inline bool
  7919. Server::write_content_with_provider(Stream &strm, const Request &req,
  7920. Response &res, const std::string &boundary,
  7921. const std::string &content_type) {
  7922. auto is_shutting_down = [this]() {
  7923. return this->svr_sock_ == INVALID_SOCKET;
  7924. };
  7925. if (res.content_length_ > 0) {
  7926. if (req.ranges.empty()) {
  7927. return detail::write_content(strm, res.content_provider_, 0,
  7928. res.content_length_, is_shutting_down);
  7929. } else if (req.ranges.size() == 1) {
  7930. auto offset_and_length = detail::get_range_offset_and_length(
  7931. req.ranges[0], res.content_length_);
  7932. return detail::write_content(strm, res.content_provider_,
  7933. offset_and_length.first,
  7934. offset_and_length.second, is_shutting_down);
  7935. } else {
  7936. return detail::write_multipart_ranges_data(
  7937. strm, req, res, boundary, content_type, res.content_length_,
  7938. is_shutting_down);
  7939. }
  7940. } else {
  7941. if (res.is_chunked_content_provider_) {
  7942. auto type = detail::encoding_type(req, res);
  7943. std::unique_ptr<detail::compressor> compressor;
  7944. if (type == detail::EncodingType::Gzip) {
  7945. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7946. compressor = detail::make_unique<detail::gzip_compressor>();
  7947. #endif
  7948. } else if (type == detail::EncodingType::Brotli) {
  7949. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7950. compressor = detail::make_unique<detail::brotli_compressor>();
  7951. #endif
  7952. } else if (type == detail::EncodingType::Zstd) {
  7953. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7954. compressor = detail::make_unique<detail::zstd_compressor>();
  7955. #endif
  7956. } else {
  7957. compressor = detail::make_unique<detail::nocompressor>();
  7958. }
  7959. assert(compressor != nullptr);
  7960. return detail::write_content_chunked(strm, res.content_provider_,
  7961. is_shutting_down, *compressor);
  7962. } else {
  7963. return detail::write_content_without_length(strm, res.content_provider_,
  7964. is_shutting_down);
  7965. }
  7966. }
  7967. }
  7968. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  7969. FormFields::iterator cur_field;
  7970. FormFiles::iterator cur_file;
  7971. auto is_text_field = false;
  7972. size_t count = 0;
  7973. if (read_content_core(
  7974. strm, req, res,
  7975. // Regular
  7976. [&](const char *buf, size_t n) {
  7977. // Prevent arithmetic overflow when checking sizes.
  7978. // Avoid computing (req.body.size() + n) directly because
  7979. // adding two unsigned `size_t` values can wrap around and
  7980. // produce a small result instead of indicating overflow.
  7981. // Instead, check using subtraction: ensure `n` does not
  7982. // exceed the remaining capacity `max_size() - size()`.
  7983. if (req.body.size() >= req.body.max_size() ||
  7984. n > req.body.max_size() - req.body.size()) {
  7985. return false;
  7986. }
  7987. // Limit decompressed body size to payload_max_length_ to protect
  7988. // against "zip bomb" attacks where a small compressed payload
  7989. // decompresses to a massive size.
  7990. if (payload_max_length_ > 0 &&
  7991. (req.body.size() >= payload_max_length_ ||
  7992. n > payload_max_length_ - req.body.size())) {
  7993. return false;
  7994. }
  7995. req.body.append(buf, n);
  7996. return true;
  7997. },
  7998. // Multipart FormData
  7999. [&](const FormData &file) {
  8000. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  8001. output_error_log(Error::TooManyFormDataFiles, &req);
  8002. return false;
  8003. }
  8004. if (file.filename.empty()) {
  8005. cur_field = req.form.fields.emplace(
  8006. file.name, FormField{file.name, file.content, file.headers});
  8007. is_text_field = true;
  8008. } else {
  8009. cur_file = req.form.files.emplace(file.name, file);
  8010. is_text_field = false;
  8011. }
  8012. return true;
  8013. },
  8014. [&](const char *buf, size_t n) {
  8015. if (is_text_field) {
  8016. auto &content = cur_field->second.content;
  8017. if (content.size() + n > content.max_size()) { return false; }
  8018. content.append(buf, n);
  8019. } else {
  8020. auto &content = cur_file->second.content;
  8021. if (content.size() + n > content.max_size()) { return false; }
  8022. content.append(buf, n);
  8023. }
  8024. return true;
  8025. })) {
  8026. const auto &content_type = req.get_header_value("Content-Type");
  8027. if (!content_type.find("application/x-www-form-urlencoded")) {
  8028. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  8029. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  8030. output_error_log(Error::ExceedMaxPayloadSize, &req);
  8031. return false;
  8032. }
  8033. detail::parse_query_text(req.body, req.params);
  8034. }
  8035. return true;
  8036. }
  8037. return false;
  8038. }
  8039. inline bool Server::read_content_with_content_receiver(
  8040. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  8041. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  8042. return read_content_core(strm, req, res, std::move(receiver),
  8043. std::move(multipart_header),
  8044. std::move(multipart_receiver));
  8045. }
  8046. inline bool Server::read_content_core(
  8047. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  8048. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  8049. detail::FormDataParser multipart_form_data_parser;
  8050. ContentReceiverWithProgress out;
  8051. if (req.is_multipart_form_data()) {
  8052. const auto &content_type = req.get_header_value("Content-Type");
  8053. std::string boundary;
  8054. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  8055. res.status = StatusCode::BadRequest_400;
  8056. output_error_log(Error::MultipartParsing, &req);
  8057. return false;
  8058. }
  8059. multipart_form_data_parser.set_boundary(std::move(boundary));
  8060. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  8061. return multipart_form_data_parser.parse(buf, n, multipart_header,
  8062. multipart_receiver);
  8063. };
  8064. } else {
  8065. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  8066. size_t /*len*/) { return receiver(buf, n); };
  8067. }
  8068. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  8069. // are true (no Transfer-Encoding and no Content-Length), then the message
  8070. // body length is zero (no message body is present).
  8071. //
  8072. // For non-SSL builds, peek into the socket to detect clients that send a
  8073. // body without a Content-Length header (raw HTTP over TCP). If there is
  8074. // pending data that exceeds the configured payload limit, treat this as an
  8075. // oversized request and fail early (causing connection close). For SSL
  8076. // builds we cannot reliably peek the decrypted application bytes, so keep
  8077. // the original behaviour.
  8078. #if !defined(CPPHTTPLIB_TLS_ENABLED)
  8079. if (!req.has_header("Content-Length") &&
  8080. !detail::is_chunked_transfer_encoding(req.headers)) {
  8081. // Only peek if payload_max_length is set to a finite value
  8082. if (payload_max_length_ > 0 &&
  8083. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  8084. socket_t s = strm.socket();
  8085. if (s != INVALID_SOCKET) {
  8086. // Peek to check if there is any pending data
  8087. char peekbuf[1];
  8088. ssize_t n = ::recv(s, peekbuf, 1, MSG_PEEK);
  8089. if (n > 0) {
  8090. // There is data, so read it with payload limit enforcement
  8091. auto result = detail::read_content_without_length(
  8092. strm, payload_max_length_, out);
  8093. if (result == detail::ReadContentResult::PayloadTooLarge) {
  8094. res.status = StatusCode::PayloadTooLarge_413;
  8095. return false;
  8096. } else if (result != detail::ReadContentResult::Success) {
  8097. return false;
  8098. }
  8099. return true;
  8100. }
  8101. }
  8102. }
  8103. return true;
  8104. }
  8105. #else
  8106. if (!req.has_header("Content-Length") &&
  8107. !detail::is_chunked_transfer_encoding(req.headers)) {
  8108. return true;
  8109. }
  8110. #endif
  8111. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  8112. out, true)) {
  8113. return false;
  8114. }
  8115. if (req.is_multipart_form_data()) {
  8116. if (!multipart_form_data_parser.is_valid()) {
  8117. res.status = StatusCode::BadRequest_400;
  8118. output_error_log(Error::MultipartParsing, &req);
  8119. return false;
  8120. }
  8121. }
  8122. return true;
  8123. }
  8124. inline bool Server::handle_file_request(Request &req, Response &res) {
  8125. for (const auto &entry : base_dirs_) {
  8126. // Prefix match
  8127. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  8128. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  8129. if (detail::is_valid_path(sub_path)) {
  8130. auto path = entry.base_dir + sub_path;
  8131. if (path.back() == '/') { path += "index.html"; }
  8132. detail::FileStat stat(path);
  8133. if (stat.is_dir()) {
  8134. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  8135. return true;
  8136. }
  8137. if (stat.is_file()) {
  8138. for (const auto &kv : entry.headers) {
  8139. res.set_header(kv.first, kv.second);
  8140. }
  8141. auto etag = detail::compute_etag(stat);
  8142. if (!etag.empty()) { res.set_header("ETag", etag); }
  8143. auto mtime = stat.mtime();
  8144. auto last_modified = detail::file_mtime_to_http_date(mtime);
  8145. if (!last_modified.empty()) {
  8146. res.set_header("Last-Modified", last_modified);
  8147. }
  8148. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  8149. check_if_range(req, etag, mtime);
  8150. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8151. if (!mm->is_open()) {
  8152. output_error_log(Error::OpenFile, &req);
  8153. return false;
  8154. }
  8155. res.set_content_provider(
  8156. mm->size(),
  8157. detail::find_content_type(path, file_extension_and_mimetype_map_,
  8158. default_file_mimetype_),
  8159. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8160. sink.write(mm->data() + offset, length);
  8161. return true;
  8162. });
  8163. if (req.method != "HEAD" && file_request_handler_) {
  8164. file_request_handler_(req, res);
  8165. }
  8166. return true;
  8167. } else {
  8168. output_error_log(Error::OpenFile, &req);
  8169. }
  8170. }
  8171. }
  8172. }
  8173. return false;
  8174. }
  8175. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  8176. const std::string &etag,
  8177. time_t mtime) const {
  8178. // Handle conditional GET:
  8179. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  8180. // 2. If-Modified-Since is checked only when If-None-Match is absent
  8181. if (req.has_header("If-None-Match")) {
  8182. if (!etag.empty()) {
  8183. auto val = req.get_header_value("If-None-Match");
  8184. // NOTE: We use exact string matching here. This works correctly
  8185. // because our server always generates weak ETags (W/"..."), and
  8186. // clients typically send back the same ETag they received.
  8187. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  8188. // If-None-Match, where W/"x" and "x" would match, but this
  8189. // simplified implementation requires exact matches.
  8190. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  8191. [&](const char *b, const char *e) {
  8192. return std::equal(b, e, "*") ||
  8193. std::equal(b, e, etag.begin());
  8194. });
  8195. if (ret) {
  8196. res.status = StatusCode::NotModified_304;
  8197. return true;
  8198. }
  8199. }
  8200. } else if (req.has_header("If-Modified-Since")) {
  8201. auto val = req.get_header_value("If-Modified-Since");
  8202. auto t = detail::parse_http_date(val);
  8203. if (t != static_cast<time_t>(-1) && mtime <= t) {
  8204. res.status = StatusCode::NotModified_304;
  8205. return true;
  8206. }
  8207. }
  8208. return false;
  8209. }
  8210. inline bool Server::check_if_range(Request &req, const std::string &etag,
  8211. time_t mtime) const {
  8212. // Handle If-Range for partial content requests (RFC 9110
  8213. // Section 13.1.5). If-Range is only evaluated when Range header is
  8214. // present. If the validator matches, serve partial content; otherwise
  8215. // serve full content.
  8216. if (!req.ranges.empty() && req.has_header("If-Range")) {
  8217. auto val = req.get_header_value("If-Range");
  8218. auto is_valid_range = [&]() {
  8219. if (detail::is_strong_etag(val)) {
  8220. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  8221. // comparison.
  8222. return (!etag.empty() && val == etag);
  8223. } else if (detail::is_weak_etag(val)) {
  8224. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  8225. return false;
  8226. } else {
  8227. // HTTP-date comparison
  8228. auto t = detail::parse_http_date(val);
  8229. return (t != static_cast<time_t>(-1) && mtime <= t);
  8230. }
  8231. };
  8232. if (!is_valid_range()) {
  8233. // Validator doesn't match: ignore Range and serve full content
  8234. req.ranges.clear();
  8235. return false;
  8236. }
  8237. }
  8238. return true;
  8239. }
  8240. inline socket_t
  8241. Server::create_server_socket(const std::string &host, int port,
  8242. int socket_flags,
  8243. SocketOptions socket_options) const {
  8244. return detail::create_socket(
  8245. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  8246. ipv6_v6only_, std::move(socket_options),
  8247. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  8248. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  8249. output_error_log(Error::BindIPAddress, nullptr);
  8250. return false;
  8251. }
  8252. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  8253. output_error_log(Error::Listen, nullptr);
  8254. return false;
  8255. }
  8256. return true;
  8257. });
  8258. }
  8259. inline int Server::bind_internal(const std::string &host, int port,
  8260. int socket_flags) {
  8261. if (is_decommissioned) { return -1; }
  8262. if (!is_valid()) { return -1; }
  8263. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  8264. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  8265. if (port == 0) {
  8266. struct sockaddr_storage addr;
  8267. socklen_t addr_len = sizeof(addr);
  8268. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  8269. &addr_len) == -1) {
  8270. output_error_log(Error::GetSockName, nullptr);
  8271. return -1;
  8272. }
  8273. if (addr.ss_family == AF_INET) {
  8274. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  8275. } else if (addr.ss_family == AF_INET6) {
  8276. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  8277. } else {
  8278. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  8279. return -1;
  8280. }
  8281. } else {
  8282. return port;
  8283. }
  8284. }
  8285. inline bool Server::listen_internal() {
  8286. if (is_decommissioned) { return false; }
  8287. auto ret = true;
  8288. is_running_ = true;
  8289. auto se = detail::scope_exit([&]() { is_running_ = false; });
  8290. {
  8291. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  8292. while (svr_sock_ != INVALID_SOCKET) {
  8293. #ifndef _WIN32
  8294. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  8295. #endif
  8296. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  8297. idle_interval_usec_);
  8298. if (val == 0) { // Timeout
  8299. task_queue->on_idle();
  8300. continue;
  8301. }
  8302. #ifndef _WIN32
  8303. }
  8304. #endif
  8305. #if defined _WIN32
  8306. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  8307. // OVERLAPPED
  8308. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  8309. #elif defined SOCK_CLOEXEC
  8310. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  8311. #else
  8312. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  8313. #endif
  8314. if (sock == INVALID_SOCKET) {
  8315. if (errno == EMFILE) {
  8316. // The per-process limit of open file descriptors has been reached.
  8317. // Try to accept new connections after a short sleep.
  8318. std::this_thread::sleep_for(std::chrono::microseconds{1});
  8319. continue;
  8320. } else if (errno == EINTR || errno == EAGAIN) {
  8321. continue;
  8322. }
  8323. if (svr_sock_ != INVALID_SOCKET) {
  8324. detail::close_socket(svr_sock_);
  8325. ret = false;
  8326. output_error_log(Error::Connection, nullptr);
  8327. } else {
  8328. ; // The server socket was closed by user.
  8329. }
  8330. break;
  8331. }
  8332. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  8333. read_timeout_sec_, read_timeout_usec_);
  8334. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  8335. write_timeout_sec_, write_timeout_usec_);
  8336. if (!task_queue->enqueue(
  8337. [this, sock]() { process_and_close_socket(sock); })) {
  8338. output_error_log(Error::ResourceExhaustion, nullptr);
  8339. detail::shutdown_socket(sock);
  8340. detail::close_socket(sock);
  8341. }
  8342. }
  8343. task_queue->shutdown();
  8344. }
  8345. is_decommissioned = !ret;
  8346. return ret;
  8347. }
  8348. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  8349. if (pre_routing_handler_ &&
  8350. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  8351. return true;
  8352. }
  8353. // File handler
  8354. if ((req.method == "GET" || req.method == "HEAD") &&
  8355. handle_file_request(req, res)) {
  8356. return true;
  8357. }
  8358. if (detail::expect_content(req)) {
  8359. // Content reader handler
  8360. {
  8361. ContentReader reader(
  8362. [&](ContentReceiver receiver) {
  8363. auto result = read_content_with_content_receiver(
  8364. strm, req, res, std::move(receiver), nullptr, nullptr);
  8365. if (!result) { output_error_log(Error::Read, &req); }
  8366. return result;
  8367. },
  8368. [&](FormDataHeader header, ContentReceiver receiver) {
  8369. auto result = read_content_with_content_receiver(
  8370. strm, req, res, nullptr, std::move(header),
  8371. std::move(receiver));
  8372. if (!result) { output_error_log(Error::Read, &req); }
  8373. return result;
  8374. });
  8375. if (req.method == "POST") {
  8376. if (dispatch_request_for_content_reader(
  8377. req, res, std::move(reader),
  8378. post_handlers_for_content_reader_)) {
  8379. return true;
  8380. }
  8381. } else if (req.method == "PUT") {
  8382. if (dispatch_request_for_content_reader(
  8383. req, res, std::move(reader),
  8384. put_handlers_for_content_reader_)) {
  8385. return true;
  8386. }
  8387. } else if (req.method == "PATCH") {
  8388. if (dispatch_request_for_content_reader(
  8389. req, res, std::move(reader),
  8390. patch_handlers_for_content_reader_)) {
  8391. return true;
  8392. }
  8393. } else if (req.method == "DELETE") {
  8394. if (dispatch_request_for_content_reader(
  8395. req, res, std::move(reader),
  8396. delete_handlers_for_content_reader_)) {
  8397. return true;
  8398. }
  8399. }
  8400. }
  8401. // Read content into `req.body`
  8402. if (!read_content(strm, req, res)) {
  8403. output_error_log(Error::Read, &req);
  8404. return false;
  8405. }
  8406. }
  8407. // Regular handler
  8408. if (req.method == "GET" || req.method == "HEAD") {
  8409. return dispatch_request(req, res, get_handlers_);
  8410. } else if (req.method == "POST") {
  8411. return dispatch_request(req, res, post_handlers_);
  8412. } else if (req.method == "PUT") {
  8413. return dispatch_request(req, res, put_handlers_);
  8414. } else if (req.method == "DELETE") {
  8415. return dispatch_request(req, res, delete_handlers_);
  8416. } else if (req.method == "OPTIONS") {
  8417. return dispatch_request(req, res, options_handlers_);
  8418. } else if (req.method == "PATCH") {
  8419. return dispatch_request(req, res, patch_handlers_);
  8420. }
  8421. res.status = StatusCode::BadRequest_400;
  8422. return false;
  8423. }
  8424. inline bool Server::dispatch_request(Request &req, Response &res,
  8425. const Handlers &handlers) const {
  8426. for (const auto &x : handlers) {
  8427. const auto &matcher = x.first;
  8428. const auto &handler = x.second;
  8429. if (matcher->match(req)) {
  8430. req.matched_route = matcher->pattern();
  8431. if (!pre_request_handler_ ||
  8432. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8433. handler(req, res);
  8434. }
  8435. return true;
  8436. }
  8437. }
  8438. return false;
  8439. }
  8440. inline void Server::apply_ranges(const Request &req, Response &res,
  8441. std::string &content_type,
  8442. std::string &boundary) const {
  8443. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  8444. auto it = res.headers.find("Content-Type");
  8445. if (it != res.headers.end()) {
  8446. content_type = it->second;
  8447. res.headers.erase(it);
  8448. }
  8449. boundary = detail::make_multipart_data_boundary();
  8450. res.set_header("Content-Type",
  8451. "multipart/byteranges; boundary=" + boundary);
  8452. }
  8453. auto type = detail::encoding_type(req, res);
  8454. if (res.body.empty()) {
  8455. if (res.content_length_ > 0) {
  8456. size_t length = 0;
  8457. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8458. length = res.content_length_;
  8459. } else if (req.ranges.size() == 1) {
  8460. auto offset_and_length = detail::get_range_offset_and_length(
  8461. req.ranges[0], res.content_length_);
  8462. length = offset_and_length.second;
  8463. auto content_range = detail::make_content_range_header_field(
  8464. offset_and_length, res.content_length_);
  8465. res.set_header("Content-Range", content_range);
  8466. } else {
  8467. length = detail::get_multipart_ranges_data_length(
  8468. req, boundary, content_type, res.content_length_);
  8469. }
  8470. res.set_header("Content-Length", std::to_string(length));
  8471. } else {
  8472. if (res.content_provider_) {
  8473. if (res.is_chunked_content_provider_) {
  8474. res.set_header("Transfer-Encoding", "chunked");
  8475. if (type == detail::EncodingType::Gzip) {
  8476. res.set_header("Content-Encoding", "gzip");
  8477. res.set_header("Vary", "Accept-Encoding");
  8478. } else if (type == detail::EncodingType::Brotli) {
  8479. res.set_header("Content-Encoding", "br");
  8480. res.set_header("Vary", "Accept-Encoding");
  8481. } else if (type == detail::EncodingType::Zstd) {
  8482. res.set_header("Content-Encoding", "zstd");
  8483. res.set_header("Vary", "Accept-Encoding");
  8484. }
  8485. }
  8486. }
  8487. }
  8488. } else {
  8489. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8490. ;
  8491. } else if (req.ranges.size() == 1) {
  8492. auto offset_and_length =
  8493. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  8494. auto offset = offset_and_length.first;
  8495. auto length = offset_and_length.second;
  8496. auto content_range = detail::make_content_range_header_field(
  8497. offset_and_length, res.body.size());
  8498. res.set_header("Content-Range", content_range);
  8499. assert(offset + length <= res.body.size());
  8500. res.body = res.body.substr(offset, length);
  8501. } else {
  8502. std::string data;
  8503. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  8504. res.body.size(), data);
  8505. res.body.swap(data);
  8506. }
  8507. if (type != detail::EncodingType::None) {
  8508. output_pre_compression_log(req, res);
  8509. std::unique_ptr<detail::compressor> compressor;
  8510. std::string content_encoding;
  8511. if (type == detail::EncodingType::Gzip) {
  8512. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8513. compressor = detail::make_unique<detail::gzip_compressor>();
  8514. content_encoding = "gzip";
  8515. #endif
  8516. } else if (type == detail::EncodingType::Brotli) {
  8517. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8518. compressor = detail::make_unique<detail::brotli_compressor>();
  8519. content_encoding = "br";
  8520. #endif
  8521. } else if (type == detail::EncodingType::Zstd) {
  8522. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8523. compressor = detail::make_unique<detail::zstd_compressor>();
  8524. content_encoding = "zstd";
  8525. #endif
  8526. }
  8527. if (compressor) {
  8528. std::string compressed;
  8529. if (compressor->compress(res.body.data(), res.body.size(), true,
  8530. [&](const char *data, size_t data_len) {
  8531. compressed.append(data, data_len);
  8532. return true;
  8533. })) {
  8534. res.body.swap(compressed);
  8535. res.set_header("Content-Encoding", content_encoding);
  8536. res.set_header("Vary", "Accept-Encoding");
  8537. }
  8538. }
  8539. }
  8540. auto length = std::to_string(res.body.size());
  8541. res.set_header("Content-Length", length);
  8542. }
  8543. }
  8544. inline bool Server::dispatch_request_for_content_reader(
  8545. Request &req, Response &res, ContentReader content_reader,
  8546. const HandlersForContentReader &handlers) const {
  8547. for (const auto &x : handlers) {
  8548. const auto &matcher = x.first;
  8549. const auto &handler = x.second;
  8550. if (matcher->match(req)) {
  8551. req.matched_route = matcher->pattern();
  8552. if (!pre_request_handler_ ||
  8553. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8554. handler(req, res, content_reader);
  8555. }
  8556. return true;
  8557. }
  8558. }
  8559. return false;
  8560. }
  8561. inline std::string
  8562. get_client_ip(const std::string &x_forwarded_for,
  8563. const std::vector<std::string> &trusted_proxies) {
  8564. // X-Forwarded-For is a comma-separated list per RFC 7239
  8565. std::vector<std::string> ip_list;
  8566. detail::split(x_forwarded_for.data(),
  8567. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  8568. [&](const char *b, const char *e) {
  8569. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  8570. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  8571. });
  8572. for (size_t i = 0; i < ip_list.size(); ++i) {
  8573. auto ip = ip_list[i];
  8574. auto is_trusted_proxy =
  8575. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  8576. [&](const std::string &proxy) { return ip == proxy; });
  8577. if (is_trusted_proxy) {
  8578. if (i == 0) {
  8579. // If the trusted proxy is the first IP, there's no preceding client IP
  8580. return ip;
  8581. } else {
  8582. // Return the IP immediately before the trusted proxy
  8583. return ip_list[i - 1];
  8584. }
  8585. }
  8586. }
  8587. // If no trusted proxy is found, return the first IP in the list
  8588. return ip_list.front();
  8589. }
  8590. inline bool
  8591. Server::process_request(Stream &strm, const std::string &remote_addr,
  8592. int remote_port, const std::string &local_addr,
  8593. int local_port, bool close_connection,
  8594. bool &connection_closed,
  8595. const std::function<void(Request &)> &setup_request) {
  8596. std::array<char, 2048> buf{};
  8597. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8598. // Connection has been closed on client
  8599. if (!line_reader.getline()) { return false; }
  8600. Request req;
  8601. req.start_time_ = std::chrono::steady_clock::now();
  8602. req.remote_addr = remote_addr;
  8603. req.remote_port = remote_port;
  8604. req.local_addr = local_addr;
  8605. req.local_port = local_port;
  8606. Response res;
  8607. res.version = "HTTP/1.1";
  8608. res.headers = default_headers_;
  8609. #ifdef __APPLE__
  8610. // Socket file descriptor exceeded FD_SETSIZE...
  8611. if (strm.socket() >= FD_SETSIZE) {
  8612. Headers dummy;
  8613. detail::read_headers(strm, dummy);
  8614. res.status = StatusCode::InternalServerError_500;
  8615. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  8616. return write_response(strm, close_connection, req, res);
  8617. }
  8618. #endif
  8619. // Request line and headers
  8620. if (!parse_request_line(line_reader.ptr(), req)) {
  8621. res.status = StatusCode::BadRequest_400;
  8622. output_error_log(Error::InvalidRequestLine, &req);
  8623. return write_response(strm, close_connection, req, res);
  8624. }
  8625. // Request headers
  8626. if (!detail::read_headers(strm, req.headers)) {
  8627. res.status = StatusCode::BadRequest_400;
  8628. output_error_log(Error::InvalidHeaders, &req);
  8629. return write_response(strm, close_connection, req, res);
  8630. }
  8631. // Check if the request URI doesn't exceed the limit
  8632. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  8633. res.status = StatusCode::UriTooLong_414;
  8634. output_error_log(Error::ExceedUriMaxLength, &req);
  8635. return write_response(strm, close_connection, req, res);
  8636. }
  8637. if (req.get_header_value("Connection") == "close") {
  8638. connection_closed = true;
  8639. }
  8640. if (req.version == "HTTP/1.0" &&
  8641. req.get_header_value("Connection") != "Keep-Alive") {
  8642. connection_closed = true;
  8643. }
  8644. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  8645. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  8646. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  8647. } else {
  8648. req.remote_addr = remote_addr;
  8649. }
  8650. req.remote_port = remote_port;
  8651. req.local_addr = local_addr;
  8652. req.local_port = local_port;
  8653. if (req.has_header("Accept")) {
  8654. const auto &accept_header = req.get_header_value("Accept");
  8655. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  8656. res.status = StatusCode::BadRequest_400;
  8657. output_error_log(Error::HTTPParsing, &req);
  8658. return write_response(strm, close_connection, req, res);
  8659. }
  8660. }
  8661. if (req.has_header("Range")) {
  8662. const auto &range_header_value = req.get_header_value("Range");
  8663. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  8664. res.status = StatusCode::RangeNotSatisfiable_416;
  8665. output_error_log(Error::InvalidRangeHeader, &req);
  8666. return write_response(strm, close_connection, req, res);
  8667. }
  8668. }
  8669. if (setup_request) { setup_request(req); }
  8670. if (req.get_header_value("Expect") == "100-continue") {
  8671. int status = StatusCode::Continue_100;
  8672. if (expect_100_continue_handler_) {
  8673. status = expect_100_continue_handler_(req, res);
  8674. }
  8675. switch (status) {
  8676. case StatusCode::Continue_100:
  8677. case StatusCode::ExpectationFailed_417:
  8678. detail::write_response_line(strm, status);
  8679. strm.write("\r\n");
  8680. break;
  8681. default:
  8682. connection_closed = true;
  8683. return write_response(strm, true, req, res);
  8684. }
  8685. }
  8686. // Setup `is_connection_closed` method
  8687. auto sock = strm.socket();
  8688. req.is_connection_closed = [sock]() {
  8689. return !detail::is_socket_alive(sock);
  8690. };
  8691. // Routing
  8692. auto routed = false;
  8693. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8694. routed = routing(req, res, strm);
  8695. #else
  8696. try {
  8697. routed = routing(req, res, strm);
  8698. } catch (std::exception &e) {
  8699. if (exception_handler_) {
  8700. auto ep = std::current_exception();
  8701. exception_handler_(req, res, ep);
  8702. routed = true;
  8703. } else {
  8704. res.status = StatusCode::InternalServerError_500;
  8705. std::string val;
  8706. auto s = e.what();
  8707. for (size_t i = 0; s[i]; i++) {
  8708. switch (s[i]) {
  8709. case '\r': val += "\\r"; break;
  8710. case '\n': val += "\\n"; break;
  8711. default: val += s[i]; break;
  8712. }
  8713. }
  8714. res.set_header("EXCEPTION_WHAT", val);
  8715. }
  8716. } catch (...) {
  8717. if (exception_handler_) {
  8718. auto ep = std::current_exception();
  8719. exception_handler_(req, res, ep);
  8720. routed = true;
  8721. } else {
  8722. res.status = StatusCode::InternalServerError_500;
  8723. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  8724. }
  8725. }
  8726. #endif
  8727. if (routed) {
  8728. if (res.status == -1) {
  8729. res.status = req.ranges.empty() ? StatusCode::OK_200
  8730. : StatusCode::PartialContent_206;
  8731. }
  8732. // Serve file content by using a content provider
  8733. if (!res.file_content_path_.empty()) {
  8734. const auto &path = res.file_content_path_;
  8735. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8736. if (!mm->is_open()) {
  8737. res.body.clear();
  8738. res.content_length_ = 0;
  8739. res.content_provider_ = nullptr;
  8740. res.status = StatusCode::NotFound_404;
  8741. output_error_log(Error::OpenFile, &req);
  8742. return write_response(strm, close_connection, req, res);
  8743. }
  8744. auto content_type = res.file_content_content_type_;
  8745. if (content_type.empty()) {
  8746. content_type = detail::find_content_type(
  8747. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  8748. }
  8749. res.set_content_provider(
  8750. mm->size(), content_type,
  8751. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8752. sink.write(mm->data() + offset, length);
  8753. return true;
  8754. });
  8755. }
  8756. if (detail::range_error(req, res)) {
  8757. res.body.clear();
  8758. res.content_length_ = 0;
  8759. res.content_provider_ = nullptr;
  8760. res.status = StatusCode::RangeNotSatisfiable_416;
  8761. return write_response(strm, close_connection, req, res);
  8762. }
  8763. return write_response_with_content(strm, close_connection, req, res);
  8764. } else {
  8765. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  8766. return write_response(strm, close_connection, req, res);
  8767. }
  8768. }
  8769. inline bool Server::is_valid() const { return true; }
  8770. inline bool Server::process_and_close_socket(socket_t sock) {
  8771. std::string remote_addr;
  8772. int remote_port = 0;
  8773. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8774. std::string local_addr;
  8775. int local_port = 0;
  8776. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8777. auto ret = detail::process_server_socket(
  8778. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8779. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8780. write_timeout_usec_,
  8781. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8782. return process_request(strm, remote_addr, remote_port, local_addr,
  8783. local_port, close_connection, connection_closed,
  8784. nullptr);
  8785. });
  8786. detail::shutdown_socket(sock);
  8787. detail::close_socket(sock);
  8788. return ret;
  8789. }
  8790. inline void Server::output_log(const Request &req, const Response &res) const {
  8791. if (logger_) {
  8792. std::lock_guard<std::mutex> guard(logger_mutex_);
  8793. logger_(req, res);
  8794. }
  8795. }
  8796. inline void Server::output_pre_compression_log(const Request &req,
  8797. const Response &res) const {
  8798. if (pre_compression_logger_) {
  8799. std::lock_guard<std::mutex> guard(logger_mutex_);
  8800. pre_compression_logger_(req, res);
  8801. }
  8802. }
  8803. inline void Server::output_error_log(const Error &err,
  8804. const Request *req) const {
  8805. if (error_logger_) {
  8806. std::lock_guard<std::mutex> guard(logger_mutex_);
  8807. error_logger_(err, req);
  8808. }
  8809. }
  8810. /*
  8811. * Group 5: ClientImpl and Client (Universal) implementation
  8812. */
  8813. // HTTP client implementation
  8814. inline ClientImpl::ClientImpl(const std::string &host)
  8815. : ClientImpl(host, 80, std::string(), std::string()) {}
  8816. inline ClientImpl::ClientImpl(const std::string &host, int port)
  8817. : ClientImpl(host, port, std::string(), std::string()) {}
  8818. inline ClientImpl::ClientImpl(const std::string &host, int port,
  8819. const std::string &client_cert_path,
  8820. const std::string &client_key_path)
  8821. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  8822. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  8823. inline ClientImpl::~ClientImpl() {
  8824. // Wait until all the requests in flight are handled.
  8825. size_t retry_count = 10;
  8826. while (retry_count-- > 0) {
  8827. {
  8828. std::lock_guard<std::mutex> guard(socket_mutex_);
  8829. if (socket_requests_in_flight_ == 0) { break; }
  8830. }
  8831. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  8832. }
  8833. std::lock_guard<std::mutex> guard(socket_mutex_);
  8834. shutdown_socket(socket_);
  8835. close_socket(socket_);
  8836. }
  8837. inline bool ClientImpl::is_valid() const { return true; }
  8838. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  8839. client_cert_path_ = rhs.client_cert_path_;
  8840. client_key_path_ = rhs.client_key_path_;
  8841. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  8842. read_timeout_sec_ = rhs.read_timeout_sec_;
  8843. read_timeout_usec_ = rhs.read_timeout_usec_;
  8844. write_timeout_sec_ = rhs.write_timeout_sec_;
  8845. write_timeout_usec_ = rhs.write_timeout_usec_;
  8846. max_timeout_msec_ = rhs.max_timeout_msec_;
  8847. basic_auth_username_ = rhs.basic_auth_username_;
  8848. basic_auth_password_ = rhs.basic_auth_password_;
  8849. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  8850. keep_alive_ = rhs.keep_alive_;
  8851. follow_location_ = rhs.follow_location_;
  8852. path_encode_ = rhs.path_encode_;
  8853. address_family_ = rhs.address_family_;
  8854. tcp_nodelay_ = rhs.tcp_nodelay_;
  8855. ipv6_v6only_ = rhs.ipv6_v6only_;
  8856. socket_options_ = rhs.socket_options_;
  8857. compress_ = rhs.compress_;
  8858. decompress_ = rhs.decompress_;
  8859. interface_ = rhs.interface_;
  8860. proxy_host_ = rhs.proxy_host_;
  8861. proxy_port_ = rhs.proxy_port_;
  8862. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  8863. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  8864. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  8865. logger_ = rhs.logger_;
  8866. error_logger_ = rhs.error_logger_;
  8867. #ifdef CPPHTTPLIB_SSL_ENABLED
  8868. digest_auth_username_ = rhs.digest_auth_username_;
  8869. digest_auth_password_ = rhs.digest_auth_password_;
  8870. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  8871. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  8872. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  8873. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  8874. server_certificate_verification_ = rhs.server_certificate_verification_;
  8875. server_hostname_verification_ = rhs.server_hostname_verification_;
  8876. #endif
  8877. }
  8878. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  8879. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8880. return detail::create_client_socket(
  8881. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  8882. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  8883. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  8884. write_timeout_sec_, write_timeout_usec_, interface_, error);
  8885. }
  8886. // Check is custom IP specified for host_
  8887. std::string ip;
  8888. auto it = addr_map_.find(host_);
  8889. if (it != addr_map_.end()) { ip = it->second; }
  8890. return detail::create_client_socket(
  8891. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  8892. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  8893. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8894. write_timeout_usec_, interface_, error);
  8895. }
  8896. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  8897. Error &error) {
  8898. auto sock = create_client_socket(error);
  8899. if (sock == INVALID_SOCKET) { return false; }
  8900. socket.sock = sock;
  8901. return true;
  8902. }
  8903. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  8904. return create_and_connect_socket(socket, error);
  8905. }
  8906. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  8907. bool /*shutdown_gracefully*/) {
  8908. // If there are any requests in flight from threads other than us, then it's
  8909. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  8910. assert(socket_requests_in_flight_ == 0 ||
  8911. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8912. }
  8913. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  8914. if (socket.sock == INVALID_SOCKET) { return; }
  8915. detail::shutdown_socket(socket.sock);
  8916. }
  8917. inline void ClientImpl::close_socket(Socket &socket) {
  8918. // If there are requests in flight in another thread, usually closing
  8919. // the socket will be fine and they will simply receive an error when
  8920. // using the closed socket, but it is still a bug since rarely the OS
  8921. // may reassign the socket id to be used for a new socket, and then
  8922. // suddenly they will be operating on a live socket that is different
  8923. // than the one they intended!
  8924. assert(socket_requests_in_flight_ == 0 ||
  8925. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8926. // It is also a bug if this happens while SSL is still active
  8927. #ifdef CPPHTTPLIB_SSL_ENABLED
  8928. assert(socket.ssl == nullptr);
  8929. #endif
  8930. if (socket.sock == INVALID_SOCKET) { return; }
  8931. detail::close_socket(socket.sock);
  8932. socket.sock = INVALID_SOCKET;
  8933. }
  8934. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  8935. Response &res,
  8936. bool skip_100_continue) const {
  8937. std::array<char, 2048> buf{};
  8938. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8939. if (!line_reader.getline()) { return false; }
  8940. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  8941. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  8942. #else
  8943. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  8944. #endif
  8945. std::cmatch m;
  8946. if (!std::regex_match(line_reader.ptr(), m, re)) {
  8947. return req.method == "CONNECT";
  8948. }
  8949. res.version = std::string(m[1]);
  8950. res.status = std::stoi(std::string(m[2]));
  8951. res.reason = std::string(m[3]);
  8952. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  8953. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  8954. if (!line_reader.getline()) { return false; } // CRLF
  8955. if (!line_reader.getline()) { return false; } // next response line
  8956. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  8957. res.version = std::string(m[1]);
  8958. res.status = std::stoi(std::string(m[2]));
  8959. res.reason = std::string(m[3]);
  8960. }
  8961. return true;
  8962. }
  8963. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  8964. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  8965. auto ret = send_(req, res, error);
  8966. if (error == Error::SSLPeerCouldBeClosed_) {
  8967. assert(!ret);
  8968. ret = send_(req, res, error);
  8969. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  8970. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  8971. }
  8972. return ret;
  8973. }
  8974. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  8975. {
  8976. std::lock_guard<std::mutex> guard(socket_mutex_);
  8977. // Set this to false immediately - if it ever gets set to true by the end
  8978. // of the request, we know another thread instructed us to close the
  8979. // socket.
  8980. socket_should_be_closed_when_request_is_done_ = false;
  8981. auto is_alive = false;
  8982. if (socket_.is_open()) {
  8983. is_alive = detail::is_socket_alive(socket_.sock);
  8984. #ifdef CPPHTTPLIB_SSL_ENABLED
  8985. if (is_alive && is_ssl()) {
  8986. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  8987. is_alive = false;
  8988. }
  8989. }
  8990. #endif
  8991. if (!is_alive) {
  8992. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  8993. // seems like the other side has already closed the connection Also,
  8994. // there cannot be any requests in flight from other threads since we
  8995. // locked request_mutex_, so safe to close everything immediately
  8996. const bool shutdown_gracefully = false;
  8997. shutdown_ssl(socket_, shutdown_gracefully);
  8998. shutdown_socket(socket_);
  8999. close_socket(socket_);
  9000. }
  9001. }
  9002. if (!is_alive) {
  9003. if (!ensure_socket_connection(socket_, error)) {
  9004. output_error_log(error, &req);
  9005. return false;
  9006. }
  9007. #ifdef CPPHTTPLIB_SSL_ENABLED
  9008. // TODO: refactoring
  9009. if (is_ssl()) {
  9010. auto &scli = static_cast<SSLClient &>(*this);
  9011. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9012. auto success = false;
  9013. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  9014. error)) {
  9015. if (!success) { output_error_log(error, &req); }
  9016. return success;
  9017. }
  9018. }
  9019. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9020. if (!scli.initialize_ssl(socket_, error)) {
  9021. output_error_log(error, &req);
  9022. return false;
  9023. }
  9024. }
  9025. }
  9026. #endif
  9027. }
  9028. // Mark the current socket as being in use so that it cannot be closed by
  9029. // anyone else while this request is ongoing, even though we will be
  9030. // releasing the mutex.
  9031. if (socket_requests_in_flight_ > 1) {
  9032. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  9033. }
  9034. socket_requests_in_flight_ += 1;
  9035. socket_requests_are_from_thread_ = std::this_thread::get_id();
  9036. }
  9037. for (const auto &header : default_headers_) {
  9038. if (req.headers.find(header.first) == req.headers.end()) {
  9039. req.headers.insert(header);
  9040. }
  9041. }
  9042. auto ret = false;
  9043. auto close_connection = !keep_alive_;
  9044. auto se = detail::scope_exit([&]() {
  9045. // Briefly lock mutex in order to mark that a request is no longer ongoing
  9046. std::lock_guard<std::mutex> guard(socket_mutex_);
  9047. socket_requests_in_flight_ -= 1;
  9048. if (socket_requests_in_flight_ <= 0) {
  9049. assert(socket_requests_in_flight_ == 0);
  9050. socket_requests_are_from_thread_ = std::thread::id();
  9051. }
  9052. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  9053. !ret) {
  9054. shutdown_ssl(socket_, true);
  9055. shutdown_socket(socket_);
  9056. close_socket(socket_);
  9057. }
  9058. });
  9059. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  9060. return handle_request(strm, req, res, close_connection, error);
  9061. });
  9062. if (!ret) {
  9063. if (error == Error::Success) {
  9064. error = Error::Unknown;
  9065. output_error_log(error, &req);
  9066. }
  9067. }
  9068. return ret;
  9069. }
  9070. inline Result ClientImpl::send(const Request &req) {
  9071. auto req2 = req;
  9072. return send_(std::move(req2));
  9073. }
  9074. inline Result ClientImpl::send_(Request &&req) {
  9075. auto res = detail::make_unique<Response>();
  9076. auto error = Error::Success;
  9077. auto ret = send(req, *res, error);
  9078. #ifdef CPPHTTPLIB_SSL_ENABLED
  9079. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  9080. last_ssl_error_, last_backend_error_};
  9081. #else
  9082. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  9083. #endif
  9084. }
  9085. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  9086. const std::string &ct) {
  9087. (void)for_stream;
  9088. for (const auto &header : default_headers_) {
  9089. if (!r.has_header(header.first)) { r.headers.insert(header); }
  9090. }
  9091. if (!r.has_header("Host")) {
  9092. if (address_family_ == AF_UNIX) {
  9093. r.headers.emplace("Host", "localhost");
  9094. } else {
  9095. r.headers.emplace(
  9096. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  9097. }
  9098. }
  9099. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  9100. if (!r.content_receiver) {
  9101. if (!r.has_header("Accept-Encoding")) {
  9102. std::string accept_encoding;
  9103. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9104. accept_encoding = "br";
  9105. #endif
  9106. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9107. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  9108. accept_encoding += "gzip, deflate";
  9109. #endif
  9110. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9111. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  9112. accept_encoding += "zstd";
  9113. #endif
  9114. r.set_header("Accept-Encoding", accept_encoding);
  9115. }
  9116. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  9117. if (!r.has_header("User-Agent")) {
  9118. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  9119. r.set_header("User-Agent", agent);
  9120. }
  9121. #endif
  9122. }
  9123. if (!r.body.empty()) {
  9124. if (!ct.empty() && !r.has_header("Content-Type")) {
  9125. r.headers.emplace("Content-Type", ct);
  9126. }
  9127. if (!r.has_header("Content-Length")) {
  9128. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  9129. }
  9130. }
  9131. }
  9132. inline ClientImpl::StreamHandle
  9133. ClientImpl::open_stream(const std::string &method, const std::string &path,
  9134. const Params &params, const Headers &headers,
  9135. const std::string &body,
  9136. const std::string &content_type) {
  9137. StreamHandle handle;
  9138. handle.response = detail::make_unique<Response>();
  9139. handle.error = Error::Success;
  9140. auto query_path = params.empty() ? path : append_query_params(path, params);
  9141. handle.connection_ = detail::make_unique<ClientConnection>();
  9142. {
  9143. std::lock_guard<std::mutex> guard(socket_mutex_);
  9144. auto is_alive = false;
  9145. if (socket_.is_open()) {
  9146. is_alive = detail::is_socket_alive(socket_.sock);
  9147. #ifdef CPPHTTPLIB_SSL_ENABLED
  9148. if (is_alive && is_ssl()) {
  9149. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  9150. is_alive = false;
  9151. }
  9152. }
  9153. #endif
  9154. if (!is_alive) {
  9155. shutdown_ssl(socket_, false);
  9156. shutdown_socket(socket_);
  9157. close_socket(socket_);
  9158. }
  9159. }
  9160. if (!is_alive) {
  9161. if (!ensure_socket_connection(socket_, handle.error)) {
  9162. handle.response.reset();
  9163. return handle;
  9164. }
  9165. #ifdef CPPHTTPLIB_SSL_ENABLED
  9166. if (is_ssl()) {
  9167. auto &scli = static_cast<SSLClient &>(*this);
  9168. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9169. if (!scli.initialize_ssl(socket_, handle.error)) {
  9170. handle.response.reset();
  9171. return handle;
  9172. }
  9173. }
  9174. }
  9175. #endif
  9176. }
  9177. transfer_socket_ownership_to_handle(handle);
  9178. }
  9179. #ifdef CPPHTTPLIB_SSL_ENABLED
  9180. if (is_ssl() && handle.connection_->session) {
  9181. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  9182. handle.connection_->sock, handle.connection_->session,
  9183. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9184. write_timeout_usec_);
  9185. } else {
  9186. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  9187. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  9188. write_timeout_sec_, write_timeout_usec_);
  9189. }
  9190. #else
  9191. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  9192. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  9193. write_timeout_sec_, write_timeout_usec_);
  9194. #endif
  9195. handle.stream_ = handle.socket_stream_.get();
  9196. Request req;
  9197. req.method = method;
  9198. req.path = query_path;
  9199. req.headers = headers;
  9200. req.body = body;
  9201. prepare_default_headers(req, true, content_type);
  9202. auto &strm = *handle.stream_;
  9203. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  9204. handle.error = Error::Write;
  9205. handle.response.reset();
  9206. return handle;
  9207. }
  9208. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  9209. handle.error)) {
  9210. handle.response.reset();
  9211. return handle;
  9212. }
  9213. if (!body.empty()) {
  9214. if (strm.write(body.data(), body.size()) < 0) {
  9215. handle.error = Error::Write;
  9216. handle.response.reset();
  9217. return handle;
  9218. }
  9219. }
  9220. if (!read_response_line(strm, req, *handle.response) ||
  9221. !detail::read_headers(strm, handle.response->headers)) {
  9222. handle.error = Error::Read;
  9223. handle.response.reset();
  9224. return handle;
  9225. }
  9226. handle.body_reader_.stream = handle.stream_;
  9227. auto content_length_str = handle.response->get_header_value("Content-Length");
  9228. if (!content_length_str.empty()) {
  9229. handle.body_reader_.content_length =
  9230. static_cast<size_t>(std::stoull(content_length_str));
  9231. }
  9232. auto transfer_encoding =
  9233. handle.response->get_header_value("Transfer-Encoding");
  9234. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  9235. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  9236. if (!content_encoding.empty()) {
  9237. handle.decompressor_ = detail::create_decompressor(content_encoding);
  9238. }
  9239. return handle;
  9240. }
  9241. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  9242. if (!is_valid() || !response) { return -1; }
  9243. if (decompressor_) { return read_with_decompression(buf, len); }
  9244. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  9245. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  9246. trailers_parsed_ = true;
  9247. if (body_reader_.chunked_decoder) {
  9248. if (!body_reader_.chunked_decoder->parse_trailers_into(
  9249. response->trailers, response->headers)) {
  9250. return n;
  9251. }
  9252. } else {
  9253. detail::ChunkedDecoder dec(*stream_);
  9254. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  9255. return n;
  9256. }
  9257. }
  9258. }
  9259. return n;
  9260. }
  9261. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  9262. size_t len) {
  9263. if (decompress_offset_ < decompress_buffer_.size()) {
  9264. auto available = decompress_buffer_.size() - decompress_offset_;
  9265. auto to_copy = (std::min)(len, available);
  9266. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  9267. decompress_offset_ += to_copy;
  9268. return static_cast<ssize_t>(to_copy);
  9269. }
  9270. decompress_buffer_.clear();
  9271. decompress_offset_ = 0;
  9272. constexpr size_t kDecompressionBufferSize = 8192;
  9273. char compressed_buf[kDecompressionBufferSize];
  9274. while (true) {
  9275. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  9276. sizeof(compressed_buf));
  9277. if (n <= 0) { return n; }
  9278. bool decompress_ok =
  9279. decompressor_->decompress(compressed_buf, static_cast<size_t>(n),
  9280. [this](const char *data, size_t data_len) {
  9281. decompress_buffer_.append(data, data_len);
  9282. return true;
  9283. });
  9284. if (!decompress_ok) {
  9285. body_reader_.last_error = Error::Read;
  9286. return -1;
  9287. }
  9288. if (!decompress_buffer_.empty()) { break; }
  9289. }
  9290. auto to_copy = (std::min)(len, decompress_buffer_.size());
  9291. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  9292. decompress_offset_ = to_copy;
  9293. return static_cast<ssize_t>(to_copy);
  9294. }
  9295. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  9296. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  9297. return;
  9298. }
  9299. trailers_parsed_ = true;
  9300. const auto bufsiz = 128;
  9301. char line_buf[bufsiz];
  9302. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  9303. if (!line_reader.getline()) { return; }
  9304. if (!detail::parse_trailers(line_reader, response->trailers,
  9305. response->headers)) {
  9306. return;
  9307. }
  9308. }
  9309. namespace detail {
  9310. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  9311. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  9312. size_t &out_chunk_offset,
  9313. size_t &out_chunk_total) {
  9314. if (finished) { return 0; }
  9315. if (chunk_remaining == 0) {
  9316. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9317. if (!lr.getline()) { return -1; }
  9318. char *endptr = nullptr;
  9319. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  9320. if (endptr == lr.ptr()) { return -1; }
  9321. if (chunk_len == ULONG_MAX) { return -1; }
  9322. if (chunk_len == 0) {
  9323. chunk_remaining = 0;
  9324. finished = true;
  9325. out_chunk_offset = 0;
  9326. out_chunk_total = 0;
  9327. return 0;
  9328. }
  9329. chunk_remaining = static_cast<size_t>(chunk_len);
  9330. last_chunk_total = chunk_remaining;
  9331. last_chunk_offset = 0;
  9332. }
  9333. auto to_read = (std::min)(chunk_remaining, len);
  9334. auto n = strm.read(buf, to_read);
  9335. if (n <= 0) { return -1; }
  9336. auto offset_before = last_chunk_offset;
  9337. last_chunk_offset += static_cast<size_t>(n);
  9338. chunk_remaining -= static_cast<size_t>(n);
  9339. out_chunk_offset = offset_before;
  9340. out_chunk_total = last_chunk_total;
  9341. if (chunk_remaining == 0) {
  9342. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9343. if (!lr.getline()) { return -1; }
  9344. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  9345. }
  9346. return n;
  9347. }
  9348. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  9349. const Headers &src_headers) {
  9350. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  9351. if (!lr.getline()) { return false; }
  9352. return parse_trailers(lr, dest, src_headers);
  9353. }
  9354. } // namespace detail
  9355. inline void
  9356. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  9357. handle.connection_->sock = socket_.sock;
  9358. #ifdef CPPHTTPLIB_SSL_ENABLED
  9359. handle.connection_->session = socket_.ssl;
  9360. socket_.ssl = nullptr;
  9361. #endif
  9362. socket_.sock = INVALID_SOCKET;
  9363. }
  9364. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  9365. Response &res, bool close_connection,
  9366. Error &error) {
  9367. if (req.path.empty()) {
  9368. error = Error::Connection;
  9369. output_error_log(error, &req);
  9370. return false;
  9371. }
  9372. auto req_save = req;
  9373. bool ret;
  9374. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  9375. auto req2 = req;
  9376. req2.path = "http://" +
  9377. detail::make_host_and_port_string(host_, port_, false) +
  9378. req.path;
  9379. ret = process_request(strm, req2, res, close_connection, error);
  9380. req = std::move(req2);
  9381. req.path = req_save.path;
  9382. } else {
  9383. ret = process_request(strm, req, res, close_connection, error);
  9384. }
  9385. if (!ret) { return false; }
  9386. if (res.get_header_value("Connection") == "close" ||
  9387. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  9388. // TODO this requires a not-entirely-obvious chain of calls to be correct
  9389. // for this to be safe.
  9390. // This is safe to call because handle_request is only called by send_
  9391. // which locks the request mutex during the process. It would be a bug
  9392. // to call it from a different thread since it's a thread-safety issue
  9393. // to do these things to the socket if another thread is using the socket.
  9394. std::lock_guard<std::mutex> guard(socket_mutex_);
  9395. shutdown_ssl(socket_, true);
  9396. shutdown_socket(socket_);
  9397. close_socket(socket_);
  9398. }
  9399. if (300 < res.status && res.status < 400 && follow_location_) {
  9400. req = std::move(req_save);
  9401. ret = redirect(req, res, error);
  9402. }
  9403. #ifdef CPPHTTPLIB_SSL_ENABLED
  9404. if ((res.status == StatusCode::Unauthorized_401 ||
  9405. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  9406. req.authorization_count_ < 5) {
  9407. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  9408. const auto &username =
  9409. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  9410. const auto &password =
  9411. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  9412. if (!username.empty() && !password.empty()) {
  9413. std::map<std::string, std::string> auth;
  9414. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  9415. Request new_req = req;
  9416. new_req.authorization_count_ += 1;
  9417. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  9418. : "Authorization");
  9419. new_req.headers.insert(detail::make_digest_authentication_header(
  9420. req, auth, new_req.authorization_count_, detail::random_string(10),
  9421. username, password, is_proxy));
  9422. Response new_res;
  9423. ret = send(new_req, new_res, error);
  9424. if (ret) { res = std::move(new_res); }
  9425. }
  9426. }
  9427. }
  9428. #endif
  9429. return ret;
  9430. }
  9431. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  9432. if (req.redirect_count_ == 0) {
  9433. error = Error::ExceedRedirectCount;
  9434. output_error_log(error, &req);
  9435. return false;
  9436. }
  9437. auto location = res.get_header_value("location");
  9438. if (location.empty()) { return false; }
  9439. thread_local const std::regex re(
  9440. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  9441. std::smatch m;
  9442. if (!std::regex_match(location, m, re)) { return false; }
  9443. auto scheme = is_ssl() ? "https" : "http";
  9444. auto next_scheme = m[1].str();
  9445. auto next_host = m[2].str();
  9446. if (next_host.empty()) { next_host = m[3].str(); }
  9447. auto port_str = m[4].str();
  9448. auto next_path = m[5].str();
  9449. auto next_query = m[6].str();
  9450. auto next_port = port_;
  9451. if (!port_str.empty()) {
  9452. next_port = std::stoi(port_str);
  9453. } else if (!next_scheme.empty()) {
  9454. next_port = next_scheme == "https" ? 443 : 80;
  9455. }
  9456. if (next_scheme.empty()) { next_scheme = scheme; }
  9457. if (next_host.empty()) { next_host = host_; }
  9458. if (next_path.empty()) { next_path = "/"; }
  9459. auto path = decode_query_component(next_path, true) + next_query;
  9460. // Same host redirect - use current client
  9461. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  9462. return detail::redirect(*this, req, res, path, location, error);
  9463. }
  9464. // Cross-host/scheme redirect - create new client with robust setup
  9465. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  9466. path, location, error);
  9467. }
  9468. // New method for robust redirect client creation
  9469. inline bool ClientImpl::create_redirect_client(
  9470. const std::string &scheme, const std::string &host, int port, Request &req,
  9471. Response &res, const std::string &path, const std::string &location,
  9472. Error &error) {
  9473. // Determine if we need SSL
  9474. auto need_ssl = (scheme == "https");
  9475. // Clean up request headers that are host/client specific
  9476. // Remove headers that should not be carried over to new host
  9477. auto headers_to_remove =
  9478. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  9479. for (const auto &header_name : headers_to_remove) {
  9480. auto it = req.headers.find(header_name);
  9481. while (it != req.headers.end()) {
  9482. it = req.headers.erase(it);
  9483. it = req.headers.find(header_name);
  9484. }
  9485. }
  9486. // Create appropriate client type and handle redirect
  9487. if (need_ssl) {
  9488. #ifdef CPPHTTPLIB_SSL_ENABLED
  9489. // Create SSL client for HTTPS redirect
  9490. SSLClient redirect_client(host, port);
  9491. // Setup basic client configuration first
  9492. setup_redirect_client(redirect_client);
  9493. // SSL-specific configuration for proxy environments
  9494. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9495. // Critical: Disable SSL verification for proxy environments
  9496. redirect_client.enable_server_certificate_verification(false);
  9497. redirect_client.enable_server_hostname_verification(false);
  9498. } else {
  9499. // For direct SSL connections, copy SSL verification settings
  9500. redirect_client.enable_server_certificate_verification(
  9501. server_certificate_verification_);
  9502. redirect_client.enable_server_hostname_verification(
  9503. server_hostname_verification_);
  9504. }
  9505. // Transfer CA certificate to redirect client
  9506. if (!ca_cert_pem_.empty()) {
  9507. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  9508. ca_cert_pem_.size());
  9509. }
  9510. if (!ca_cert_file_path_.empty()) {
  9511. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  9512. }
  9513. // Client certificates are set through constructor for SSLClient
  9514. // NOTE: SSLClient constructor already takes client_cert_path and
  9515. // client_key_path so we need to create it properly if client certs are
  9516. // needed
  9517. // Execute the redirect
  9518. return detail::redirect(redirect_client, req, res, path, location, error);
  9519. #else
  9520. // SSL not supported - set appropriate error
  9521. error = Error::SSLConnection;
  9522. output_error_log(error, &req);
  9523. return false;
  9524. #endif
  9525. } else {
  9526. // HTTP redirect
  9527. ClientImpl redirect_client(host, port);
  9528. // Setup client with robust configuration
  9529. setup_redirect_client(redirect_client);
  9530. // Execute the redirect
  9531. return detail::redirect(redirect_client, req, res, path, location, error);
  9532. }
  9533. }
  9534. // New method for robust client setup (based on basic_manual_redirect.cpp
  9535. // logic)
  9536. template <typename ClientType>
  9537. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  9538. // Copy basic settings first
  9539. client.set_connection_timeout(connection_timeout_sec_);
  9540. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  9541. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  9542. client.set_keep_alive(keep_alive_);
  9543. client.set_follow_location(
  9544. true); // Enable redirects to handle multi-step redirects
  9545. client.set_path_encode(path_encode_);
  9546. client.set_compress(compress_);
  9547. client.set_decompress(decompress_);
  9548. // Copy authentication settings BEFORE proxy setup
  9549. if (!basic_auth_username_.empty()) {
  9550. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  9551. }
  9552. if (!bearer_token_auth_token_.empty()) {
  9553. client.set_bearer_token_auth(bearer_token_auth_token_);
  9554. }
  9555. #ifdef CPPHTTPLIB_SSL_ENABLED
  9556. if (!digest_auth_username_.empty()) {
  9557. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  9558. }
  9559. #endif
  9560. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  9561. // before proxy auth)
  9562. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9563. // First set proxy host and port
  9564. client.set_proxy(proxy_host_, proxy_port_);
  9565. // Then set proxy authentication (order matters!)
  9566. if (!proxy_basic_auth_username_.empty()) {
  9567. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  9568. proxy_basic_auth_password_);
  9569. }
  9570. if (!proxy_bearer_token_auth_token_.empty()) {
  9571. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  9572. }
  9573. #ifdef CPPHTTPLIB_SSL_ENABLED
  9574. if (!proxy_digest_auth_username_.empty()) {
  9575. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  9576. proxy_digest_auth_password_);
  9577. }
  9578. #endif
  9579. }
  9580. // Copy network and socket settings
  9581. client.set_address_family(address_family_);
  9582. client.set_tcp_nodelay(tcp_nodelay_);
  9583. client.set_ipv6_v6only(ipv6_v6only_);
  9584. if (socket_options_) { client.set_socket_options(socket_options_); }
  9585. if (!interface_.empty()) { client.set_interface(interface_); }
  9586. // Copy logging and headers
  9587. if (logger_) { client.set_logger(logger_); }
  9588. if (error_logger_) { client.set_error_logger(error_logger_); }
  9589. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  9590. // Each new client should generate its own headers based on its target host
  9591. }
  9592. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  9593. const Request &req,
  9594. Error &error) const {
  9595. auto is_shutting_down = []() { return false; };
  9596. if (req.is_chunked_content_provider_) {
  9597. // TODO: Brotli support
  9598. std::unique_ptr<detail::compressor> compressor;
  9599. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9600. if (compress_) {
  9601. compressor = detail::make_unique<detail::gzip_compressor>();
  9602. } else
  9603. #endif
  9604. {
  9605. compressor = detail::make_unique<detail::nocompressor>();
  9606. }
  9607. return detail::write_content_chunked(strm, req.content_provider_,
  9608. is_shutting_down, *compressor, error);
  9609. } else {
  9610. return detail::write_content_with_progress(
  9611. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  9612. req.upload_progress, error);
  9613. }
  9614. }
  9615. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  9616. bool close_connection, Error &error,
  9617. bool skip_body) {
  9618. // Prepare additional headers
  9619. if (close_connection) {
  9620. if (!req.has_header("Connection")) {
  9621. req.set_header("Connection", "close");
  9622. }
  9623. }
  9624. std::string ct_for_defaults;
  9625. if (!req.has_header("Content-Type") && !req.body.empty()) {
  9626. ct_for_defaults = "text/plain";
  9627. }
  9628. prepare_default_headers(req, false, ct_for_defaults);
  9629. if (req.body.empty()) {
  9630. if (req.content_provider_) {
  9631. if (!req.is_chunked_content_provider_) {
  9632. if (!req.has_header("Content-Length")) {
  9633. auto length = std::to_string(req.content_length_);
  9634. req.set_header("Content-Length", length);
  9635. }
  9636. }
  9637. } else {
  9638. if (req.method == "POST" || req.method == "PUT" ||
  9639. req.method == "PATCH") {
  9640. req.set_header("Content-Length", "0");
  9641. }
  9642. }
  9643. }
  9644. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  9645. if (!req.has_header("Authorization")) {
  9646. req.headers.insert(make_basic_authentication_header(
  9647. basic_auth_username_, basic_auth_password_, false));
  9648. }
  9649. }
  9650. if (!proxy_basic_auth_username_.empty() &&
  9651. !proxy_basic_auth_password_.empty()) {
  9652. if (!req.has_header("Proxy-Authorization")) {
  9653. req.headers.insert(make_basic_authentication_header(
  9654. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  9655. }
  9656. }
  9657. if (!bearer_token_auth_token_.empty()) {
  9658. if (!req.has_header("Authorization")) {
  9659. req.headers.insert(make_bearer_token_authentication_header(
  9660. bearer_token_auth_token_, false));
  9661. }
  9662. }
  9663. if (!proxy_bearer_token_auth_token_.empty()) {
  9664. if (!req.has_header("Proxy-Authorization")) {
  9665. req.headers.insert(make_bearer_token_authentication_header(
  9666. proxy_bearer_token_auth_token_, true));
  9667. }
  9668. }
  9669. // Request line and headers
  9670. {
  9671. detail::BufferStream bstrm;
  9672. // Extract path and query from req.path
  9673. std::string path_part, query_part;
  9674. auto query_pos = req.path.find('?');
  9675. if (query_pos != std::string::npos) {
  9676. path_part = req.path.substr(0, query_pos);
  9677. query_part = req.path.substr(query_pos + 1);
  9678. } else {
  9679. path_part = req.path;
  9680. query_part = "";
  9681. }
  9682. // Encode path part. If the original `req.path` already contained a
  9683. // query component, preserve its raw query string (including parameter
  9684. // order) instead of reparsing and reassembling it which may reorder
  9685. // parameters due to container ordering (e.g. `Params` uses
  9686. // `std::multimap`). When there is no query in `req.path`, fall back to
  9687. // building a query from `req.params` so existing callers that pass
  9688. // `Params` continue to work.
  9689. auto path_with_query =
  9690. path_encode_ ? detail::encode_path(path_part) : path_part;
  9691. if (!query_part.empty()) {
  9692. // Normalize the query string (decode then re-encode) while preserving
  9693. // the original parameter order.
  9694. auto normalized = detail::normalize_query_string(query_part);
  9695. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  9696. // Still populate req.params for handlers/users who read them.
  9697. detail::parse_query_text(query_part, req.params);
  9698. } else {
  9699. // No query in path; parse any query_part (empty) and append params
  9700. // from `req.params` when present (preserves prior behavior for
  9701. // callers who provide Params separately).
  9702. detail::parse_query_text(query_part, req.params);
  9703. if (!req.params.empty()) {
  9704. path_with_query = append_query_params(path_with_query, req.params);
  9705. }
  9706. }
  9707. // Write request line and headers
  9708. detail::write_request_line(bstrm, req.method, path_with_query);
  9709. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  9710. error)) {
  9711. output_error_log(error, &req);
  9712. return false;
  9713. }
  9714. // Flush buffer
  9715. auto &data = bstrm.get_buffer();
  9716. if (!detail::write_data(strm, data.data(), data.size())) {
  9717. error = Error::Write;
  9718. output_error_log(error, &req);
  9719. return false;
  9720. }
  9721. }
  9722. // After sending request line and headers, wait briefly for an early server
  9723. // response (e.g. 4xx) and avoid sending a potentially large request body
  9724. // unnecessarily. This workaround is only enabled on Windows because Unix
  9725. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  9726. // buffering can accept large writes even when the peer already responded.
  9727. // Check the stream first (which covers SSL via `is_readable()`), then
  9728. // fall back to select on the socket. Only perform the wait for very large
  9729. // request bodies to avoid interfering with normal small requests and
  9730. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  9731. // response. Skip this check when using Expect: 100-continue, as the protocol
  9732. // handles early responses properly.
  9733. #if defined(_WIN32)
  9734. if (!skip_body &&
  9735. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  9736. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  9737. auto start = std::chrono::high_resolution_clock::now();
  9738. for (;;) {
  9739. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  9740. // from SSL internals. If the underlying socket is readable, assume an
  9741. // early response may be present.
  9742. auto sock = strm.socket();
  9743. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  9744. return false;
  9745. }
  9746. // Fallback to stream-level check for non-socket streams or when the
  9747. // socket isn't reporting readable. Avoid using `is_readable()` for
  9748. // SSL, since `SSL_pending()` may report buffered records that do not
  9749. // indicate a complete application-level response yet.
  9750. if (!is_ssl() && strm.is_readable()) { return false; }
  9751. auto now = std::chrono::high_resolution_clock::now();
  9752. auto elapsed =
  9753. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  9754. .count();
  9755. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  9756. break;
  9757. }
  9758. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  9759. }
  9760. }
  9761. #endif
  9762. // Body
  9763. if (skip_body) { return true; }
  9764. return write_request_body(strm, req, error);
  9765. }
  9766. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  9767. Error &error) {
  9768. if (req.body.empty()) {
  9769. return write_content_with_provider(strm, req, error);
  9770. }
  9771. if (req.upload_progress) {
  9772. auto body_size = req.body.size();
  9773. size_t written = 0;
  9774. auto data = req.body.data();
  9775. while (written < body_size) {
  9776. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  9777. if (!detail::write_data(strm, data + written, to_write)) {
  9778. error = Error::Write;
  9779. output_error_log(error, &req);
  9780. return false;
  9781. }
  9782. written += to_write;
  9783. if (!req.upload_progress(written, body_size)) {
  9784. error = Error::Canceled;
  9785. output_error_log(error, &req);
  9786. return false;
  9787. }
  9788. }
  9789. } else {
  9790. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  9791. error = Error::Write;
  9792. output_error_log(error, &req);
  9793. return false;
  9794. }
  9795. }
  9796. return true;
  9797. }
  9798. inline std::unique_ptr<Response>
  9799. ClientImpl::send_with_content_provider_and_receiver(
  9800. Request &req, const char *body, size_t content_length,
  9801. ContentProvider content_provider,
  9802. ContentProviderWithoutLength content_provider_without_length,
  9803. const std::string &content_type, ContentReceiver content_receiver,
  9804. Error &error) {
  9805. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9806. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9807. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  9808. #endif
  9809. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9810. if (compress_ && !content_provider_without_length) {
  9811. // TODO: Brotli support
  9812. detail::gzip_compressor compressor;
  9813. if (content_provider) {
  9814. auto ok = true;
  9815. size_t offset = 0;
  9816. DataSink data_sink;
  9817. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  9818. if (ok) {
  9819. auto last = offset + data_len == content_length;
  9820. auto ret = compressor.compress(
  9821. data, data_len, last,
  9822. [&](const char *compressed_data, size_t compressed_data_len) {
  9823. req.body.append(compressed_data, compressed_data_len);
  9824. return true;
  9825. });
  9826. if (ret) {
  9827. offset += data_len;
  9828. } else {
  9829. ok = false;
  9830. }
  9831. }
  9832. return ok;
  9833. };
  9834. while (ok && offset < content_length) {
  9835. if (!content_provider(offset, content_length - offset, data_sink)) {
  9836. error = Error::Canceled;
  9837. output_error_log(error, &req);
  9838. return nullptr;
  9839. }
  9840. }
  9841. } else {
  9842. if (!compressor.compress(body, content_length, true,
  9843. [&](const char *data, size_t data_len) {
  9844. req.body.append(data, data_len);
  9845. return true;
  9846. })) {
  9847. error = Error::Compression;
  9848. output_error_log(error, &req);
  9849. return nullptr;
  9850. }
  9851. }
  9852. } else
  9853. #endif
  9854. {
  9855. if (content_provider) {
  9856. req.content_length_ = content_length;
  9857. req.content_provider_ = std::move(content_provider);
  9858. req.is_chunked_content_provider_ = false;
  9859. } else if (content_provider_without_length) {
  9860. req.content_length_ = 0;
  9861. req.content_provider_ = detail::ContentProviderAdapter(
  9862. std::move(content_provider_without_length));
  9863. req.is_chunked_content_provider_ = true;
  9864. req.set_header("Transfer-Encoding", "chunked");
  9865. } else {
  9866. req.body.assign(body, content_length);
  9867. }
  9868. }
  9869. if (content_receiver) {
  9870. req.content_receiver =
  9871. [content_receiver](const char *data, size_t data_length,
  9872. size_t /*offset*/, size_t /*total_length*/) {
  9873. return content_receiver(data, data_length);
  9874. };
  9875. }
  9876. auto res = detail::make_unique<Response>();
  9877. return send(req, *res, error) ? std::move(res) : nullptr;
  9878. }
  9879. inline Result ClientImpl::send_with_content_provider_and_receiver(
  9880. const std::string &method, const std::string &path, const Headers &headers,
  9881. const char *body, size_t content_length, ContentProvider content_provider,
  9882. ContentProviderWithoutLength content_provider_without_length,
  9883. const std::string &content_type, ContentReceiver content_receiver,
  9884. UploadProgress progress) {
  9885. Request req;
  9886. req.method = method;
  9887. req.headers = headers;
  9888. req.path = path;
  9889. req.upload_progress = std::move(progress);
  9890. if (max_timeout_msec_ > 0) {
  9891. req.start_time_ = std::chrono::steady_clock::now();
  9892. }
  9893. auto error = Error::Success;
  9894. auto res = send_with_content_provider_and_receiver(
  9895. req, body, content_length, std::move(content_provider),
  9896. std::move(content_provider_without_length), content_type,
  9897. std::move(content_receiver), error);
  9898. #ifdef CPPHTTPLIB_SSL_ENABLED
  9899. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  9900. last_backend_error_};
  9901. #else
  9902. return Result{std::move(res), error, std::move(req.headers)};
  9903. #endif
  9904. }
  9905. inline void ClientImpl::output_log(const Request &req,
  9906. const Response &res) const {
  9907. if (logger_) {
  9908. std::lock_guard<std::mutex> guard(logger_mutex_);
  9909. logger_(req, res);
  9910. }
  9911. }
  9912. inline void ClientImpl::output_error_log(const Error &err,
  9913. const Request *req) const {
  9914. if (error_logger_) {
  9915. std::lock_guard<std::mutex> guard(logger_mutex_);
  9916. error_logger_(err, req);
  9917. }
  9918. }
  9919. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  9920. Response &res, bool close_connection,
  9921. Error &error) {
  9922. // Auto-add Expect: 100-continue for large bodies
  9923. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  9924. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  9925. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  9926. req.set_header("Expect", "100-continue");
  9927. }
  9928. }
  9929. // Check for Expect: 100-continue
  9930. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  9931. // Send request (skip body if using Expect: 100-continue)
  9932. auto write_request_success =
  9933. write_request(strm, req, close_connection, error, expect_100_continue);
  9934. #ifdef CPPHTTPLIB_SSL_ENABLED
  9935. if (is_ssl() && !expect_100_continue) {
  9936. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  9937. if (!is_proxy_enabled) {
  9938. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  9939. error = Error::SSLPeerCouldBeClosed_;
  9940. output_error_log(error, &req);
  9941. return false;
  9942. }
  9943. }
  9944. }
  9945. #endif
  9946. // Handle Expect: 100-continue with timeout
  9947. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  9948. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  9949. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  9950. auto ret = detail::select_read(strm.socket(), sec, usec);
  9951. if (ret <= 0) {
  9952. // Timeout or error: send body anyway (server didn't respond in time)
  9953. if (!write_request_body(strm, req, error)) { return false; }
  9954. expect_100_continue = false; // Switch to normal response handling
  9955. }
  9956. }
  9957. // Receive response and headers
  9958. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  9959. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  9960. !detail::read_headers(strm, res.headers)) {
  9961. if (write_request_success) { error = Error::Read; }
  9962. output_error_log(error, &req);
  9963. return false;
  9964. }
  9965. if (!write_request_success) { return false; }
  9966. // Handle Expect: 100-continue response
  9967. if (expect_100_continue) {
  9968. if (res.status == StatusCode::Continue_100) {
  9969. // Server accepted, send the body
  9970. if (!write_request_body(strm, req, error)) { return false; }
  9971. // Read the actual response
  9972. res.headers.clear();
  9973. res.body.clear();
  9974. if (!read_response_line(strm, req, res) ||
  9975. !detail::read_headers(strm, res.headers)) {
  9976. error = Error::Read;
  9977. output_error_log(error, &req);
  9978. return false;
  9979. }
  9980. }
  9981. // If not 100 Continue, server returned an error; proceed with that response
  9982. }
  9983. // Body
  9984. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  9985. req.method != "CONNECT") {
  9986. auto redirect = 300 < res.status && res.status < 400 &&
  9987. res.status != StatusCode::NotModified_304 &&
  9988. follow_location_;
  9989. if (req.response_handler && !redirect) {
  9990. if (!req.response_handler(res)) {
  9991. error = Error::Canceled;
  9992. output_error_log(error, &req);
  9993. return false;
  9994. }
  9995. }
  9996. auto out =
  9997. req.content_receiver
  9998. ? static_cast<ContentReceiverWithProgress>(
  9999. [&](const char *buf, size_t n, size_t off, size_t len) {
  10000. if (redirect) { return true; }
  10001. auto ret = req.content_receiver(buf, n, off, len);
  10002. if (!ret) {
  10003. error = Error::Canceled;
  10004. output_error_log(error, &req);
  10005. }
  10006. return ret;
  10007. })
  10008. : static_cast<ContentReceiverWithProgress>(
  10009. [&](const char *buf, size_t n, size_t /*off*/,
  10010. size_t /*len*/) {
  10011. assert(res.body.size() + n <= res.body.max_size());
  10012. res.body.append(buf, n);
  10013. return true;
  10014. });
  10015. auto progress = [&](size_t current, size_t total) {
  10016. if (!req.download_progress || redirect) { return true; }
  10017. auto ret = req.download_progress(current, total);
  10018. if (!ret) {
  10019. error = Error::Canceled;
  10020. output_error_log(error, &req);
  10021. }
  10022. return ret;
  10023. };
  10024. if (res.has_header("Content-Length")) {
  10025. if (!req.content_receiver) {
  10026. auto len = res.get_header_value_u64("Content-Length");
  10027. if (len > res.body.max_size()) {
  10028. error = Error::Read;
  10029. output_error_log(error, &req);
  10030. return false;
  10031. }
  10032. res.body.reserve(static_cast<size_t>(len));
  10033. }
  10034. }
  10035. if (res.status != StatusCode::NotModified_304) {
  10036. int dummy_status;
  10037. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  10038. dummy_status, std::move(progress),
  10039. std::move(out), decompress_)) {
  10040. if (error != Error::Canceled) { error = Error::Read; }
  10041. output_error_log(error, &req);
  10042. return false;
  10043. }
  10044. }
  10045. }
  10046. // Log
  10047. output_log(req, res);
  10048. return true;
  10049. }
  10050. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  10051. const std::string &boundary, const UploadFormDataItems &items,
  10052. const FormDataProviderItems &provider_items) const {
  10053. size_t cur_item = 0;
  10054. size_t cur_start = 0;
  10055. // cur_item and cur_start are copied to within the std::function and
  10056. // maintain state between successive calls
  10057. return [&, cur_item, cur_start](size_t offset,
  10058. DataSink &sink) mutable -> bool {
  10059. if (!offset && !items.empty()) {
  10060. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  10061. return true;
  10062. } else if (cur_item < provider_items.size()) {
  10063. if (!cur_start) {
  10064. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  10065. provider_items[cur_item], boundary);
  10066. offset += begin.size();
  10067. cur_start = offset;
  10068. sink.os << begin;
  10069. }
  10070. DataSink cur_sink;
  10071. auto has_data = true;
  10072. cur_sink.write = sink.write;
  10073. cur_sink.done = [&]() { has_data = false; };
  10074. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  10075. return false;
  10076. }
  10077. if (!has_data) {
  10078. sink.os << detail::serialize_multipart_formdata_item_end();
  10079. cur_item++;
  10080. cur_start = 0;
  10081. }
  10082. return true;
  10083. } else {
  10084. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  10085. sink.done();
  10086. return true;
  10087. }
  10088. };
  10089. }
  10090. inline bool ClientImpl::process_socket(
  10091. const Socket &socket,
  10092. std::chrono::time_point<std::chrono::steady_clock> start_time,
  10093. std::function<bool(Stream &strm)> callback) {
  10094. return detail::process_client_socket(
  10095. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10096. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  10097. }
  10098. inline bool ClientImpl::is_ssl() const { return false; }
  10099. inline Result ClientImpl::Get(const std::string &path,
  10100. DownloadProgress progress) {
  10101. return Get(path, Headers(), std::move(progress));
  10102. }
  10103. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  10104. const Headers &headers,
  10105. DownloadProgress progress) {
  10106. if (params.empty()) { return Get(path, headers); }
  10107. std::string path_with_query = append_query_params(path, params);
  10108. return Get(path_with_query, headers, std::move(progress));
  10109. }
  10110. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  10111. DownloadProgress progress) {
  10112. Request req;
  10113. req.method = "GET";
  10114. req.path = path;
  10115. req.headers = headers;
  10116. req.download_progress = std::move(progress);
  10117. if (max_timeout_msec_ > 0) {
  10118. req.start_time_ = std::chrono::steady_clock::now();
  10119. }
  10120. return send_(std::move(req));
  10121. }
  10122. inline Result ClientImpl::Get(const std::string &path,
  10123. ContentReceiver content_receiver,
  10124. DownloadProgress progress) {
  10125. return Get(path, Headers(), nullptr, std::move(content_receiver),
  10126. std::move(progress));
  10127. }
  10128. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  10129. ContentReceiver content_receiver,
  10130. DownloadProgress progress) {
  10131. return Get(path, headers, nullptr, std::move(content_receiver),
  10132. std::move(progress));
  10133. }
  10134. inline Result ClientImpl::Get(const std::string &path,
  10135. ResponseHandler response_handler,
  10136. ContentReceiver content_receiver,
  10137. DownloadProgress progress) {
  10138. return Get(path, Headers(), std::move(response_handler),
  10139. std::move(content_receiver), std::move(progress));
  10140. }
  10141. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  10142. ResponseHandler response_handler,
  10143. ContentReceiver content_receiver,
  10144. DownloadProgress progress) {
  10145. Request req;
  10146. req.method = "GET";
  10147. req.path = path;
  10148. req.headers = headers;
  10149. req.response_handler = std::move(response_handler);
  10150. req.content_receiver =
  10151. [content_receiver](const char *data, size_t data_length,
  10152. size_t /*offset*/, size_t /*total_length*/) {
  10153. return content_receiver(data, data_length);
  10154. };
  10155. req.download_progress = std::move(progress);
  10156. if (max_timeout_msec_ > 0) {
  10157. req.start_time_ = std::chrono::steady_clock::now();
  10158. }
  10159. return send_(std::move(req));
  10160. }
  10161. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  10162. const Headers &headers,
  10163. ContentReceiver content_receiver,
  10164. DownloadProgress progress) {
  10165. return Get(path, params, headers, nullptr, std::move(content_receiver),
  10166. std::move(progress));
  10167. }
  10168. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  10169. const Headers &headers,
  10170. ResponseHandler response_handler,
  10171. ContentReceiver content_receiver,
  10172. DownloadProgress progress) {
  10173. if (params.empty()) {
  10174. return Get(path, headers, std::move(response_handler),
  10175. std::move(content_receiver), std::move(progress));
  10176. }
  10177. std::string path_with_query = append_query_params(path, params);
  10178. return Get(path_with_query, headers, std::move(response_handler),
  10179. std::move(content_receiver), std::move(progress));
  10180. }
  10181. inline Result ClientImpl::Head(const std::string &path) {
  10182. return Head(path, Headers());
  10183. }
  10184. inline Result ClientImpl::Head(const std::string &path,
  10185. const Headers &headers) {
  10186. Request req;
  10187. req.method = "HEAD";
  10188. req.headers = headers;
  10189. req.path = path;
  10190. if (max_timeout_msec_ > 0) {
  10191. req.start_time_ = std::chrono::steady_clock::now();
  10192. }
  10193. return send_(std::move(req));
  10194. }
  10195. inline Result ClientImpl::Post(const std::string &path) {
  10196. return Post(path, std::string(), std::string());
  10197. }
  10198. inline Result ClientImpl::Post(const std::string &path,
  10199. const Headers &headers) {
  10200. return Post(path, headers, nullptr, 0, std::string());
  10201. }
  10202. inline Result ClientImpl::Post(const std::string &path, const char *body,
  10203. size_t content_length,
  10204. const std::string &content_type,
  10205. UploadProgress progress) {
  10206. return Post(path, Headers(), body, content_length, content_type, progress);
  10207. }
  10208. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  10209. const std::string &content_type,
  10210. UploadProgress progress) {
  10211. return Post(path, Headers(), body, content_type, progress);
  10212. }
  10213. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  10214. return Post(path, Headers(), params);
  10215. }
  10216. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  10217. ContentProvider content_provider,
  10218. const std::string &content_type,
  10219. UploadProgress progress) {
  10220. return Post(path, Headers(), content_length, std::move(content_provider),
  10221. content_type, progress);
  10222. }
  10223. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  10224. ContentProvider content_provider,
  10225. const std::string &content_type,
  10226. ContentReceiver content_receiver,
  10227. UploadProgress progress) {
  10228. return Post(path, Headers(), content_length, std::move(content_provider),
  10229. content_type, std::move(content_receiver), progress);
  10230. }
  10231. inline Result ClientImpl::Post(const std::string &path,
  10232. ContentProviderWithoutLength content_provider,
  10233. const std::string &content_type,
  10234. UploadProgress progress) {
  10235. return Post(path, Headers(), std::move(content_provider), content_type,
  10236. progress);
  10237. }
  10238. inline Result ClientImpl::Post(const std::string &path,
  10239. ContentProviderWithoutLength content_provider,
  10240. const std::string &content_type,
  10241. ContentReceiver content_receiver,
  10242. UploadProgress progress) {
  10243. return Post(path, Headers(), std::move(content_provider), content_type,
  10244. std::move(content_receiver), progress);
  10245. }
  10246. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10247. const Params &params) {
  10248. auto query = detail::params_to_query_str(params);
  10249. return Post(path, headers, query, "application/x-www-form-urlencoded");
  10250. }
  10251. inline Result ClientImpl::Post(const std::string &path,
  10252. const UploadFormDataItems &items,
  10253. UploadProgress progress) {
  10254. return Post(path, Headers(), items, progress);
  10255. }
  10256. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10257. const UploadFormDataItems &items,
  10258. UploadProgress progress) {
  10259. const auto &boundary = detail::make_multipart_data_boundary();
  10260. const auto &content_type =
  10261. detail::serialize_multipart_formdata_get_content_type(boundary);
  10262. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10263. return Post(path, headers, body, content_type, progress);
  10264. }
  10265. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10266. const UploadFormDataItems &items,
  10267. const std::string &boundary,
  10268. UploadProgress progress) {
  10269. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10270. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10271. }
  10272. const auto &content_type =
  10273. detail::serialize_multipart_formdata_get_content_type(boundary);
  10274. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10275. return Post(path, headers, body, content_type, progress);
  10276. }
  10277. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10278. const char *body, size_t content_length,
  10279. const std::string &content_type,
  10280. UploadProgress progress) {
  10281. return send_with_content_provider_and_receiver(
  10282. "POST", path, headers, body, content_length, nullptr, nullptr,
  10283. content_type, nullptr, progress);
  10284. }
  10285. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10286. const std::string &body,
  10287. const std::string &content_type,
  10288. UploadProgress progress) {
  10289. return send_with_content_provider_and_receiver(
  10290. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  10291. content_type, nullptr, progress);
  10292. }
  10293. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10294. size_t content_length,
  10295. ContentProvider content_provider,
  10296. const std::string &content_type,
  10297. UploadProgress progress) {
  10298. return send_with_content_provider_and_receiver(
  10299. "POST", path, headers, nullptr, content_length,
  10300. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10301. }
  10302. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10303. size_t content_length,
  10304. ContentProvider content_provider,
  10305. const std::string &content_type,
  10306. ContentReceiver content_receiver,
  10307. DownloadProgress progress) {
  10308. return send_with_content_provider_and_receiver(
  10309. "POST", path, headers, nullptr, content_length,
  10310. std::move(content_provider), nullptr, content_type,
  10311. std::move(content_receiver), std::move(progress));
  10312. }
  10313. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10314. ContentProviderWithoutLength content_provider,
  10315. const std::string &content_type,
  10316. UploadProgress progress) {
  10317. return send_with_content_provider_and_receiver(
  10318. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10319. content_type, nullptr, progress);
  10320. }
  10321. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10322. ContentProviderWithoutLength content_provider,
  10323. const std::string &content_type,
  10324. ContentReceiver content_receiver,
  10325. DownloadProgress progress) {
  10326. return send_with_content_provider_and_receiver(
  10327. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10328. content_type, std::move(content_receiver), std::move(progress));
  10329. }
  10330. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10331. const UploadFormDataItems &items,
  10332. const FormDataProviderItems &provider_items,
  10333. UploadProgress progress) {
  10334. const auto &boundary = detail::make_multipart_data_boundary();
  10335. const auto &content_type =
  10336. detail::serialize_multipart_formdata_get_content_type(boundary);
  10337. return send_with_content_provider_and_receiver(
  10338. "POST", path, headers, nullptr, 0, nullptr,
  10339. get_multipart_content_provider(boundary, items, provider_items),
  10340. content_type, nullptr, progress);
  10341. }
  10342. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  10343. const std::string &body,
  10344. const std::string &content_type,
  10345. ContentReceiver content_receiver,
  10346. DownloadProgress progress) {
  10347. Request req;
  10348. req.method = "POST";
  10349. req.path = path;
  10350. req.headers = headers;
  10351. req.body = body;
  10352. req.content_receiver =
  10353. [content_receiver](const char *data, size_t data_length,
  10354. size_t /*offset*/, size_t /*total_length*/) {
  10355. return content_receiver(data, data_length);
  10356. };
  10357. req.download_progress = std::move(progress);
  10358. if (max_timeout_msec_ > 0) {
  10359. req.start_time_ = std::chrono::steady_clock::now();
  10360. }
  10361. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10362. return send_(std::move(req));
  10363. }
  10364. inline Result ClientImpl::Put(const std::string &path) {
  10365. return Put(path, std::string(), std::string());
  10366. }
  10367. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  10368. return Put(path, headers, nullptr, 0, std::string());
  10369. }
  10370. inline Result ClientImpl::Put(const std::string &path, const char *body,
  10371. size_t content_length,
  10372. const std::string &content_type,
  10373. UploadProgress progress) {
  10374. return Put(path, Headers(), body, content_length, content_type, progress);
  10375. }
  10376. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  10377. const std::string &content_type,
  10378. UploadProgress progress) {
  10379. return Put(path, Headers(), body, content_type, progress);
  10380. }
  10381. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  10382. return Put(path, Headers(), params);
  10383. }
  10384. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  10385. ContentProvider content_provider,
  10386. const std::string &content_type,
  10387. UploadProgress progress) {
  10388. return Put(path, Headers(), content_length, std::move(content_provider),
  10389. content_type, progress);
  10390. }
  10391. inline Result ClientImpl::Put(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 Put(path, Headers(), content_length, std::move(content_provider),
  10397. content_type, std::move(content_receiver), progress);
  10398. }
  10399. inline Result ClientImpl::Put(const std::string &path,
  10400. ContentProviderWithoutLength content_provider,
  10401. const std::string &content_type,
  10402. UploadProgress progress) {
  10403. return Put(path, Headers(), std::move(content_provider), content_type,
  10404. progress);
  10405. }
  10406. inline Result ClientImpl::Put(const std::string &path,
  10407. ContentProviderWithoutLength content_provider,
  10408. const std::string &content_type,
  10409. ContentReceiver content_receiver,
  10410. UploadProgress progress) {
  10411. return Put(path, Headers(), std::move(content_provider), content_type,
  10412. std::move(content_receiver), progress);
  10413. }
  10414. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10415. const Params &params) {
  10416. auto query = detail::params_to_query_str(params);
  10417. return Put(path, headers, query, "application/x-www-form-urlencoded");
  10418. }
  10419. inline Result ClientImpl::Put(const std::string &path,
  10420. const UploadFormDataItems &items,
  10421. UploadProgress progress) {
  10422. return Put(path, Headers(), items, progress);
  10423. }
  10424. inline Result ClientImpl::Put(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 Put(path, headers, body, content_type, progress);
  10432. }
  10433. inline Result ClientImpl::Put(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 Put(path, headers, body, content_type, progress);
  10444. }
  10445. inline Result ClientImpl::Put(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. "PUT", path, headers, body, content_length, nullptr, nullptr,
  10451. content_type, nullptr, progress);
  10452. }
  10453. inline Result ClientImpl::Put(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. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  10459. content_type, nullptr, progress);
  10460. }
  10461. inline Result ClientImpl::Put(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. "PUT", path, headers, nullptr, content_length,
  10468. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10469. }
  10470. inline Result ClientImpl::Put(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. UploadProgress progress) {
  10476. return send_with_content_provider_and_receiver(
  10477. "PUT", path, headers, nullptr, content_length,
  10478. std::move(content_provider), nullptr, content_type,
  10479. std::move(content_receiver), progress);
  10480. }
  10481. inline Result ClientImpl::Put(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. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10487. content_type, nullptr, progress);
  10488. }
  10489. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10490. ContentProviderWithoutLength content_provider,
  10491. const std::string &content_type,
  10492. ContentReceiver content_receiver,
  10493. UploadProgress progress) {
  10494. return send_with_content_provider_and_receiver(
  10495. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10496. content_type, std::move(content_receiver), progress);
  10497. }
  10498. inline Result ClientImpl::Put(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. "PUT", path, headers, nullptr, 0, nullptr,
  10507. get_multipart_content_provider(boundary, items, provider_items),
  10508. content_type, nullptr, progress);
  10509. }
  10510. inline Result ClientImpl::Put(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 = "PUT";
  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::Patch(const std::string &path) {
  10533. return Patch(path, std::string(), std::string());
  10534. }
  10535. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10536. UploadProgress progress) {
  10537. return Patch(path, headers, nullptr, 0, std::string(), progress);
  10538. }
  10539. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  10540. size_t content_length,
  10541. const std::string &content_type,
  10542. UploadProgress progress) {
  10543. return Patch(path, Headers(), body, content_length, content_type, progress);
  10544. }
  10545. inline Result ClientImpl::Patch(const std::string &path,
  10546. const std::string &body,
  10547. const std::string &content_type,
  10548. UploadProgress progress) {
  10549. return Patch(path, Headers(), body, content_type, progress);
  10550. }
  10551. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  10552. return Patch(path, Headers(), params);
  10553. }
  10554. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10555. ContentProvider content_provider,
  10556. const std::string &content_type,
  10557. UploadProgress progress) {
  10558. return Patch(path, Headers(), content_length, std::move(content_provider),
  10559. content_type, progress);
  10560. }
  10561. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10562. ContentProvider content_provider,
  10563. const std::string &content_type,
  10564. ContentReceiver content_receiver,
  10565. UploadProgress progress) {
  10566. return Patch(path, Headers(), content_length, std::move(content_provider),
  10567. content_type, std::move(content_receiver), progress);
  10568. }
  10569. inline Result ClientImpl::Patch(const std::string &path,
  10570. ContentProviderWithoutLength content_provider,
  10571. const std::string &content_type,
  10572. UploadProgress progress) {
  10573. return Patch(path, Headers(), std::move(content_provider), content_type,
  10574. progress);
  10575. }
  10576. inline Result ClientImpl::Patch(const std::string &path,
  10577. ContentProviderWithoutLength content_provider,
  10578. const std::string &content_type,
  10579. ContentReceiver content_receiver,
  10580. UploadProgress progress) {
  10581. return Patch(path, Headers(), std::move(content_provider), content_type,
  10582. std::move(content_receiver), progress);
  10583. }
  10584. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10585. const Params &params) {
  10586. auto query = detail::params_to_query_str(params);
  10587. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  10588. }
  10589. inline Result ClientImpl::Patch(const std::string &path,
  10590. const UploadFormDataItems &items,
  10591. UploadProgress progress) {
  10592. return Patch(path, Headers(), items, progress);
  10593. }
  10594. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10595. const UploadFormDataItems &items,
  10596. UploadProgress progress) {
  10597. const auto &boundary = detail::make_multipart_data_boundary();
  10598. const auto &content_type =
  10599. detail::serialize_multipart_formdata_get_content_type(boundary);
  10600. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10601. return Patch(path, headers, body, content_type, progress);
  10602. }
  10603. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10604. const UploadFormDataItems &items,
  10605. const std::string &boundary,
  10606. UploadProgress progress) {
  10607. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10608. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10609. }
  10610. const auto &content_type =
  10611. detail::serialize_multipart_formdata_get_content_type(boundary);
  10612. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10613. return Patch(path, headers, body, content_type, progress);
  10614. }
  10615. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10616. const char *body, size_t content_length,
  10617. const std::string &content_type,
  10618. UploadProgress progress) {
  10619. return send_with_content_provider_and_receiver(
  10620. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  10621. content_type, nullptr, progress);
  10622. }
  10623. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10624. const std::string &body,
  10625. const std::string &content_type,
  10626. UploadProgress progress) {
  10627. return send_with_content_provider_and_receiver(
  10628. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  10629. content_type, nullptr, progress);
  10630. }
  10631. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10632. size_t content_length,
  10633. ContentProvider content_provider,
  10634. const std::string &content_type,
  10635. UploadProgress progress) {
  10636. return send_with_content_provider_and_receiver(
  10637. "PATCH", path, headers, nullptr, content_length,
  10638. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10639. }
  10640. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10641. size_t content_length,
  10642. ContentProvider content_provider,
  10643. const std::string &content_type,
  10644. ContentReceiver content_receiver,
  10645. UploadProgress progress) {
  10646. return send_with_content_provider_and_receiver(
  10647. "PATCH", path, headers, nullptr, content_length,
  10648. std::move(content_provider), nullptr, content_type,
  10649. std::move(content_receiver), progress);
  10650. }
  10651. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10652. ContentProviderWithoutLength content_provider,
  10653. const std::string &content_type,
  10654. UploadProgress progress) {
  10655. return send_with_content_provider_and_receiver(
  10656. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10657. content_type, nullptr, progress);
  10658. }
  10659. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10660. ContentProviderWithoutLength content_provider,
  10661. const std::string &content_type,
  10662. ContentReceiver content_receiver,
  10663. UploadProgress progress) {
  10664. return send_with_content_provider_and_receiver(
  10665. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10666. content_type, std::move(content_receiver), progress);
  10667. }
  10668. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10669. const UploadFormDataItems &items,
  10670. const FormDataProviderItems &provider_items,
  10671. UploadProgress progress) {
  10672. const auto &boundary = detail::make_multipart_data_boundary();
  10673. const auto &content_type =
  10674. detail::serialize_multipart_formdata_get_content_type(boundary);
  10675. return send_with_content_provider_and_receiver(
  10676. "PATCH", path, headers, nullptr, 0, nullptr,
  10677. get_multipart_content_provider(boundary, items, provider_items),
  10678. content_type, nullptr, progress);
  10679. }
  10680. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10681. const std::string &body,
  10682. const std::string &content_type,
  10683. ContentReceiver content_receiver,
  10684. DownloadProgress progress) {
  10685. Request req;
  10686. req.method = "PATCH";
  10687. req.path = path;
  10688. req.headers = headers;
  10689. req.body = body;
  10690. req.content_receiver =
  10691. [content_receiver](const char *data, size_t data_length,
  10692. size_t /*offset*/, size_t /*total_length*/) {
  10693. return content_receiver(data, data_length);
  10694. };
  10695. req.download_progress = std::move(progress);
  10696. if (max_timeout_msec_ > 0) {
  10697. req.start_time_ = std::chrono::steady_clock::now();
  10698. }
  10699. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10700. return send_(std::move(req));
  10701. }
  10702. inline Result ClientImpl::Delete(const std::string &path,
  10703. DownloadProgress progress) {
  10704. return Delete(path, Headers(), std::string(), std::string(), progress);
  10705. }
  10706. inline Result ClientImpl::Delete(const std::string &path,
  10707. const Headers &headers,
  10708. DownloadProgress progress) {
  10709. return Delete(path, headers, std::string(), std::string(), progress);
  10710. }
  10711. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  10712. size_t content_length,
  10713. const std::string &content_type,
  10714. DownloadProgress progress) {
  10715. return Delete(path, Headers(), body, content_length, content_type, progress);
  10716. }
  10717. inline Result ClientImpl::Delete(const std::string &path,
  10718. const std::string &body,
  10719. const std::string &content_type,
  10720. DownloadProgress progress) {
  10721. return Delete(path, Headers(), body.data(), body.size(), content_type,
  10722. progress);
  10723. }
  10724. inline Result ClientImpl::Delete(const std::string &path,
  10725. const Headers &headers,
  10726. const std::string &body,
  10727. const std::string &content_type,
  10728. DownloadProgress progress) {
  10729. return Delete(path, headers, body.data(), body.size(), content_type,
  10730. progress);
  10731. }
  10732. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  10733. DownloadProgress progress) {
  10734. return Delete(path, Headers(), params, progress);
  10735. }
  10736. inline Result ClientImpl::Delete(const std::string &path,
  10737. const Headers &headers, const Params &params,
  10738. DownloadProgress progress) {
  10739. auto query = detail::params_to_query_str(params);
  10740. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  10741. progress);
  10742. }
  10743. inline Result ClientImpl::Delete(const std::string &path,
  10744. const Headers &headers, const char *body,
  10745. size_t content_length,
  10746. const std::string &content_type,
  10747. DownloadProgress progress) {
  10748. Request req;
  10749. req.method = "DELETE";
  10750. req.headers = headers;
  10751. req.path = path;
  10752. req.download_progress = std::move(progress);
  10753. if (max_timeout_msec_ > 0) {
  10754. req.start_time_ = std::chrono::steady_clock::now();
  10755. }
  10756. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10757. req.body.assign(body, content_length);
  10758. return send_(std::move(req));
  10759. }
  10760. inline Result ClientImpl::Options(const std::string &path) {
  10761. return Options(path, Headers());
  10762. }
  10763. inline Result ClientImpl::Options(const std::string &path,
  10764. const Headers &headers) {
  10765. Request req;
  10766. req.method = "OPTIONS";
  10767. req.headers = headers;
  10768. req.path = path;
  10769. if (max_timeout_msec_ > 0) {
  10770. req.start_time_ = std::chrono::steady_clock::now();
  10771. }
  10772. return send_(std::move(req));
  10773. }
  10774. inline void ClientImpl::stop() {
  10775. std::lock_guard<std::mutex> guard(socket_mutex_);
  10776. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  10777. // do is to shutdown_socket, so that threads using this socket suddenly
  10778. // discover they can't read/write any more and error out. Everything else
  10779. // (closing the socket, shutting ssl down) is unsafe because these actions
  10780. // are not thread-safe.
  10781. if (socket_requests_in_flight_ > 0) {
  10782. shutdown_socket(socket_);
  10783. // Aside from that, we set a flag for the socket to be closed when we're
  10784. // done.
  10785. socket_should_be_closed_when_request_is_done_ = true;
  10786. return;
  10787. }
  10788. // Otherwise, still holding the mutex, we can shut everything down ourselves
  10789. shutdown_ssl(socket_, true);
  10790. shutdown_socket(socket_);
  10791. close_socket(socket_);
  10792. }
  10793. inline std::string ClientImpl::host() const { return host_; }
  10794. inline int ClientImpl::port() const { return port_; }
  10795. inline size_t ClientImpl::is_socket_open() const {
  10796. std::lock_guard<std::mutex> guard(socket_mutex_);
  10797. return socket_.is_open();
  10798. }
  10799. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  10800. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  10801. connection_timeout_sec_ = sec;
  10802. connection_timeout_usec_ = usec;
  10803. }
  10804. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  10805. read_timeout_sec_ = sec;
  10806. read_timeout_usec_ = usec;
  10807. }
  10808. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  10809. write_timeout_sec_ = sec;
  10810. write_timeout_usec_ = usec;
  10811. }
  10812. inline void ClientImpl::set_max_timeout(time_t msec) {
  10813. max_timeout_msec_ = msec;
  10814. }
  10815. inline void ClientImpl::set_basic_auth(const std::string &username,
  10816. const std::string &password) {
  10817. basic_auth_username_ = username;
  10818. basic_auth_password_ = password;
  10819. }
  10820. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  10821. bearer_token_auth_token_ = token;
  10822. }
  10823. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  10824. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  10825. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  10826. inline void
  10827. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  10828. addr_map_ = std::move(addr_map);
  10829. }
  10830. inline void ClientImpl::set_default_headers(Headers headers) {
  10831. default_headers_ = std::move(headers);
  10832. }
  10833. inline void ClientImpl::set_header_writer(
  10834. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  10835. header_writer_ = writer;
  10836. }
  10837. inline void ClientImpl::set_address_family(int family) {
  10838. address_family_ = family;
  10839. }
  10840. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  10841. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  10842. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  10843. socket_options_ = std::move(socket_options);
  10844. }
  10845. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  10846. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  10847. inline void ClientImpl::set_interface(const std::string &intf) {
  10848. interface_ = intf;
  10849. }
  10850. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  10851. proxy_host_ = host;
  10852. proxy_port_ = port;
  10853. }
  10854. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  10855. const std::string &password) {
  10856. proxy_basic_auth_username_ = username;
  10857. proxy_basic_auth_password_ = password;
  10858. }
  10859. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  10860. proxy_bearer_token_auth_token_ = token;
  10861. }
  10862. #ifdef CPPHTTPLIB_SSL_ENABLED
  10863. inline void ClientImpl::set_digest_auth(const std::string &username,
  10864. const std::string &password) {
  10865. digest_auth_username_ = username;
  10866. digest_auth_password_ = password;
  10867. }
  10868. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  10869. const std::string &ca_cert_dir_path) {
  10870. ca_cert_file_path_ = ca_cert_file_path;
  10871. ca_cert_dir_path_ = ca_cert_dir_path;
  10872. }
  10873. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  10874. const std::string &password) {
  10875. proxy_digest_auth_username_ = username;
  10876. proxy_digest_auth_password_ = password;
  10877. }
  10878. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  10879. server_certificate_verification_ = enabled;
  10880. }
  10881. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  10882. server_hostname_verification_ = enabled;
  10883. }
  10884. #endif
  10885. // ClientImpl::set_ca_cert_store is defined after TLS namespace (uses helpers)
  10886. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10887. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  10888. std::size_t size) const {
  10889. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  10890. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  10891. if (!mem) { return nullptr; }
  10892. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  10893. if (!inf) { return nullptr; }
  10894. auto cts = X509_STORE_new();
  10895. if (cts) {
  10896. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  10897. auto itmp = sk_X509_INFO_value(inf, i);
  10898. if (!itmp) { continue; }
  10899. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  10900. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  10901. }
  10902. }
  10903. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  10904. return cts;
  10905. }
  10906. inline void ClientImpl::set_server_certificate_verifier(
  10907. std::function<SSLVerifierResponse(SSL *ssl)> /*verifier*/) {
  10908. // Base implementation does nothing - SSLClient overrides this
  10909. }
  10910. #endif
  10911. inline void ClientImpl::set_logger(Logger logger) {
  10912. logger_ = std::move(logger);
  10913. }
  10914. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  10915. error_logger_ = std::move(error_logger);
  10916. }
  10917. /*
  10918. * SSL/TLS Common Implementation
  10919. */
  10920. inline ClientConnection::~ClientConnection() {
  10921. #ifdef CPPHTTPLIB_SSL_ENABLED
  10922. if (session) {
  10923. tls::shutdown(session, true);
  10924. tls::free_session(session);
  10925. session = nullptr;
  10926. }
  10927. #endif
  10928. if (sock != INVALID_SOCKET) {
  10929. detail::close_socket(sock);
  10930. sock = INVALID_SOCKET;
  10931. }
  10932. }
  10933. // Universal client implementation
  10934. inline Client::Client(const std::string &scheme_host_port)
  10935. : Client(scheme_host_port, std::string(), std::string()) {}
  10936. inline Client::Client(const std::string &scheme_host_port,
  10937. const std::string &client_cert_path,
  10938. const std::string &client_key_path) {
  10939. const static std::regex re(
  10940. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  10941. std::smatch m;
  10942. if (std::regex_match(scheme_host_port, m, re)) {
  10943. auto scheme = m[1].str();
  10944. #ifdef CPPHTTPLIB_SSL_ENABLED
  10945. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  10946. #else
  10947. if (!scheme.empty() && scheme != "http") {
  10948. #endif
  10949. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10950. std::string msg = "'" + scheme + "' scheme is not supported.";
  10951. throw std::invalid_argument(msg);
  10952. #endif
  10953. return;
  10954. }
  10955. auto is_ssl = scheme == "https";
  10956. auto host = m[2].str();
  10957. if (host.empty()) { host = m[3].str(); }
  10958. auto port_str = m[4].str();
  10959. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  10960. if (is_ssl) {
  10961. #ifdef CPPHTTPLIB_SSL_ENABLED
  10962. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  10963. client_key_path);
  10964. is_ssl_ = is_ssl;
  10965. #endif
  10966. } else {
  10967. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  10968. client_key_path);
  10969. }
  10970. } else {
  10971. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  10972. // if port param below changes.
  10973. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  10974. client_cert_path, client_key_path);
  10975. }
  10976. } // namespace detail
  10977. inline Client::Client(const std::string &host, int port)
  10978. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  10979. inline Client::Client(const std::string &host, int port,
  10980. const std::string &client_cert_path,
  10981. const std::string &client_key_path)
  10982. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  10983. client_key_path)) {}
  10984. inline Client::~Client() = default;
  10985. inline bool Client::is_valid() const {
  10986. return cli_ != nullptr && cli_->is_valid();
  10987. }
  10988. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  10989. return cli_->Get(path, std::move(progress));
  10990. }
  10991. inline Result Client::Get(const std::string &path, const Headers &headers,
  10992. DownloadProgress progress) {
  10993. return cli_->Get(path, headers, std::move(progress));
  10994. }
  10995. inline Result Client::Get(const std::string &path,
  10996. ContentReceiver content_receiver,
  10997. DownloadProgress progress) {
  10998. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  10999. }
  11000. inline Result Client::Get(const std::string &path, const Headers &headers,
  11001. ContentReceiver content_receiver,
  11002. DownloadProgress progress) {
  11003. return cli_->Get(path, headers, std::move(content_receiver),
  11004. std::move(progress));
  11005. }
  11006. inline Result Client::Get(const std::string &path,
  11007. ResponseHandler response_handler,
  11008. ContentReceiver content_receiver,
  11009. DownloadProgress progress) {
  11010. return cli_->Get(path, std::move(response_handler),
  11011. std::move(content_receiver), std::move(progress));
  11012. }
  11013. inline Result Client::Get(const std::string &path, const Headers &headers,
  11014. ResponseHandler response_handler,
  11015. ContentReceiver content_receiver,
  11016. DownloadProgress progress) {
  11017. return cli_->Get(path, headers, std::move(response_handler),
  11018. std::move(content_receiver), std::move(progress));
  11019. }
  11020. inline Result Client::Get(const std::string &path, const Params &params,
  11021. const Headers &headers, DownloadProgress progress) {
  11022. return cli_->Get(path, params, headers, std::move(progress));
  11023. }
  11024. inline Result Client::Get(const std::string &path, const Params &params,
  11025. const Headers &headers,
  11026. ContentReceiver content_receiver,
  11027. DownloadProgress progress) {
  11028. return cli_->Get(path, params, headers, std::move(content_receiver),
  11029. std::move(progress));
  11030. }
  11031. inline Result Client::Get(const std::string &path, const Params &params,
  11032. const Headers &headers,
  11033. ResponseHandler response_handler,
  11034. ContentReceiver content_receiver,
  11035. DownloadProgress progress) {
  11036. return cli_->Get(path, params, headers, std::move(response_handler),
  11037. std::move(content_receiver), std::move(progress));
  11038. }
  11039. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  11040. inline Result Client::Head(const std::string &path, const Headers &headers) {
  11041. return cli_->Head(path, headers);
  11042. }
  11043. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  11044. inline Result Client::Post(const std::string &path, const Headers &headers) {
  11045. return cli_->Post(path, headers);
  11046. }
  11047. inline Result Client::Post(const std::string &path, const char *body,
  11048. size_t content_length,
  11049. const std::string &content_type,
  11050. UploadProgress progress) {
  11051. return cli_->Post(path, body, content_length, content_type, progress);
  11052. }
  11053. inline Result Client::Post(const std::string &path, const Headers &headers,
  11054. const char *body, size_t content_length,
  11055. const std::string &content_type,
  11056. UploadProgress progress) {
  11057. return cli_->Post(path, headers, body, content_length, content_type,
  11058. progress);
  11059. }
  11060. inline Result Client::Post(const std::string &path, const std::string &body,
  11061. const std::string &content_type,
  11062. UploadProgress progress) {
  11063. return cli_->Post(path, body, content_type, progress);
  11064. }
  11065. inline Result Client::Post(const std::string &path, const Headers &headers,
  11066. const std::string &body,
  11067. const std::string &content_type,
  11068. UploadProgress progress) {
  11069. return cli_->Post(path, headers, body, content_type, progress);
  11070. }
  11071. inline Result Client::Post(const std::string &path, size_t content_length,
  11072. ContentProvider content_provider,
  11073. const std::string &content_type,
  11074. UploadProgress progress) {
  11075. return cli_->Post(path, content_length, std::move(content_provider),
  11076. content_type, progress);
  11077. }
  11078. inline Result Client::Post(const std::string &path, size_t content_length,
  11079. ContentProvider content_provider,
  11080. const std::string &content_type,
  11081. ContentReceiver content_receiver,
  11082. UploadProgress progress) {
  11083. return cli_->Post(path, content_length, std::move(content_provider),
  11084. content_type, std::move(content_receiver), progress);
  11085. }
  11086. inline Result Client::Post(const std::string &path,
  11087. ContentProviderWithoutLength content_provider,
  11088. const std::string &content_type,
  11089. UploadProgress progress) {
  11090. return cli_->Post(path, std::move(content_provider), content_type, progress);
  11091. }
  11092. inline Result Client::Post(const std::string &path,
  11093. ContentProviderWithoutLength content_provider,
  11094. const std::string &content_type,
  11095. ContentReceiver content_receiver,
  11096. UploadProgress progress) {
  11097. return cli_->Post(path, std::move(content_provider), content_type,
  11098. std::move(content_receiver), progress);
  11099. }
  11100. inline Result Client::Post(const std::string &path, const Headers &headers,
  11101. size_t content_length,
  11102. ContentProvider content_provider,
  11103. const std::string &content_type,
  11104. UploadProgress progress) {
  11105. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11106. content_type, progress);
  11107. }
  11108. inline Result Client::Post(const std::string &path, const Headers &headers,
  11109. size_t content_length,
  11110. ContentProvider content_provider,
  11111. const std::string &content_type,
  11112. ContentReceiver content_receiver,
  11113. DownloadProgress progress) {
  11114. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11115. content_type, std::move(content_receiver), progress);
  11116. }
  11117. inline Result Client::Post(const std::string &path, const Headers &headers,
  11118. ContentProviderWithoutLength content_provider,
  11119. const std::string &content_type,
  11120. UploadProgress progress) {
  11121. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11122. progress);
  11123. }
  11124. inline Result Client::Post(const std::string &path, const Headers &headers,
  11125. ContentProviderWithoutLength content_provider,
  11126. const std::string &content_type,
  11127. ContentReceiver content_receiver,
  11128. DownloadProgress progress) {
  11129. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11130. std::move(content_receiver), progress);
  11131. }
  11132. inline Result Client::Post(const std::string &path, const Params &params) {
  11133. return cli_->Post(path, params);
  11134. }
  11135. inline Result Client::Post(const std::string &path, const Headers &headers,
  11136. const Params &params) {
  11137. return cli_->Post(path, headers, params);
  11138. }
  11139. inline Result Client::Post(const std::string &path,
  11140. const UploadFormDataItems &items,
  11141. UploadProgress progress) {
  11142. return cli_->Post(path, items, progress);
  11143. }
  11144. inline Result Client::Post(const std::string &path, const Headers &headers,
  11145. const UploadFormDataItems &items,
  11146. UploadProgress progress) {
  11147. return cli_->Post(path, headers, items, progress);
  11148. }
  11149. inline Result Client::Post(const std::string &path, const Headers &headers,
  11150. const UploadFormDataItems &items,
  11151. const std::string &boundary,
  11152. UploadProgress progress) {
  11153. return cli_->Post(path, headers, items, boundary, progress);
  11154. }
  11155. inline Result Client::Post(const std::string &path, const Headers &headers,
  11156. const UploadFormDataItems &items,
  11157. const FormDataProviderItems &provider_items,
  11158. UploadProgress progress) {
  11159. return cli_->Post(path, headers, items, provider_items, progress);
  11160. }
  11161. inline Result Client::Post(const std::string &path, const Headers &headers,
  11162. const std::string &body,
  11163. const std::string &content_type,
  11164. ContentReceiver content_receiver,
  11165. DownloadProgress progress) {
  11166. return cli_->Post(path, headers, body, content_type,
  11167. std::move(content_receiver), progress);
  11168. }
  11169. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  11170. inline Result Client::Put(const std::string &path, const Headers &headers) {
  11171. return cli_->Put(path, headers);
  11172. }
  11173. inline Result Client::Put(const std::string &path, const char *body,
  11174. size_t content_length,
  11175. const std::string &content_type,
  11176. UploadProgress progress) {
  11177. return cli_->Put(path, body, content_length, content_type, progress);
  11178. }
  11179. inline Result Client::Put(const std::string &path, const Headers &headers,
  11180. const char *body, size_t content_length,
  11181. const std::string &content_type,
  11182. UploadProgress progress) {
  11183. return cli_->Put(path, headers, body, content_length, content_type, progress);
  11184. }
  11185. inline Result Client::Put(const std::string &path, const std::string &body,
  11186. const std::string &content_type,
  11187. UploadProgress progress) {
  11188. return cli_->Put(path, body, content_type, progress);
  11189. }
  11190. inline Result Client::Put(const std::string &path, const Headers &headers,
  11191. const std::string &body,
  11192. const std::string &content_type,
  11193. UploadProgress progress) {
  11194. return cli_->Put(path, headers, body, content_type, progress);
  11195. }
  11196. inline Result Client::Put(const std::string &path, size_t content_length,
  11197. ContentProvider content_provider,
  11198. const std::string &content_type,
  11199. UploadProgress progress) {
  11200. return cli_->Put(path, content_length, std::move(content_provider),
  11201. content_type, progress);
  11202. }
  11203. inline Result Client::Put(const std::string &path, size_t content_length,
  11204. ContentProvider content_provider,
  11205. const std::string &content_type,
  11206. ContentReceiver content_receiver,
  11207. UploadProgress progress) {
  11208. return cli_->Put(path, content_length, std::move(content_provider),
  11209. content_type, std::move(content_receiver), progress);
  11210. }
  11211. inline Result Client::Put(const std::string &path,
  11212. ContentProviderWithoutLength content_provider,
  11213. const std::string &content_type,
  11214. UploadProgress progress) {
  11215. return cli_->Put(path, std::move(content_provider), content_type, progress);
  11216. }
  11217. inline Result Client::Put(const std::string &path,
  11218. ContentProviderWithoutLength content_provider,
  11219. const std::string &content_type,
  11220. ContentReceiver content_receiver,
  11221. UploadProgress progress) {
  11222. return cli_->Put(path, std::move(content_provider), content_type,
  11223. std::move(content_receiver), progress);
  11224. }
  11225. inline Result Client::Put(const std::string &path, const Headers &headers,
  11226. size_t content_length,
  11227. ContentProvider content_provider,
  11228. const std::string &content_type,
  11229. UploadProgress progress) {
  11230. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11231. content_type, progress);
  11232. }
  11233. inline Result Client::Put(const std::string &path, const Headers &headers,
  11234. size_t content_length,
  11235. ContentProvider content_provider,
  11236. const std::string &content_type,
  11237. ContentReceiver content_receiver,
  11238. UploadProgress progress) {
  11239. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11240. content_type, std::move(content_receiver), progress);
  11241. }
  11242. inline Result Client::Put(const std::string &path, const Headers &headers,
  11243. ContentProviderWithoutLength content_provider,
  11244. const std::string &content_type,
  11245. UploadProgress progress) {
  11246. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11247. progress);
  11248. }
  11249. inline Result Client::Put(const std::string &path, const Headers &headers,
  11250. ContentProviderWithoutLength content_provider,
  11251. const std::string &content_type,
  11252. ContentReceiver content_receiver,
  11253. UploadProgress progress) {
  11254. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11255. std::move(content_receiver), progress);
  11256. }
  11257. inline Result Client::Put(const std::string &path, const Params &params) {
  11258. return cli_->Put(path, params);
  11259. }
  11260. inline Result Client::Put(const std::string &path, const Headers &headers,
  11261. const Params &params) {
  11262. return cli_->Put(path, headers, params);
  11263. }
  11264. inline Result Client::Put(const std::string &path,
  11265. const UploadFormDataItems &items,
  11266. UploadProgress progress) {
  11267. return cli_->Put(path, items, progress);
  11268. }
  11269. inline Result Client::Put(const std::string &path, const Headers &headers,
  11270. const UploadFormDataItems &items,
  11271. UploadProgress progress) {
  11272. return cli_->Put(path, headers, items, progress);
  11273. }
  11274. inline Result Client::Put(const std::string &path, const Headers &headers,
  11275. const UploadFormDataItems &items,
  11276. const std::string &boundary,
  11277. UploadProgress progress) {
  11278. return cli_->Put(path, headers, items, boundary, progress);
  11279. }
  11280. inline Result Client::Put(const std::string &path, const Headers &headers,
  11281. const UploadFormDataItems &items,
  11282. const FormDataProviderItems &provider_items,
  11283. UploadProgress progress) {
  11284. return cli_->Put(path, headers, items, provider_items, progress);
  11285. }
  11286. inline Result Client::Put(const std::string &path, const Headers &headers,
  11287. const std::string &body,
  11288. const std::string &content_type,
  11289. ContentReceiver content_receiver,
  11290. DownloadProgress progress) {
  11291. return cli_->Put(path, headers, body, content_type, content_receiver,
  11292. progress);
  11293. }
  11294. inline Result Client::Patch(const std::string &path) {
  11295. return cli_->Patch(path);
  11296. }
  11297. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  11298. return cli_->Patch(path, headers);
  11299. }
  11300. inline Result Client::Patch(const std::string &path, const char *body,
  11301. size_t content_length,
  11302. const std::string &content_type,
  11303. UploadProgress progress) {
  11304. return cli_->Patch(path, body, content_length, content_type, progress);
  11305. }
  11306. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11307. const char *body, size_t content_length,
  11308. const std::string &content_type,
  11309. UploadProgress progress) {
  11310. return cli_->Patch(path, headers, body, content_length, content_type,
  11311. progress);
  11312. }
  11313. inline Result Client::Patch(const std::string &path, const std::string &body,
  11314. const std::string &content_type,
  11315. UploadProgress progress) {
  11316. return cli_->Patch(path, body, content_type, progress);
  11317. }
  11318. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11319. const std::string &body,
  11320. const std::string &content_type,
  11321. UploadProgress progress) {
  11322. return cli_->Patch(path, headers, body, content_type, progress);
  11323. }
  11324. inline Result Client::Patch(const std::string &path, size_t content_length,
  11325. ContentProvider content_provider,
  11326. const std::string &content_type,
  11327. UploadProgress progress) {
  11328. return cli_->Patch(path, content_length, std::move(content_provider),
  11329. content_type, progress);
  11330. }
  11331. inline Result Client::Patch(const std::string &path, size_t content_length,
  11332. ContentProvider content_provider,
  11333. const std::string &content_type,
  11334. ContentReceiver content_receiver,
  11335. UploadProgress progress) {
  11336. return cli_->Patch(path, content_length, std::move(content_provider),
  11337. content_type, std::move(content_receiver), progress);
  11338. }
  11339. inline Result Client::Patch(const std::string &path,
  11340. ContentProviderWithoutLength content_provider,
  11341. const std::string &content_type,
  11342. UploadProgress progress) {
  11343. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  11344. }
  11345. inline Result Client::Patch(const std::string &path,
  11346. ContentProviderWithoutLength content_provider,
  11347. const std::string &content_type,
  11348. ContentReceiver content_receiver,
  11349. UploadProgress progress) {
  11350. return cli_->Patch(path, std::move(content_provider), content_type,
  11351. std::move(content_receiver), progress);
  11352. }
  11353. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11354. size_t content_length,
  11355. ContentProvider content_provider,
  11356. const std::string &content_type,
  11357. UploadProgress progress) {
  11358. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11359. content_type, progress);
  11360. }
  11361. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11362. size_t content_length,
  11363. ContentProvider content_provider,
  11364. const std::string &content_type,
  11365. ContentReceiver content_receiver,
  11366. UploadProgress progress) {
  11367. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11368. content_type, std::move(content_receiver), progress);
  11369. }
  11370. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11371. ContentProviderWithoutLength content_provider,
  11372. const std::string &content_type,
  11373. UploadProgress progress) {
  11374. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11375. progress);
  11376. }
  11377. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11378. ContentProviderWithoutLength content_provider,
  11379. const std::string &content_type,
  11380. ContentReceiver content_receiver,
  11381. UploadProgress progress) {
  11382. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11383. std::move(content_receiver), progress);
  11384. }
  11385. inline Result Client::Patch(const std::string &path, const Params &params) {
  11386. return cli_->Patch(path, params);
  11387. }
  11388. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11389. const Params &params) {
  11390. return cli_->Patch(path, headers, params);
  11391. }
  11392. inline Result Client::Patch(const std::string &path,
  11393. const UploadFormDataItems &items,
  11394. UploadProgress progress) {
  11395. return cli_->Patch(path, items, progress);
  11396. }
  11397. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11398. const UploadFormDataItems &items,
  11399. UploadProgress progress) {
  11400. return cli_->Patch(path, headers, items, progress);
  11401. }
  11402. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11403. const UploadFormDataItems &items,
  11404. const std::string &boundary,
  11405. UploadProgress progress) {
  11406. return cli_->Patch(path, headers, items, boundary, progress);
  11407. }
  11408. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11409. const UploadFormDataItems &items,
  11410. const FormDataProviderItems &provider_items,
  11411. UploadProgress progress) {
  11412. return cli_->Patch(path, headers, items, provider_items, progress);
  11413. }
  11414. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11415. const std::string &body,
  11416. const std::string &content_type,
  11417. ContentReceiver content_receiver,
  11418. DownloadProgress progress) {
  11419. return cli_->Patch(path, headers, body, content_type, content_receiver,
  11420. progress);
  11421. }
  11422. inline Result Client::Delete(const std::string &path,
  11423. DownloadProgress progress) {
  11424. return cli_->Delete(path, progress);
  11425. }
  11426. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11427. DownloadProgress progress) {
  11428. return cli_->Delete(path, headers, progress);
  11429. }
  11430. inline Result Client::Delete(const std::string &path, const char *body,
  11431. size_t content_length,
  11432. const std::string &content_type,
  11433. DownloadProgress progress) {
  11434. return cli_->Delete(path, body, content_length, content_type, progress);
  11435. }
  11436. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11437. const char *body, size_t content_length,
  11438. const std::string &content_type,
  11439. DownloadProgress progress) {
  11440. return cli_->Delete(path, headers, body, content_length, content_type,
  11441. progress);
  11442. }
  11443. inline Result Client::Delete(const std::string &path, const std::string &body,
  11444. const std::string &content_type,
  11445. DownloadProgress progress) {
  11446. return cli_->Delete(path, body, content_type, progress);
  11447. }
  11448. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11449. const std::string &body,
  11450. const std::string &content_type,
  11451. DownloadProgress progress) {
  11452. return cli_->Delete(path, headers, body, content_type, progress);
  11453. }
  11454. inline Result Client::Delete(const std::string &path, const Params &params,
  11455. DownloadProgress progress) {
  11456. return cli_->Delete(path, params, progress);
  11457. }
  11458. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11459. const Params &params, DownloadProgress progress) {
  11460. return cli_->Delete(path, headers, params, progress);
  11461. }
  11462. inline Result Client::Options(const std::string &path) {
  11463. return cli_->Options(path);
  11464. }
  11465. inline Result Client::Options(const std::string &path, const Headers &headers) {
  11466. return cli_->Options(path, headers);
  11467. }
  11468. inline ClientImpl::StreamHandle
  11469. Client::open_stream(const std::string &method, const std::string &path,
  11470. const Params &params, const Headers &headers,
  11471. const std::string &body, const std::string &content_type) {
  11472. return cli_->open_stream(method, path, params, headers, body, content_type);
  11473. }
  11474. inline bool Client::send(Request &req, Response &res, Error &error) {
  11475. return cli_->send(req, res, error);
  11476. }
  11477. inline Result Client::send(const Request &req) { return cli_->send(req); }
  11478. inline void Client::stop() { cli_->stop(); }
  11479. inline std::string Client::host() const { return cli_->host(); }
  11480. inline int Client::port() const { return cli_->port(); }
  11481. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  11482. inline socket_t Client::socket() const { return cli_->socket(); }
  11483. inline void
  11484. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  11485. cli_->set_hostname_addr_map(std::move(addr_map));
  11486. }
  11487. inline void Client::set_default_headers(Headers headers) {
  11488. cli_->set_default_headers(std::move(headers));
  11489. }
  11490. inline void Client::set_header_writer(
  11491. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11492. cli_->set_header_writer(writer);
  11493. }
  11494. inline void Client::set_address_family(int family) {
  11495. cli_->set_address_family(family);
  11496. }
  11497. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  11498. inline void Client::set_socket_options(SocketOptions socket_options) {
  11499. cli_->set_socket_options(std::move(socket_options));
  11500. }
  11501. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  11502. cli_->set_connection_timeout(sec, usec);
  11503. }
  11504. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  11505. cli_->set_read_timeout(sec, usec);
  11506. }
  11507. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  11508. cli_->set_write_timeout(sec, usec);
  11509. }
  11510. inline void Client::set_basic_auth(const std::string &username,
  11511. const std::string &password) {
  11512. cli_->set_basic_auth(username, password);
  11513. }
  11514. inline void Client::set_bearer_token_auth(const std::string &token) {
  11515. cli_->set_bearer_token_auth(token);
  11516. }
  11517. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  11518. inline void Client::set_follow_location(bool on) {
  11519. cli_->set_follow_location(on);
  11520. }
  11521. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  11522. [[deprecated("Use set_path_encode instead")]]
  11523. inline void Client::set_url_encode(bool on) {
  11524. cli_->set_path_encode(on);
  11525. }
  11526. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  11527. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  11528. inline void Client::set_interface(const std::string &intf) {
  11529. cli_->set_interface(intf);
  11530. }
  11531. inline void Client::set_proxy(const std::string &host, int port) {
  11532. cli_->set_proxy(host, port);
  11533. }
  11534. inline void Client::set_proxy_basic_auth(const std::string &username,
  11535. const std::string &password) {
  11536. cli_->set_proxy_basic_auth(username, password);
  11537. }
  11538. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  11539. cli_->set_proxy_bearer_token_auth(token);
  11540. }
  11541. inline void Client::set_logger(Logger logger) {
  11542. cli_->set_logger(std::move(logger));
  11543. }
  11544. inline void Client::set_error_logger(ErrorLogger error_logger) {
  11545. cli_->set_error_logger(std::move(error_logger));
  11546. }
  11547. /*
  11548. * Group 6: SSL Server and Client implementation
  11549. */
  11550. #ifdef CPPHTTPLIB_SSL_ENABLED
  11551. // SSL HTTP server implementation
  11552. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  11553. const char *client_ca_cert_file_path,
  11554. const char *client_ca_cert_dir_path,
  11555. const char *private_key_password) {
  11556. using namespace tls;
  11557. ctx_ = create_server_context();
  11558. if (!ctx_) { return; }
  11559. // Load server certificate and private key
  11560. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  11561. private_key_password)) {
  11562. last_ssl_error_ = static_cast<int>(get_error());
  11563. free_context(ctx_);
  11564. ctx_ = nullptr;
  11565. return;
  11566. }
  11567. // Load client CA certificates for client authentication
  11568. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  11569. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  11570. client_ca_cert_dir_path)) {
  11571. last_ssl_error_ = static_cast<int>(get_error());
  11572. free_context(ctx_);
  11573. ctx_ = nullptr;
  11574. return;
  11575. }
  11576. // Enable client certificate verification
  11577. set_verify_client(ctx_, true);
  11578. }
  11579. }
  11580. inline SSLServer::SSLServer(const PemMemory &pem) {
  11581. using namespace tls;
  11582. ctx_ = create_server_context();
  11583. if (ctx_) {
  11584. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  11585. pem.private_key_password)) {
  11586. last_ssl_error_ = static_cast<int>(get_error());
  11587. free_context(ctx_);
  11588. ctx_ = nullptr;
  11589. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  11590. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  11591. last_ssl_error_ = static_cast<int>(get_error());
  11592. free_context(ctx_);
  11593. ctx_ = nullptr;
  11594. } else {
  11595. set_verify_client(ctx_, true);
  11596. }
  11597. }
  11598. }
  11599. }
  11600. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  11601. using namespace tls;
  11602. ctx_ = create_server_context();
  11603. if (ctx_) {
  11604. if (!setup_callback(ctx_)) {
  11605. free_context(ctx_);
  11606. ctx_ = nullptr;
  11607. }
  11608. }
  11609. }
  11610. inline SSLServer::~SSLServer() {
  11611. if (ctx_) { tls::free_context(ctx_); }
  11612. }
  11613. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  11614. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  11615. using namespace tls;
  11616. // Create TLS session with mutex protection
  11617. session_t session = nullptr;
  11618. {
  11619. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11620. session = create_session(static_cast<ctx_t>(ctx_), sock);
  11621. }
  11622. if (!session) {
  11623. last_ssl_error_ = static_cast<int>(get_error());
  11624. detail::shutdown_socket(sock);
  11625. detail::close_socket(sock);
  11626. return false;
  11627. }
  11628. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  11629. bool handshake_done = false;
  11630. bool ret = false;
  11631. auto cleanup = detail::scope_exit([&] {
  11632. // Shutdown gracefully if handshake succeeded and processing was successful
  11633. if (handshake_done) { shutdown(session, ret); }
  11634. free_session(session);
  11635. detail::shutdown_socket(sock);
  11636. detail::close_socket(sock);
  11637. });
  11638. // Perform TLS accept handshake with timeout
  11639. TlsError tls_err;
  11640. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  11641. &tls_err)) {
  11642. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11643. // Map TlsError to legacy ssl_error for backward compatibility
  11644. if (tls_err.code == ErrorCode::WantRead) {
  11645. last_ssl_error_ = SSL_ERROR_WANT_READ;
  11646. } else if (tls_err.code == ErrorCode::WantWrite) {
  11647. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  11648. } else {
  11649. last_ssl_error_ = SSL_ERROR_SSL;
  11650. }
  11651. #else
  11652. last_ssl_error_ = static_cast<int>(get_error());
  11653. #endif
  11654. return false;
  11655. }
  11656. handshake_done = true;
  11657. std::string remote_addr;
  11658. int remote_port = 0;
  11659. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  11660. std::string local_addr;
  11661. int local_port = 0;
  11662. detail::get_local_ip_and_port(sock, local_addr, local_port);
  11663. ret = detail::process_server_socket_ssl(
  11664. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  11665. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11666. write_timeout_usec_,
  11667. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  11668. return process_request(strm, remote_addr, remote_port, local_addr,
  11669. local_port, close_connection, connection_closed,
  11670. [&](Request &req) { req.ssl = session; });
  11671. });
  11672. return ret;
  11673. }
  11674. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  11675. const char *key_pem,
  11676. const char *client_ca_pem,
  11677. const char *password) {
  11678. if (!ctx_) { return false; }
  11679. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11680. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  11681. return false;
  11682. }
  11683. if (client_ca_pem) {
  11684. return tls::update_server_client_ca(ctx_, client_ca_pem);
  11685. }
  11686. return true;
  11687. }
  11688. // SSL HTTP client implementation
  11689. inline SSLClient::~SSLClient() {
  11690. if (ctx_) { tls::free_context(ctx_); }
  11691. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  11692. // base function rather than the derived function once we get to the
  11693. // base class destructor, and won't free the SSL (causing a leak).
  11694. shutdown_ssl_impl(socket_, true);
  11695. }
  11696. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  11697. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  11698. shutdown_ssl_impl(socket, shutdown_gracefully);
  11699. }
  11700. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  11701. bool shutdown_gracefully) {
  11702. if (socket.sock == INVALID_SOCKET) {
  11703. assert(socket.ssl == nullptr);
  11704. return;
  11705. }
  11706. if (socket.ssl) {
  11707. tls::shutdown(socket.ssl, shutdown_gracefully);
  11708. {
  11709. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11710. tls::free_session(socket.ssl);
  11711. }
  11712. socket.ssl = nullptr;
  11713. }
  11714. assert(socket.ssl == nullptr);
  11715. }
  11716. inline bool SSLClient::process_socket(
  11717. const Socket &socket,
  11718. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11719. std::function<bool(Stream &strm)> callback) {
  11720. assert(socket.ssl);
  11721. return detail::process_client_socket_ssl(
  11722. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  11723. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  11724. std::move(callback));
  11725. }
  11726. inline bool SSLClient::is_ssl() const { return true; }
  11727. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  11728. if (!is_valid()) {
  11729. error = Error::SSLConnection;
  11730. return false;
  11731. }
  11732. return ClientImpl::create_and_connect_socket(socket, error);
  11733. }
  11734. // Assumes that socket_mutex_ is locked and that there are no requests in
  11735. // flight
  11736. inline bool SSLClient::connect_with_proxy(
  11737. Socket &socket,
  11738. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11739. Response &res, bool &success, Error &error) {
  11740. success = true;
  11741. Response proxy_res;
  11742. if (!detail::process_client_socket(
  11743. socket.sock, read_timeout_sec_, read_timeout_usec_,
  11744. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  11745. start_time, [&](Stream &strm) {
  11746. Request req2;
  11747. req2.method = "CONNECT";
  11748. req2.path =
  11749. detail::make_host_and_port_string_always_port(host_, port_);
  11750. if (max_timeout_msec_ > 0) {
  11751. req2.start_time_ = std::chrono::steady_clock::now();
  11752. }
  11753. return process_request(strm, req2, proxy_res, false, error);
  11754. })) {
  11755. // Thread-safe to close everything because we are assuming there are no
  11756. // requests in flight
  11757. shutdown_ssl(socket, true);
  11758. shutdown_socket(socket);
  11759. close_socket(socket);
  11760. success = false;
  11761. return false;
  11762. }
  11763. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  11764. if (!proxy_digest_auth_username_.empty() &&
  11765. !proxy_digest_auth_password_.empty()) {
  11766. std::map<std::string, std::string> auth;
  11767. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  11768. // Close the current socket and create a new one for the authenticated
  11769. // request
  11770. shutdown_ssl(socket, true);
  11771. shutdown_socket(socket);
  11772. close_socket(socket);
  11773. // Create a new socket for the authenticated CONNECT request
  11774. if (!ensure_socket_connection(socket, error)) {
  11775. success = false;
  11776. output_error_log(error, nullptr);
  11777. return false;
  11778. }
  11779. proxy_res = Response();
  11780. if (!detail::process_client_socket(
  11781. socket.sock, read_timeout_sec_, read_timeout_usec_,
  11782. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  11783. start_time, [&](Stream &strm) {
  11784. Request req3;
  11785. req3.method = "CONNECT";
  11786. req3.path = detail::make_host_and_port_string_always_port(
  11787. host_, port_);
  11788. req3.headers.insert(detail::make_digest_authentication_header(
  11789. req3, auth, 1, detail::random_string(10),
  11790. proxy_digest_auth_username_, proxy_digest_auth_password_,
  11791. true));
  11792. if (max_timeout_msec_ > 0) {
  11793. req3.start_time_ = std::chrono::steady_clock::now();
  11794. }
  11795. return process_request(strm, req3, proxy_res, false, error);
  11796. })) {
  11797. // Thread-safe to close everything because we are assuming there are
  11798. // no requests in flight
  11799. shutdown_ssl(socket, true);
  11800. shutdown_socket(socket);
  11801. close_socket(socket);
  11802. success = false;
  11803. return false;
  11804. }
  11805. }
  11806. }
  11807. }
  11808. // If status code is not 200, proxy request is failed.
  11809. // Set error to ProxyConnection and return proxy response
  11810. // as the response of the request
  11811. if (proxy_res.status != StatusCode::OK_200) {
  11812. error = Error::ProxyConnection;
  11813. output_error_log(error, nullptr);
  11814. res = std::move(proxy_res);
  11815. // Thread-safe to close everything because we are assuming there are
  11816. // no requests in flight
  11817. shutdown_ssl(socket, true);
  11818. shutdown_socket(socket);
  11819. close_socket(socket);
  11820. return false;
  11821. }
  11822. return true;
  11823. }
  11824. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  11825. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  11826. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  11827. if (!initialize_ssl(socket, error)) {
  11828. shutdown_socket(socket);
  11829. close_socket(socket);
  11830. return false;
  11831. }
  11832. return true;
  11833. }
  11834. // SSL HTTP client implementation
  11835. inline SSLClient::SSLClient(const std::string &host)
  11836. : SSLClient(host, 443, std::string(), std::string()) {}
  11837. inline SSLClient::SSLClient(const std::string &host, int port)
  11838. : SSLClient(host, port, std::string(), std::string()) {}
  11839. inline SSLClient::SSLClient(const std::string &host, int port,
  11840. const std::string &client_cert_path,
  11841. const std::string &client_key_path,
  11842. const std::string &private_key_password)
  11843. : ClientImpl(host, port, client_cert_path, client_key_path) {
  11844. ctx_ = tls::create_client_context();
  11845. if (!ctx_) { return; }
  11846. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  11847. if (!client_cert_path.empty() && !client_key_path.empty()) {
  11848. const char *password =
  11849. private_key_password.empty() ? nullptr : private_key_password.c_str();
  11850. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  11851. client_key_path.c_str(), password)) {
  11852. last_backend_error_ = tls::get_error();
  11853. tls::free_context(ctx_);
  11854. ctx_ = nullptr;
  11855. }
  11856. }
  11857. }
  11858. inline SSLClient::SSLClient(const std::string &host, int port,
  11859. const PemMemory &pem)
  11860. : ClientImpl(host, port) {
  11861. ctx_ = tls::create_client_context();
  11862. if (!ctx_) { return; }
  11863. tls::set_min_version(ctx_, tls::Version::TLS1_2);
  11864. if (pem.cert_pem && pem.key_pem) {
  11865. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  11866. pem.private_key_password)) {
  11867. last_backend_error_ = tls::get_error();
  11868. tls::free_context(ctx_);
  11869. ctx_ = nullptr;
  11870. }
  11871. }
  11872. }
  11873. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  11874. if (ca_cert_store && ctx_) {
  11875. // set_ca_store takes ownership of ca_cert_store
  11876. tls::set_ca_store(ctx_, ca_cert_store);
  11877. } else if (ca_cert_store) {
  11878. tls::free_ca_store(ca_cert_store);
  11879. }
  11880. }
  11881. inline void
  11882. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  11883. if (!ctx_) { return; }
  11884. tls::set_verify_callback(ctx_, verifier);
  11885. }
  11886. inline void SSLClient::set_session_verifier(
  11887. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  11888. session_verifier_ = std::move(verifier);
  11889. }
  11890. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  11891. std::size_t size) {
  11892. if (ctx_ && ca_cert && size > 0) {
  11893. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  11894. tls::load_ca_pem(ctx_, ca_cert, size);
  11895. }
  11896. }
  11897. inline bool SSLClient::load_certs() {
  11898. auto ret = true;
  11899. std::call_once(initialize_cert_, [&]() {
  11900. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11901. if (!ca_cert_file_path_.empty()) {
  11902. if (!tls::load_ca_file(ctx_, ca_cert_file_path_.c_str())) {
  11903. last_backend_error_ = tls::get_error();
  11904. ret = false;
  11905. }
  11906. } else if (!ca_cert_dir_path_.empty()) {
  11907. if (!tls::load_ca_dir(ctx_, ca_cert_dir_path_.c_str())) {
  11908. last_backend_error_ = tls::get_error();
  11909. ret = false;
  11910. }
  11911. } else if (ca_cert_pem_.empty()) {
  11912. if (!tls::load_system_certs(ctx_)) {
  11913. last_backend_error_ = tls::get_error();
  11914. }
  11915. }
  11916. });
  11917. return ret;
  11918. }
  11919. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  11920. using namespace tls;
  11921. // Load CA certificates if server verification is enabled
  11922. if (server_certificate_verification_) {
  11923. if (!load_certs()) {
  11924. error = Error::SSLLoadingCerts;
  11925. output_error_log(error, nullptr);
  11926. return false;
  11927. }
  11928. }
  11929. bool is_ip = detail::is_ip_address(host_);
  11930. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  11931. // MbedTLS needs explicit verification mode (OpenSSL uses SSL_VERIFY_NONE
  11932. // by default and performs all verification post-handshake).
  11933. // For IP addresses with verification enabled, use OPTIONAL mode since
  11934. // MbedTLS requires hostname for VERIFY_REQUIRED.
  11935. if (is_ip && server_certificate_verification_) {
  11936. set_verify_client(ctx_, false);
  11937. } else {
  11938. set_verify_client(ctx_, server_certificate_verification_);
  11939. }
  11940. #endif
  11941. // Create TLS session
  11942. session_t session = nullptr;
  11943. {
  11944. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11945. session = create_session(ctx_, socket.sock);
  11946. }
  11947. if (!session) {
  11948. error = Error::SSLConnection;
  11949. last_backend_error_ = get_error();
  11950. return false;
  11951. }
  11952. // Use scope_exit to ensure session is freed on error paths
  11953. bool success = false;
  11954. auto session_guard = detail::scope_exit([&] {
  11955. if (!success) { free_session(session); }
  11956. });
  11957. // Set SNI extension (skip for IP addresses per RFC 6066).
  11958. // On MbedTLS, set_sni also enables hostname verification internally.
  11959. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  11960. if (!is_ip) {
  11961. if (!set_sni(session, host_.c_str())) {
  11962. error = Error::SSLConnection;
  11963. last_backend_error_ = get_error();
  11964. return false;
  11965. }
  11966. }
  11967. // Perform non-blocking TLS handshake with timeout
  11968. TlsError tls_err;
  11969. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  11970. connection_timeout_usec_, &tls_err)) {
  11971. last_ssl_error_ = static_cast<int>(tls_err.code);
  11972. last_backend_error_ = tls_err.backend_code;
  11973. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  11974. error = Error::SSLServerVerification;
  11975. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  11976. error = Error::SSLServerHostnameVerification;
  11977. } else {
  11978. error = Error::SSLConnection;
  11979. }
  11980. output_error_log(error, nullptr);
  11981. return false;
  11982. }
  11983. // Post-handshake session verifier callback
  11984. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  11985. if (session_verifier_) { verification_status = session_verifier_(session); }
  11986. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  11987. last_backend_error_ = get_error();
  11988. error = Error::SSLServerVerification;
  11989. output_error_log(error, nullptr);
  11990. return false;
  11991. }
  11992. // Default server certificate verification
  11993. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  11994. server_certificate_verification_) {
  11995. verify_result_ = tls::get_verify_result(session);
  11996. if (verify_result_ != 0) {
  11997. last_backend_error_ = static_cast<unsigned long>(verify_result_);
  11998. error = Error::SSLServerVerification;
  11999. output_error_log(error, nullptr);
  12000. return false;
  12001. }
  12002. auto server_cert = get_peer_cert(session);
  12003. if (!server_cert) {
  12004. last_backend_error_ = get_error();
  12005. error = Error::SSLServerVerification;
  12006. output_error_log(error, nullptr);
  12007. return false;
  12008. }
  12009. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  12010. // Hostname verification (post-handshake for all cases).
  12011. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  12012. // On MbedTLS, set_sni already enabled hostname verification during
  12013. // handshake for non-IP hosts, but this check is still needed for IP
  12014. // addresses where SNI is not set.
  12015. if (server_hostname_verification_) {
  12016. if (!verify_hostname(server_cert, host_.c_str())) {
  12017. last_backend_error_ = hostname_mismatch_code();
  12018. error = Error::SSLServerHostnameVerification;
  12019. output_error_log(error, nullptr);
  12020. return false;
  12021. }
  12022. }
  12023. }
  12024. success = true;
  12025. socket.ssl = session;
  12026. return true;
  12027. }
  12028. inline void Client::set_digest_auth(const std::string &username,
  12029. const std::string &password) {
  12030. cli_->set_digest_auth(username, password);
  12031. }
  12032. inline void Client::set_proxy_digest_auth(const std::string &username,
  12033. const std::string &password) {
  12034. cli_->set_proxy_digest_auth(username, password);
  12035. }
  12036. inline void Client::enable_server_certificate_verification(bool enabled) {
  12037. cli_->enable_server_certificate_verification(enabled);
  12038. }
  12039. inline void Client::enable_server_hostname_verification(bool enabled) {
  12040. cli_->enable_server_hostname_verification(enabled);
  12041. }
  12042. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  12043. const std::string &ca_cert_dir_path) {
  12044. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  12045. }
  12046. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  12047. if (is_ssl_) {
  12048. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  12049. } else if (ca_cert_store) {
  12050. tls::free_ca_store(ca_cert_store);
  12051. }
  12052. }
  12053. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  12054. set_ca_cert_store(tls::create_ca_store(ca_cert, size));
  12055. }
  12056. inline void
  12057. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  12058. if (is_ssl_) {
  12059. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  12060. std::move(verifier));
  12061. }
  12062. }
  12063. inline void Client::set_session_verifier(
  12064. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  12065. if (is_ssl_) {
  12066. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  12067. }
  12068. }
  12069. inline tls::ctx_t Client::tls_context() const {
  12070. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  12071. return nullptr;
  12072. }
  12073. #endif // CPPHTTPLIB_SSL_ENABLED
  12074. /*
  12075. * Group 7: TLS abstraction layer - Common API
  12076. */
  12077. #ifdef CPPHTTPLIB_SSL_ENABLED
  12078. namespace tls {
  12079. // Helper for PeerCert construction
  12080. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  12081. return PeerCert(get_peer_cert(session));
  12082. }
  12083. namespace impl {
  12084. inline VerifyCallback &get_verify_callback() {
  12085. static thread_local VerifyCallback callback;
  12086. return callback;
  12087. }
  12088. inline VerifyCallback &get_mbedtls_verify_callback() {
  12089. static thread_local VerifyCallback callback;
  12090. return callback;
  12091. }
  12092. } // namespace impl
  12093. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  12094. const char *ca_dir) {
  12095. if (!ctx) { return false; }
  12096. bool success = true;
  12097. if (ca_file && *ca_file) {
  12098. if (!load_ca_file(ctx, ca_file)) { success = false; }
  12099. }
  12100. if (ca_dir && *ca_dir) {
  12101. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  12102. }
  12103. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12104. // Set CA list for client certificate request (CertificateRequest message)
  12105. if (ca_file && *ca_file) {
  12106. auto list = SSL_load_client_CA_file(ca_file);
  12107. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  12108. }
  12109. #endif
  12110. return success;
  12111. }
  12112. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  12113. const char *password) {
  12114. return set_client_cert_pem(ctx, cert, key, password);
  12115. }
  12116. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  12117. const char *key_path, const char *password) {
  12118. return set_client_cert_file(ctx, cert_path, key_path, password);
  12119. }
  12120. // PeerCert implementation
  12121. inline PeerCert::PeerCert() = default;
  12122. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  12123. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  12124. other.cert_ = nullptr;
  12125. }
  12126. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  12127. if (this != &other) {
  12128. if (cert_) { free_cert(cert_); }
  12129. cert_ = other.cert_;
  12130. other.cert_ = nullptr;
  12131. }
  12132. return *this;
  12133. }
  12134. inline PeerCert::~PeerCert() {
  12135. if (cert_) { free_cert(cert_); }
  12136. }
  12137. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  12138. inline std::string PeerCert::subject_cn() const {
  12139. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  12140. }
  12141. inline std::string PeerCert::issuer_name() const {
  12142. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  12143. }
  12144. inline bool PeerCert::check_hostname(const char *hostname) const {
  12145. return cert_ ? verify_hostname(cert_, hostname) : false;
  12146. }
  12147. inline std::vector<SanEntry> PeerCert::sans() const {
  12148. std::vector<SanEntry> result;
  12149. if (cert_) { get_cert_sans(cert_, result); }
  12150. return result;
  12151. }
  12152. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  12153. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  12154. }
  12155. inline std::string PeerCert::serial() const {
  12156. return cert_ ? get_cert_serial(cert_) : std::string();
  12157. }
  12158. // VerifyContext method implementations
  12159. inline std::string VerifyContext::subject_cn() const {
  12160. return cert ? get_cert_subject_cn(cert) : std::string();
  12161. }
  12162. inline std::string VerifyContext::issuer_name() const {
  12163. return cert ? get_cert_issuer_name(cert) : std::string();
  12164. }
  12165. inline bool VerifyContext::check_hostname(const char *hostname) const {
  12166. return cert ? verify_hostname(cert, hostname) : false;
  12167. }
  12168. inline std::vector<SanEntry> VerifyContext::sans() const {
  12169. std::vector<SanEntry> result;
  12170. if (cert) { get_cert_sans(cert, result); }
  12171. return result;
  12172. }
  12173. inline bool VerifyContext::validity(time_t &not_before,
  12174. time_t &not_after) const {
  12175. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  12176. }
  12177. inline std::string VerifyContext::serial() const {
  12178. return cert ? get_cert_serial(cert) : std::string();
  12179. }
  12180. // TlsError static method implementation
  12181. inline std::string TlsError::verify_error_to_string(long error_code) {
  12182. return verify_error_string(error_code);
  12183. }
  12184. } // namespace tls
  12185. // Request::peer_cert() implementation
  12186. inline tls::PeerCert Request::peer_cert() const {
  12187. return tls::get_peer_cert_from_session(ssl);
  12188. }
  12189. // Request::sni() implementation
  12190. inline std::string Request::sni() const {
  12191. if (!ssl) { return std::string(); }
  12192. const char *s = tls::get_sni(ssl);
  12193. return s ? std::string(s) : std::string();
  12194. }
  12195. #endif // CPPHTTPLIB_SSL_ENABLED
  12196. /*
  12197. * Group 8: TLS abstraction layer - OpenSSL backend
  12198. */
  12199. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12200. inline SSL_CTX *Client::ssl_context() const {
  12201. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  12202. return nullptr;
  12203. }
  12204. inline void Client::set_server_certificate_verifier(
  12205. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  12206. cli_->set_server_certificate_verifier(verifier);
  12207. }
  12208. inline long Client::get_verify_result() const {
  12209. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).get_verify_result(); }
  12210. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  12211. }
  12212. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  12213. /*
  12214. * OpenSSL Backend Implementation
  12215. */
  12216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12217. namespace tls {
  12218. namespace impl {
  12219. // OpenSSL-specific helpers for converting native types to PEM
  12220. inline std::string x509_to_pem(X509 *cert) {
  12221. if (!cert) return {};
  12222. BIO *bio = BIO_new(BIO_s_mem());
  12223. if (!bio) return {};
  12224. if (PEM_write_bio_X509(bio, cert) != 1) {
  12225. BIO_free(bio);
  12226. return {};
  12227. }
  12228. char *data = nullptr;
  12229. long len = BIO_get_mem_data(bio, &data);
  12230. std::string pem(data, static_cast<size_t>(len));
  12231. BIO_free(bio);
  12232. return pem;
  12233. }
  12234. inline std::string evp_pkey_to_pem(EVP_PKEY *key) {
  12235. if (!key) return {};
  12236. BIO *bio = BIO_new(BIO_s_mem());
  12237. if (!bio) return {};
  12238. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr,
  12239. nullptr) != 1) {
  12240. BIO_free(bio);
  12241. return {};
  12242. }
  12243. char *data = nullptr;
  12244. long len = BIO_get_mem_data(bio, &data);
  12245. std::string pem(data, static_cast<size_t>(len));
  12246. BIO_free(bio);
  12247. return pem;
  12248. }
  12249. inline std::string x509_store_to_pem(X509_STORE *store) {
  12250. if (!store) return {};
  12251. std::string pem;
  12252. auto objs = X509_STORE_get0_objects(store);
  12253. if (!objs) return {};
  12254. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  12255. auto obj = sk_X509_OBJECT_value(objs, i);
  12256. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  12257. auto cert = X509_OBJECT_get0_X509(obj);
  12258. if (cert) { pem += x509_to_pem(cert); }
  12259. }
  12260. }
  12261. return pem;
  12262. }
  12263. // Helper to map OpenSSL SSL_get_error to ErrorCode
  12264. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  12265. switch (ssl_error) {
  12266. case SSL_ERROR_NONE: return ErrorCode::Success;
  12267. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  12268. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  12269. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  12270. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  12271. case SSL_ERROR_SSL:
  12272. default: return ErrorCode::Fatal;
  12273. }
  12274. }
  12275. // Helper: Create client CA list from PEM string
  12276. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  12277. // Caller takes ownership of returned list
  12278. inline STACK_OF(X509_NAME) *
  12279. create_client_ca_list_from_pem(const char *ca_pem) {
  12280. if (!ca_pem) { return nullptr; }
  12281. auto ca_list = sk_X509_NAME_new_null();
  12282. if (!ca_list) { return nullptr; }
  12283. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  12284. if (!bio) {
  12285. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  12286. return nullptr;
  12287. }
  12288. X509 *cert = nullptr;
  12289. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  12290. nullptr) {
  12291. X509_NAME *name = X509_get_subject_name(cert);
  12292. if (name) { sk_X509_NAME_push(ca_list, X509_NAME_dup(name)); }
  12293. X509_free(cert);
  12294. }
  12295. BIO_free(bio);
  12296. return ca_list;
  12297. }
  12298. // Helper: Extract CA names from X509_STORE
  12299. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  12300. // Caller takes ownership of returned list
  12301. inline STACK_OF(X509_NAME) *
  12302. extract_client_ca_list_from_store(X509_STORE *store) {
  12303. if (!store) { return nullptr; }
  12304. auto ca_list = sk_X509_NAME_new_null();
  12305. if (!ca_list) { return nullptr; }
  12306. auto objs = X509_STORE_get0_objects(store);
  12307. if (!objs) {
  12308. sk_X509_NAME_free(ca_list);
  12309. return nullptr;
  12310. }
  12311. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  12312. auto obj = sk_X509_OBJECT_value(objs, i);
  12313. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  12314. auto cert = X509_OBJECT_get0_X509(obj);
  12315. if (cert) {
  12316. auto subject = X509_get_subject_name(cert);
  12317. if (subject) {
  12318. auto name_dup = X509_NAME_dup(subject);
  12319. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  12320. }
  12321. }
  12322. }
  12323. }
  12324. if (sk_X509_NAME_num(ca_list) == 0) {
  12325. sk_X509_NAME_free(ca_list);
  12326. return nullptr;
  12327. }
  12328. return ca_list;
  12329. }
  12330. // OpenSSL verify callback wrapper
  12331. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  12332. auto &callback = get_verify_callback();
  12333. if (!callback) { return preverify_ok; }
  12334. // Get SSL object from X509_STORE_CTX
  12335. auto ssl = static_cast<SSL *>(
  12336. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  12337. if (!ssl) { return preverify_ok; }
  12338. // Get current certificate and depth
  12339. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  12340. int depth = X509_STORE_CTX_get_error_depth(ctx);
  12341. int error = X509_STORE_CTX_get_error(ctx);
  12342. // Build context
  12343. VerifyContext verify_ctx;
  12344. verify_ctx.session = static_cast<session_t>(ssl);
  12345. verify_ctx.cert = static_cast<cert_t>(cert);
  12346. verify_ctx.depth = depth;
  12347. verify_ctx.preverify_ok = (preverify_ok != 0);
  12348. verify_ctx.error_code = error;
  12349. verify_ctx.error_string =
  12350. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  12351. return callback(verify_ctx) ? 1 : 0;
  12352. }
  12353. } // namespace impl
  12354. inline ctx_t create_client_context() {
  12355. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  12356. if (ctx) {
  12357. // Disable auto-retry to properly handle non-blocking I/O
  12358. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  12359. // Set minimum TLS version
  12360. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  12361. }
  12362. return static_cast<ctx_t>(ctx);
  12363. }
  12364. inline void free_context(ctx_t ctx) {
  12365. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  12366. }
  12367. inline bool set_min_version(ctx_t ctx, Version version) {
  12368. if (!ctx) return false;
  12369. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  12370. static_cast<int>(version)) == 1;
  12371. }
  12372. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  12373. if (!ctx || !pem || len == 0) return false;
  12374. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12375. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12376. if (!store) return false;
  12377. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  12378. if (!bio) return false;
  12379. bool ok = true;
  12380. X509 *cert = nullptr;
  12381. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  12382. nullptr) {
  12383. if (X509_STORE_add_cert(store, cert) != 1) {
  12384. // Ignore duplicate errors
  12385. auto err = ERR_peek_last_error();
  12386. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  12387. ok = false;
  12388. }
  12389. }
  12390. X509_free(cert);
  12391. if (!ok) break;
  12392. }
  12393. BIO_free(bio);
  12394. // Clear any "no more certificates" errors
  12395. ERR_clear_error();
  12396. return ok;
  12397. }
  12398. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  12399. if (!ctx || !file_path) return false;
  12400. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  12401. nullptr) == 1;
  12402. }
  12403. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  12404. if (!ctx || !dir_path) return false;
  12405. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  12406. dir_path) == 1;
  12407. }
  12408. inline bool load_system_certs(ctx_t ctx) {
  12409. if (!ctx) return false;
  12410. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12411. #ifdef _WIN32
  12412. // Windows: Load from system certificate store
  12413. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12414. if (!store) return false;
  12415. auto hStore = CertOpenSystemStoreW(NULL, L"ROOT");
  12416. if (!hStore) return false;
  12417. bool loaded_any = false;
  12418. PCCERT_CONTEXT pContext = nullptr;
  12419. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  12420. nullptr) {
  12421. const unsigned char *data = pContext->pbCertEncoded;
  12422. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  12423. if (x509) {
  12424. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  12425. X509_free(x509);
  12426. }
  12427. }
  12428. CertCloseStore(hStore, 0);
  12429. return loaded_any;
  12430. #elif defined(__APPLE__)
  12431. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  12432. // macOS: Load from Keychain
  12433. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12434. if (!store) return false;
  12435. CFArrayRef certs = nullptr;
  12436. if (SecTrustCopyAnchorCertificates(&certs) != errSecSuccess || !certs) {
  12437. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12438. }
  12439. bool loaded_any = false;
  12440. auto count = CFArrayGetCount(certs);
  12441. for (CFIndex i = 0; i < count; i++) {
  12442. auto cert = reinterpret_cast<SecCertificateRef>(
  12443. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  12444. CFDataRef der = SecCertificateCopyData(cert);
  12445. if (der) {
  12446. const unsigned char *data = CFDataGetBytePtr(der);
  12447. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  12448. if (x509) {
  12449. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  12450. X509_free(x509);
  12451. }
  12452. CFRelease(der);
  12453. }
  12454. }
  12455. CFRelease(certs);
  12456. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12457. #else
  12458. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12459. #endif
  12460. #else
  12461. // Other Unix: use default verify paths
  12462. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  12463. #endif
  12464. }
  12465. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  12466. const char *password) {
  12467. if (!ctx || !cert || !key) return false;
  12468. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12469. // Load certificate
  12470. auto cert_bio = BIO_new_mem_buf(cert, -1);
  12471. if (!cert_bio) return false;
  12472. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  12473. BIO_free(cert_bio);
  12474. if (!x509) return false;
  12475. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  12476. X509_free(x509);
  12477. if (!cert_ok) return false;
  12478. // Load private key
  12479. auto key_bio = BIO_new_mem_buf(key, -1);
  12480. if (!key_bio) return false;
  12481. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  12482. password ? const_cast<char *>(password)
  12483. : nullptr);
  12484. BIO_free(key_bio);
  12485. if (!pkey) return false;
  12486. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  12487. EVP_PKEY_free(pkey);
  12488. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  12489. }
  12490. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  12491. const char *key_path, const char *password) {
  12492. if (!ctx || !cert_path || !key_path) return false;
  12493. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12494. if (password && password[0] != '\0') {
  12495. SSL_CTX_set_default_passwd_cb_userdata(
  12496. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  12497. }
  12498. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  12499. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  12500. }
  12501. inline ctx_t create_server_context() {
  12502. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12503. if (ctx) {
  12504. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  12505. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12506. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  12507. }
  12508. return static_cast<ctx_t>(ctx);
  12509. }
  12510. inline void set_verify_client(ctx_t ctx, bool require) {
  12511. if (!ctx) return;
  12512. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  12513. require
  12514. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  12515. : SSL_VERIFY_NONE,
  12516. nullptr);
  12517. }
  12518. inline session_t create_session(ctx_t ctx, socket_t sock) {
  12519. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  12520. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12521. SSL *ssl = SSL_new(ssl_ctx);
  12522. if (!ssl) return nullptr;
  12523. // Disable auto-retry for proper non-blocking I/O handling
  12524. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  12525. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  12526. if (!bio) {
  12527. SSL_free(ssl);
  12528. return nullptr;
  12529. }
  12530. SSL_set_bio(ssl, bio, bio);
  12531. return static_cast<session_t>(ssl);
  12532. }
  12533. inline void free_session(session_t session) {
  12534. if (session) { SSL_free(static_cast<SSL *>(session)); }
  12535. }
  12536. inline bool set_sni(session_t session, const char *hostname) {
  12537. if (!session || !hostname) return false;
  12538. auto ssl = static_cast<SSL *>(session);
  12539. // Set SNI (Server Name Indication) only - does not enable verification
  12540. #if defined(OPENSSL_IS_BORINGSSL)
  12541. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  12542. #else
  12543. // Direct call instead of macro to suppress -Wold-style-cast warning
  12544. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  12545. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  12546. #endif
  12547. }
  12548. inline bool set_hostname(session_t session, const char *hostname) {
  12549. if (!session || !hostname) return false;
  12550. auto ssl = static_cast<SSL *>(session);
  12551. // Set SNI (Server Name Indication)
  12552. if (!set_sni(session, hostname)) { return false; }
  12553. // Enable hostname verification
  12554. auto param = SSL_get0_param(ssl);
  12555. if (!param) return false;
  12556. X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  12557. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  12558. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  12559. return true;
  12560. }
  12561. inline TlsError connect(session_t session) {
  12562. if (!session) { return TlsError(); }
  12563. auto ssl = static_cast<SSL *>(session);
  12564. auto ret = SSL_connect(ssl);
  12565. TlsError err;
  12566. if (ret == 1) {
  12567. err.code = ErrorCode::Success;
  12568. } else {
  12569. auto ssl_err = SSL_get_error(ssl, ret);
  12570. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12571. err.backend_code = ERR_get_error();
  12572. }
  12573. return err;
  12574. }
  12575. inline TlsError accept(session_t session) {
  12576. if (!session) { return TlsError(); }
  12577. auto ssl = static_cast<SSL *>(session);
  12578. auto ret = SSL_accept(ssl);
  12579. TlsError err;
  12580. if (ret == 1) {
  12581. err.code = ErrorCode::Success;
  12582. } else {
  12583. auto ssl_err = SSL_get_error(ssl, ret);
  12584. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12585. err.backend_code = ERR_get_error();
  12586. }
  12587. return err;
  12588. }
  12589. inline bool connect_nonblocking(session_t session, socket_t sock,
  12590. time_t timeout_sec, time_t timeout_usec,
  12591. TlsError *err) {
  12592. if (!session) {
  12593. if (err) { err->code = ErrorCode::Fatal; }
  12594. return false;
  12595. }
  12596. auto ssl = static_cast<SSL *>(session);
  12597. auto bio = SSL_get_rbio(ssl);
  12598. // Set non-blocking mode for handshake
  12599. detail::set_nonblocking(sock, true);
  12600. if (bio) { BIO_set_nbio(bio, 1); }
  12601. auto cleanup = detail::scope_exit([&]() {
  12602. // Restore blocking mode after handshake
  12603. if (bio) { BIO_set_nbio(bio, 0); }
  12604. detail::set_nonblocking(sock, false);
  12605. });
  12606. auto res = 0;
  12607. while ((res = SSL_connect(ssl)) != 1) {
  12608. auto ssl_err = SSL_get_error(ssl, res);
  12609. switch (ssl_err) {
  12610. case SSL_ERROR_WANT_READ:
  12611. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  12612. continue;
  12613. }
  12614. break;
  12615. case SSL_ERROR_WANT_WRITE:
  12616. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  12617. continue;
  12618. }
  12619. break;
  12620. default: break;
  12621. }
  12622. if (err) {
  12623. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  12624. err->backend_code = ERR_get_error();
  12625. }
  12626. return false;
  12627. }
  12628. if (err) { err->code = ErrorCode::Success; }
  12629. return true;
  12630. }
  12631. inline bool accept_nonblocking(session_t session, socket_t sock,
  12632. time_t timeout_sec, time_t timeout_usec,
  12633. TlsError *err) {
  12634. if (!session) {
  12635. if (err) { err->code = ErrorCode::Fatal; }
  12636. return false;
  12637. }
  12638. auto ssl = static_cast<SSL *>(session);
  12639. auto bio = SSL_get_rbio(ssl);
  12640. // Set non-blocking mode for handshake
  12641. detail::set_nonblocking(sock, true);
  12642. if (bio) { BIO_set_nbio(bio, 1); }
  12643. auto cleanup = detail::scope_exit([&]() {
  12644. // Restore blocking mode after handshake
  12645. if (bio) { BIO_set_nbio(bio, 0); }
  12646. detail::set_nonblocking(sock, false);
  12647. });
  12648. auto res = 0;
  12649. while ((res = SSL_accept(ssl)) != 1) {
  12650. auto ssl_err = SSL_get_error(ssl, res);
  12651. switch (ssl_err) {
  12652. case SSL_ERROR_WANT_READ:
  12653. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  12654. continue;
  12655. }
  12656. break;
  12657. case SSL_ERROR_WANT_WRITE:
  12658. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  12659. continue;
  12660. }
  12661. break;
  12662. default: break;
  12663. }
  12664. if (err) {
  12665. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  12666. err->backend_code = ERR_get_error();
  12667. }
  12668. return false;
  12669. }
  12670. if (err) { err->code = ErrorCode::Success; }
  12671. return true;
  12672. }
  12673. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  12674. if (!session || !buf) {
  12675. err.code = ErrorCode::Fatal;
  12676. return -1;
  12677. }
  12678. auto ssl = static_cast<SSL *>(session);
  12679. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  12680. if (ret > 0) {
  12681. err.code = ErrorCode::Success;
  12682. return ret;
  12683. }
  12684. auto ssl_err = SSL_get_error(ssl, ret);
  12685. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12686. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  12687. return -1;
  12688. }
  12689. inline ssize_t write(session_t session, const void *buf, size_t len,
  12690. TlsError &err) {
  12691. if (!session || !buf) {
  12692. err.code = ErrorCode::Fatal;
  12693. return -1;
  12694. }
  12695. auto ssl = static_cast<SSL *>(session);
  12696. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  12697. if (ret > 0) {
  12698. err.code = ErrorCode::Success;
  12699. return ret;
  12700. }
  12701. auto ssl_err = SSL_get_error(ssl, ret);
  12702. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  12703. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  12704. return -1;
  12705. }
  12706. inline int pending(const_session_t session) {
  12707. if (!session) return 0;
  12708. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  12709. }
  12710. inline void shutdown(session_t session, bool graceful) {
  12711. if (!session) return;
  12712. auto ssl = static_cast<SSL *>(session);
  12713. if (graceful) {
  12714. // First call sends close_notify
  12715. if (SSL_shutdown(ssl) == 0) {
  12716. // Second call waits for peer's close_notify
  12717. SSL_shutdown(ssl);
  12718. }
  12719. }
  12720. }
  12721. inline bool is_peer_closed(session_t session, socket_t sock) {
  12722. if (!session) return true;
  12723. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  12724. detail::set_nonblocking(sock, true);
  12725. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  12726. auto ssl = static_cast<SSL *>(session);
  12727. char buf;
  12728. auto ret = SSL_peek(ssl, &buf, 1);
  12729. if (ret > 0) return false;
  12730. auto err = SSL_get_error(ssl, ret);
  12731. return err == SSL_ERROR_ZERO_RETURN;
  12732. }
  12733. inline cert_t get_peer_cert(const_session_t session) {
  12734. if (!session) return nullptr;
  12735. return static_cast<cert_t>(SSL_get1_peer_certificate(
  12736. static_cast<SSL *>(const_cast<void *>(session))));
  12737. }
  12738. inline void free_cert(cert_t cert) {
  12739. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  12740. }
  12741. inline bool verify_hostname(cert_t cert, const char *hostname) {
  12742. if (!cert || !hostname) return false;
  12743. auto x509 = static_cast<X509 *>(cert);
  12744. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  12745. if (detail::is_ip_address(hostname)) {
  12746. return X509_check_ip_asc(x509, hostname, 0) == 1;
  12747. }
  12748. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  12749. }
  12750. inline uint64_t hostname_mismatch_code() {
  12751. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  12752. }
  12753. inline long get_verify_result(const_session_t session) {
  12754. if (!session) return X509_V_ERR_UNSPECIFIED;
  12755. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  12756. }
  12757. inline std::string get_cert_subject_cn(cert_t cert) {
  12758. if (!cert) return "";
  12759. auto x509 = static_cast<X509 *>(cert);
  12760. auto subject_name = X509_get_subject_name(x509);
  12761. if (!subject_name) return "";
  12762. char buf[256];
  12763. auto len =
  12764. X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf, sizeof(buf));
  12765. if (len < 0) return "";
  12766. return std::string(buf, static_cast<size_t>(len));
  12767. }
  12768. inline std::string get_cert_issuer_name(cert_t cert) {
  12769. if (!cert) return "";
  12770. auto x509 = static_cast<X509 *>(cert);
  12771. auto issuer_name = X509_get_issuer_name(x509);
  12772. if (!issuer_name) return "";
  12773. char buf[256];
  12774. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  12775. return std::string(buf);
  12776. }
  12777. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  12778. sans.clear();
  12779. if (!cert) return false;
  12780. auto x509 = static_cast<X509 *>(cert);
  12781. auto names = static_cast<GENERAL_NAMES *>(
  12782. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  12783. if (!names) return true; // No SANs is valid
  12784. auto count = sk_GENERAL_NAME_num(names);
  12785. for (int i = 0; i < count; i++) {
  12786. auto gen = sk_GENERAL_NAME_value(names, i);
  12787. if (!gen) continue;
  12788. SanEntry entry;
  12789. switch (gen->type) {
  12790. case GEN_DNS:
  12791. entry.type = SanType::DNS;
  12792. if (gen->d.dNSName) {
  12793. entry.value = std::string(
  12794. reinterpret_cast<const char *>(
  12795. ASN1_STRING_get0_data(gen->d.dNSName)),
  12796. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  12797. }
  12798. break;
  12799. case GEN_IPADD:
  12800. entry.type = SanType::IP;
  12801. if (gen->d.iPAddress) {
  12802. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  12803. auto len = ASN1_STRING_length(gen->d.iPAddress);
  12804. if (len == 4) {
  12805. // IPv4
  12806. char buf[INET_ADDRSTRLEN];
  12807. inet_ntop(AF_INET, data, buf, sizeof(buf));
  12808. entry.value = buf;
  12809. } else if (len == 16) {
  12810. // IPv6
  12811. char buf[INET6_ADDRSTRLEN];
  12812. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  12813. entry.value = buf;
  12814. }
  12815. }
  12816. break;
  12817. case GEN_EMAIL:
  12818. entry.type = SanType::EMAIL;
  12819. if (gen->d.rfc822Name) {
  12820. entry.value = std::string(
  12821. reinterpret_cast<const char *>(
  12822. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  12823. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  12824. }
  12825. break;
  12826. case GEN_URI:
  12827. entry.type = SanType::URI;
  12828. if (gen->d.uniformResourceIdentifier) {
  12829. entry.value = std::string(
  12830. reinterpret_cast<const char *>(
  12831. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  12832. static_cast<size_t>(
  12833. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  12834. }
  12835. break;
  12836. default: entry.type = SanType::OTHER; break;
  12837. }
  12838. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  12839. }
  12840. GENERAL_NAMES_free(names);
  12841. return true;
  12842. }
  12843. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  12844. time_t &not_after) {
  12845. if (!cert) return false;
  12846. auto x509 = static_cast<X509 *>(cert);
  12847. auto nb = X509_get0_notBefore(x509);
  12848. auto na = X509_get0_notAfter(x509);
  12849. if (!nb || !na) return false;
  12850. // Convert ASN1_TIME to time_t
  12851. struct tm tm_nb = {}, tm_na = {};
  12852. if (ASN1_TIME_to_tm(nb, &tm_nb) != 1) return false;
  12853. if (ASN1_TIME_to_tm(na, &tm_na) != 1) return false;
  12854. #ifdef _WIN32
  12855. not_before = _mkgmtime(&tm_nb);
  12856. not_after = _mkgmtime(&tm_na);
  12857. #else
  12858. not_before = timegm(&tm_nb);
  12859. not_after = timegm(&tm_na);
  12860. #endif
  12861. return true;
  12862. }
  12863. inline std::string get_cert_serial(cert_t cert) {
  12864. if (!cert) return "";
  12865. auto x509 = static_cast<X509 *>(cert);
  12866. auto serial = X509_get_serialNumber(x509);
  12867. if (!serial) return "";
  12868. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  12869. if (!bn) return "";
  12870. auto hex = BN_bn2hex(bn);
  12871. BN_free(bn);
  12872. if (!hex) return "";
  12873. std::string result(hex);
  12874. OPENSSL_free(hex);
  12875. return result;
  12876. }
  12877. inline const char *get_sni(const_session_t session) {
  12878. if (!session) return nullptr;
  12879. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  12880. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  12881. }
  12882. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  12883. inline uint64_t get_error() { return ERR_get_error(); }
  12884. inline std::string error_string(uint64_t code) {
  12885. char buf[256];
  12886. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  12887. return std::string(buf);
  12888. }
  12889. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  12890. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  12891. if (!mem) { return nullptr; }
  12892. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  12893. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  12894. if (!inf) { return nullptr; }
  12895. auto store = X509_STORE_new();
  12896. if (store) {
  12897. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  12898. auto itmp = sk_X509_INFO_value(inf, i);
  12899. if (!itmp) { continue; }
  12900. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  12901. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  12902. }
  12903. }
  12904. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  12905. return static_cast<ca_store_t>(store);
  12906. }
  12907. inline void free_ca_store(ca_store_t store) {
  12908. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  12909. }
  12910. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  12911. if (!ctx || !store) { return false; }
  12912. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12913. auto x509_store = static_cast<X509_STORE *>(store);
  12914. // Check if same store is already set
  12915. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  12916. // SSL_CTX_set_cert_store takes ownership and frees the old store
  12917. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  12918. return true;
  12919. }
  12920. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  12921. certs.clear();
  12922. if (!ctx) { return 0; }
  12923. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12924. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12925. if (!store) { return 0; }
  12926. auto objs = X509_STORE_get0_objects(store);
  12927. if (!objs) { return 0; }
  12928. int count = sk_X509_OBJECT_num(objs);
  12929. for (int i = 0; i < count; i++) {
  12930. auto obj = sk_X509_OBJECT_value(objs, i);
  12931. if (!obj) { continue; }
  12932. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  12933. auto x509 = X509_OBJECT_get0_X509(obj);
  12934. if (x509) {
  12935. // Increment reference count so caller can free it
  12936. X509_up_ref(x509);
  12937. certs.push_back(static_cast<cert_t>(x509));
  12938. }
  12939. }
  12940. }
  12941. return certs.size();
  12942. }
  12943. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  12944. std::vector<std::string> names;
  12945. if (!ctx) { return names; }
  12946. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12947. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  12948. if (!store) { return names; }
  12949. auto objs = X509_STORE_get0_objects(store);
  12950. if (!objs) { return names; }
  12951. int count = sk_X509_OBJECT_num(objs);
  12952. for (int i = 0; i < count; i++) {
  12953. auto obj = sk_X509_OBJECT_value(objs, i);
  12954. if (!obj) { continue; }
  12955. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  12956. auto x509 = X509_OBJECT_get0_X509(obj);
  12957. if (x509) {
  12958. auto subject = X509_get_subject_name(x509);
  12959. if (subject) {
  12960. char buf[512];
  12961. X509_NAME_oneline(subject, buf, sizeof(buf));
  12962. names.push_back(buf);
  12963. }
  12964. }
  12965. }
  12966. }
  12967. return names;
  12968. }
  12969. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  12970. const char *key_pem, const char *password) {
  12971. if (!ctx || !cert_pem || !key_pem) { return false; }
  12972. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  12973. // Load certificate from PEM
  12974. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  12975. if (!cert_bio) { return false; }
  12976. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  12977. BIO_free(cert_bio);
  12978. if (!cert) { return false; }
  12979. // Load private key from PEM
  12980. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  12981. if (!key_bio) {
  12982. X509_free(cert);
  12983. return false;
  12984. }
  12985. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  12986. password ? const_cast<char *>(password)
  12987. : nullptr);
  12988. BIO_free(key_bio);
  12989. if (!key) {
  12990. X509_free(cert);
  12991. return false;
  12992. }
  12993. // Update certificate and key
  12994. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  12995. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  12996. X509_free(cert);
  12997. EVP_PKEY_free(key);
  12998. return ret;
  12999. }
  13000. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  13001. if (!ctx || !ca_pem) { return false; }
  13002. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13003. // Create new X509_STORE from PEM
  13004. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  13005. if (!store) { return false; }
  13006. // SSL_CTX_set_cert_store takes ownership
  13007. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  13008. // Set client CA list for client certificate request
  13009. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  13010. if (ca_list) {
  13011. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  13012. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  13013. }
  13014. return true;
  13015. }
  13016. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  13017. if (!ctx) { return false; }
  13018. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  13019. impl::get_verify_callback() = std::move(callback);
  13020. if (impl::get_verify_callback()) {
  13021. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  13022. } else {
  13023. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  13024. }
  13025. return true;
  13026. }
  13027. inline long get_verify_error(const_session_t session) {
  13028. if (!session) { return -1; }
  13029. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  13030. return SSL_get_verify_result(ssl);
  13031. }
  13032. inline std::string verify_error_string(long error_code) {
  13033. if (error_code == X509_V_OK) { return ""; }
  13034. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  13035. return str ? str : "unknown error";
  13036. }
  13037. namespace impl {
  13038. // OpenSSL-specific helpers for public API wrappers
  13039. inline ctx_t create_server_context_from_x509(X509 *cert, EVP_PKEY *key,
  13040. X509_STORE *client_ca_store,
  13041. int &out_error) {
  13042. out_error = 0;
  13043. auto cert_pem = x509_to_pem(cert);
  13044. auto key_pem = evp_pkey_to_pem(key);
  13045. if (cert_pem.empty() || key_pem.empty()) {
  13046. out_error = static_cast<int>(ERR_get_error());
  13047. return nullptr;
  13048. }
  13049. auto ctx = create_server_context();
  13050. if (!ctx) {
  13051. out_error = static_cast<int>(get_error());
  13052. return nullptr;
  13053. }
  13054. if (!set_server_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr)) {
  13055. out_error = static_cast<int>(get_error());
  13056. free_context(ctx);
  13057. return nullptr;
  13058. }
  13059. if (client_ca_store) {
  13060. // Set cert store for verification (SSL_CTX_set_cert_store takes ownership)
  13061. SSL_CTX_set_cert_store(static_cast<SSL_CTX *>(ctx), client_ca_store);
  13062. // Extract and set client CA list directly from store (more efficient than
  13063. // PEM conversion)
  13064. auto ca_list = extract_client_ca_list_from_store(client_ca_store);
  13065. if (ca_list) {
  13066. SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), ca_list);
  13067. }
  13068. set_verify_client(ctx, true);
  13069. }
  13070. return ctx;
  13071. }
  13072. inline void update_server_certs_from_x509(ctx_t ctx, X509 *cert, EVP_PKEY *key,
  13073. X509_STORE *client_ca_store) {
  13074. auto cert_pem = x509_to_pem(cert);
  13075. auto key_pem = evp_pkey_to_pem(key);
  13076. if (!cert_pem.empty() && !key_pem.empty()) {
  13077. update_server_cert(ctx, cert_pem.c_str(), key_pem.c_str(), nullptr);
  13078. }
  13079. if (client_ca_store) {
  13080. auto ca_pem = x509_store_to_pem(client_ca_store);
  13081. if (!ca_pem.empty()) { update_server_client_ca(ctx, ca_pem.c_str()); }
  13082. X509_STORE_free(client_ca_store);
  13083. }
  13084. }
  13085. inline ctx_t create_client_context_from_x509(X509 *cert, EVP_PKEY *key,
  13086. const char *password,
  13087. unsigned long &out_error) {
  13088. out_error = 0;
  13089. auto ctx = create_client_context();
  13090. if (!ctx) {
  13091. out_error = static_cast<unsigned long>(get_error());
  13092. return nullptr;
  13093. }
  13094. if (cert && key) {
  13095. auto cert_pem = x509_to_pem(cert);
  13096. auto key_pem = evp_pkey_to_pem(key);
  13097. if (cert_pem.empty() || key_pem.empty()) {
  13098. out_error = ERR_get_error();
  13099. free_context(ctx);
  13100. return nullptr;
  13101. }
  13102. if (!set_client_cert_pem(ctx, cert_pem.c_str(), key_pem.c_str(),
  13103. password)) {
  13104. out_error = static_cast<unsigned long>(get_error());
  13105. free_context(ctx);
  13106. return nullptr;
  13107. }
  13108. }
  13109. return ctx;
  13110. }
  13111. } // namespace impl
  13112. } // namespace tls
  13113. // ClientImpl::set_ca_cert_store - defined here to use
  13114. // tls::impl::x509_store_to_pem Deprecated: converts X509_STORE to PEM and
  13115. // stores for redirect transfer
  13116. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  13117. if (ca_cert_store) {
  13118. ca_cert_pem_ = tls::impl::x509_store_to_pem(ca_cert_store);
  13119. }
  13120. }
  13121. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  13122. X509_STORE *client_ca_cert_store) {
  13123. ctx_ = tls::impl::create_server_context_from_x509(
  13124. cert, private_key, client_ca_cert_store, last_ssl_error_);
  13125. }
  13126. inline SSLServer::SSLServer(
  13127. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  13128. // Use abstract API to create context
  13129. ctx_ = tls::create_server_context();
  13130. if (ctx_) {
  13131. // Pass to OpenSSL-specific callback (ctx_ is SSL_CTX* internally)
  13132. auto ssl_ctx = static_cast<SSL_CTX *>(ctx_);
  13133. if (!setup_ssl_ctx_callback(*ssl_ctx)) {
  13134. tls::free_context(ctx_);
  13135. ctx_ = nullptr;
  13136. }
  13137. }
  13138. }
  13139. inline SSL_CTX *SSLServer::ssl_context() const {
  13140. return static_cast<SSL_CTX *>(ctx_);
  13141. }
  13142. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  13143. X509_STORE *client_ca_cert_store) {
  13144. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13145. tls::impl::update_server_certs_from_x509(ctx_, cert, private_key,
  13146. client_ca_cert_store);
  13147. }
  13148. inline SSLClient::SSLClient(const std::string &host, int port,
  13149. X509 *client_cert, EVP_PKEY *client_key,
  13150. const std::string &private_key_password)
  13151. : ClientImpl(host, port) {
  13152. const char *password =
  13153. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13154. ctx_ = tls::impl::create_client_context_from_x509(
  13155. client_cert, client_key, password, last_backend_error_);
  13156. }
  13157. inline long SSLClient::get_verify_result() const { return verify_result_; }
  13158. inline void SSLClient::set_server_certificate_verifier(
  13159. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  13160. // Wrap SSL* callback into backend-independent session_verifier_
  13161. auto v = std::make_shared<std::function<SSLVerifierResponse(SSL *)>>(
  13162. std::move(verifier));
  13163. session_verifier_ = [v](tls::session_t session) {
  13164. return (*v)(static_cast<SSL *>(session));
  13165. };
  13166. }
  13167. inline SSL_CTX *SSLClient::ssl_context() const {
  13168. return static_cast<SSL_CTX *>(ctx_);
  13169. }
  13170. inline bool SSLClient::verify_host(X509 *server_cert) const {
  13171. /* Quote from RFC2818 section 3.1 "Server Identity"
  13172. If a subjectAltName extension of type dNSName is present, that MUST
  13173. be used as the identity. Otherwise, the (most specific) Common Name
  13174. field in the Subject field of the certificate MUST be used. Although
  13175. the use of the Common Name is existing practice, it is deprecated and
  13176. Certification Authorities are encouraged to use the dNSName instead.
  13177. Matching is performed using the matching rules specified by
  13178. [RFC2459]. If more than one identity of a given type is present in
  13179. the certificate (e.g., more than one dNSName name, a match in any one
  13180. of the set is considered acceptable.) Names may contain the wildcard
  13181. character * which is considered to match any single domain name
  13182. component or component fragment. E.g., *.a.com matches foo.a.com but
  13183. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  13184. In some cases, the URI is specified as an IP address rather than a
  13185. hostname. In this case, the iPAddress subjectAltName must be present
  13186. in the certificate and must exactly match the IP in the URI.
  13187. */
  13188. return verify_host_with_subject_alt_name(server_cert) ||
  13189. verify_host_with_common_name(server_cert);
  13190. }
  13191. inline bool
  13192. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  13193. auto ret = false;
  13194. auto type = GEN_DNS;
  13195. struct in6_addr addr6 = {};
  13196. struct in_addr addr = {};
  13197. size_t addr_len = 0;
  13198. #ifndef __MINGW32__
  13199. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  13200. type = GEN_IPADD;
  13201. addr_len = sizeof(struct in6_addr);
  13202. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  13203. type = GEN_IPADD;
  13204. addr_len = sizeof(struct in_addr);
  13205. }
  13206. #endif
  13207. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  13208. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  13209. if (alt_names) {
  13210. auto dsn_matched = false;
  13211. auto ip_matched = false;
  13212. auto count = sk_GENERAL_NAME_num(alt_names);
  13213. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  13214. auto val = sk_GENERAL_NAME_value(alt_names, i);
  13215. if (!val || val->type != type) { continue; }
  13216. auto name =
  13217. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  13218. if (name == nullptr) { continue; }
  13219. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  13220. switch (type) {
  13221. case GEN_DNS:
  13222. dsn_matched =
  13223. detail::match_hostname(std::string(name, name_len), host_);
  13224. break;
  13225. case GEN_IPADD:
  13226. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  13227. ip_matched = true;
  13228. }
  13229. break;
  13230. }
  13231. }
  13232. if (dsn_matched || ip_matched) { ret = true; }
  13233. }
  13234. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  13235. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  13236. return ret;
  13237. }
  13238. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  13239. const auto subject_name = X509_get_subject_name(server_cert);
  13240. if (subject_name != nullptr) {
  13241. char name[BUFSIZ];
  13242. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  13243. name, sizeof(name));
  13244. if (name_len != -1) {
  13245. return detail::match_hostname(
  13246. std::string(name, static_cast<size_t>(name_len)), host_);
  13247. }
  13248. }
  13249. return false;
  13250. }
  13251. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  13252. /*
  13253. * Group 9: TLS abstraction layer - Mbed TLS backend
  13254. */
  13255. /*
  13256. * Mbed TLS Backend Implementation
  13257. */
  13258. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13259. namespace tls {
  13260. namespace impl {
  13261. // Mbed TLS session wrapper
  13262. struct MbedTlsSession {
  13263. mbedtls_ssl_context ssl;
  13264. socket_t sock = INVALID_SOCKET;
  13265. std::string hostname; // For client: set via set_sni
  13266. std::string sni_hostname; // For server: received from client via SNI callback
  13267. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  13268. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  13269. MbedTlsSession(const MbedTlsSession &) = delete;
  13270. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  13271. };
  13272. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  13273. // queue)
  13274. inline int &mbedtls_last_error() {
  13275. static thread_local int err = 0;
  13276. return err;
  13277. }
  13278. // Helper to map Mbed TLS error to ErrorCode
  13279. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  13280. if (ret == 0) { return ErrorCode::Success; }
  13281. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  13282. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  13283. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  13284. return ErrorCode::PeerClosed;
  13285. }
  13286. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  13287. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  13288. out_errno = errno;
  13289. return ErrorCode::SyscallError;
  13290. }
  13291. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  13292. return ErrorCode::CertVerifyFailed;
  13293. }
  13294. return ErrorCode::Fatal;
  13295. }
  13296. // BIO-like send callback for Mbed TLS
  13297. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  13298. size_t len) {
  13299. auto sock = *static_cast<socket_t *>(ctx);
  13300. #ifdef _WIN32
  13301. auto ret =
  13302. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  13303. if (ret == SOCKET_ERROR) {
  13304. int err = WSAGetLastError();
  13305. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  13306. return MBEDTLS_ERR_NET_SEND_FAILED;
  13307. }
  13308. #else
  13309. auto ret = send(sock, buf, len, 0);
  13310. if (ret < 0) {
  13311. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  13312. return MBEDTLS_ERR_SSL_WANT_WRITE;
  13313. }
  13314. return MBEDTLS_ERR_NET_SEND_FAILED;
  13315. }
  13316. #endif
  13317. return static_cast<int>(ret);
  13318. }
  13319. // BIO-like recv callback for Mbed TLS
  13320. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  13321. auto sock = *static_cast<socket_t *>(ctx);
  13322. #ifdef _WIN32
  13323. auto ret =
  13324. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  13325. if (ret == SOCKET_ERROR) {
  13326. int err = WSAGetLastError();
  13327. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  13328. return MBEDTLS_ERR_NET_RECV_FAILED;
  13329. }
  13330. #else
  13331. auto ret = recv(sock, buf, len, 0);
  13332. if (ret < 0) {
  13333. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  13334. return MBEDTLS_ERR_SSL_WANT_READ;
  13335. }
  13336. return MBEDTLS_ERR_NET_RECV_FAILED;
  13337. }
  13338. #endif
  13339. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  13340. return static_cast<int>(ret);
  13341. }
  13342. // MbedTlsContext constructor/destructor implementations
  13343. inline MbedTlsContext::MbedTlsContext() {
  13344. mbedtls_ssl_config_init(&conf);
  13345. mbedtls_entropy_init(&entropy);
  13346. mbedtls_ctr_drbg_init(&ctr_drbg);
  13347. mbedtls_x509_crt_init(&ca_chain);
  13348. mbedtls_x509_crt_init(&own_cert);
  13349. mbedtls_pk_init(&own_key);
  13350. }
  13351. inline MbedTlsContext::~MbedTlsContext() {
  13352. mbedtls_pk_free(&own_key);
  13353. mbedtls_x509_crt_free(&own_cert);
  13354. mbedtls_x509_crt_free(&ca_chain);
  13355. mbedtls_ctr_drbg_free(&ctr_drbg);
  13356. mbedtls_entropy_free(&entropy);
  13357. mbedtls_ssl_config_free(&conf);
  13358. }
  13359. // Thread-local storage for SNI captured during handshake
  13360. // This is needed because the SNI callback doesn't have a way to pass
  13361. // session-specific data before the session is fully set up
  13362. inline std::string &mbedpending_sni() {
  13363. static thread_local std::string sni;
  13364. return sni;
  13365. }
  13366. // SNI callback for Mbed TLS server to capture client's SNI hostname
  13367. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  13368. const unsigned char *name, size_t name_len) {
  13369. (void)p_ctx;
  13370. (void)ssl;
  13371. // Store SNI name in thread-local storage
  13372. // It will be retrieved and stored in the session after handshake
  13373. if (name && name_len > 0) {
  13374. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  13375. } else {
  13376. mbedpending_sni().clear();
  13377. }
  13378. return 0; // Accept any SNI
  13379. }
  13380. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  13381. int cert_depth, uint32_t *flags);
  13382. // Check if a string is an IPv4 address
  13383. inline bool is_ipv4_address(const std::string &str) {
  13384. int dots = 0;
  13385. for (char c : str) {
  13386. if (c == '.') {
  13387. dots++;
  13388. } else if (!isdigit(static_cast<unsigned char>(c))) {
  13389. return false;
  13390. }
  13391. }
  13392. return dots == 3;
  13393. }
  13394. // Parse IPv4 address string to bytes
  13395. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  13396. int parts[4];
  13397. if (sscanf(str.c_str(), "%d.%d.%d.%d", &parts[0], &parts[1], &parts[2],
  13398. &parts[3]) != 4) {
  13399. return false;
  13400. }
  13401. for (int i = 0; i < 4; i++) {
  13402. if (parts[i] < 0 || parts[i] > 255) return false;
  13403. out[i] = static_cast<unsigned char>(parts[i]);
  13404. }
  13405. return true;
  13406. }
  13407. // MbedTLS verify callback wrapper
  13408. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  13409. int cert_depth, uint32_t *flags) {
  13410. auto &callback = get_verify_callback();
  13411. if (!callback) { return 0; } // Continue with default verification
  13412. // data points to the MbedTlsSession
  13413. auto *session = static_cast<MbedTlsSession *>(data);
  13414. // Build context
  13415. VerifyContext verify_ctx;
  13416. verify_ctx.session = static_cast<session_t>(session);
  13417. verify_ctx.cert = static_cast<cert_t>(crt);
  13418. verify_ctx.depth = cert_depth;
  13419. verify_ctx.preverify_ok = (*flags == 0);
  13420. verify_ctx.error_code = static_cast<long>(*flags);
  13421. // Convert Mbed TLS flags to error string
  13422. static thread_local char error_buf[256];
  13423. if (*flags != 0) {
  13424. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  13425. verify_ctx.error_string = error_buf;
  13426. } else {
  13427. verify_ctx.error_string = nullptr;
  13428. }
  13429. bool accepted = callback(verify_ctx);
  13430. if (accepted) {
  13431. *flags = 0; // Clear all error flags
  13432. return 0;
  13433. }
  13434. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  13435. }
  13436. } // namespace impl
  13437. inline ctx_t create_client_context() {
  13438. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  13439. if (!ctx) { return nullptr; }
  13440. ctx->is_server = false;
  13441. // Seed the random number generator
  13442. const char *pers = "httplib_client";
  13443. int ret = mbedtls_ctr_drbg_seed(
  13444. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  13445. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  13446. if (ret != 0) {
  13447. impl::mbedtls_last_error() = ret;
  13448. delete ctx;
  13449. return nullptr;
  13450. }
  13451. // Set up SSL config for client
  13452. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  13453. MBEDTLS_SSL_TRANSPORT_STREAM,
  13454. MBEDTLS_SSL_PRESET_DEFAULT);
  13455. if (ret != 0) {
  13456. impl::mbedtls_last_error() = ret;
  13457. delete ctx;
  13458. return nullptr;
  13459. }
  13460. // Set random number generator
  13461. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  13462. // Default: verify peer certificate
  13463. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13464. // Set minimum TLS version to 1.2
  13465. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13466. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13467. #else
  13468. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13469. MBEDTLS_SSL_MINOR_VERSION_3);
  13470. #endif
  13471. return static_cast<ctx_t>(ctx);
  13472. }
  13473. inline ctx_t create_server_context() {
  13474. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  13475. if (!ctx) { return nullptr; }
  13476. ctx->is_server = true;
  13477. // Seed the random number generator
  13478. const char *pers = "httplib_server";
  13479. int ret = mbedtls_ctr_drbg_seed(
  13480. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  13481. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  13482. if (ret != 0) {
  13483. impl::mbedtls_last_error() = ret;
  13484. delete ctx;
  13485. return nullptr;
  13486. }
  13487. // Set up SSL config for server
  13488. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  13489. MBEDTLS_SSL_TRANSPORT_STREAM,
  13490. MBEDTLS_SSL_PRESET_DEFAULT);
  13491. if (ret != 0) {
  13492. impl::mbedtls_last_error() = ret;
  13493. delete ctx;
  13494. return nullptr;
  13495. }
  13496. // Set random number generator
  13497. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  13498. // Default: don't verify client
  13499. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  13500. // Set minimum TLS version to 1.2
  13501. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13502. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13503. #else
  13504. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13505. MBEDTLS_SSL_MINOR_VERSION_3);
  13506. #endif
  13507. // Set SNI callback to capture client's SNI hostname
  13508. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  13509. return static_cast<ctx_t>(ctx);
  13510. }
  13511. inline void free_context(ctx_t ctx) {
  13512. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  13513. }
  13514. inline bool set_min_version(ctx_t ctx, Version version) {
  13515. if (!ctx) { return false; }
  13516. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13517. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13518. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  13519. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  13520. if (version >= Version::TLS1_3) {
  13521. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  13522. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  13523. #endif
  13524. }
  13525. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  13526. #else
  13527. // Mbed TLS 2.x uses major/minor version numbers
  13528. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  13529. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  13530. if (version >= Version::TLS1_3) {
  13531. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  13532. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  13533. #else
  13534. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  13535. #endif
  13536. }
  13537. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  13538. #endif
  13539. return true;
  13540. }
  13541. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  13542. if (!ctx || !pem) { return false; }
  13543. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13544. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  13545. // Add null terminator if not present
  13546. std::string pem_str(pem, len);
  13547. int ret = mbedtls_x509_crt_parse(
  13548. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  13549. pem_str.size() + 1);
  13550. if (ret != 0) {
  13551. impl::mbedtls_last_error() = ret;
  13552. return false;
  13553. }
  13554. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13555. return true;
  13556. }
  13557. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  13558. if (!ctx || !file_path) { return false; }
  13559. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13560. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  13561. if (ret != 0) {
  13562. impl::mbedtls_last_error() = ret;
  13563. return false;
  13564. }
  13565. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13566. return true;
  13567. }
  13568. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  13569. if (!ctx || !dir_path) { return false; }
  13570. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13571. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  13572. if (ret < 0) { // Returns number of certs on success, negative on error
  13573. impl::mbedtls_last_error() = ret;
  13574. return false;
  13575. }
  13576. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13577. return true;
  13578. }
  13579. inline bool load_system_certs(ctx_t ctx) {
  13580. if (!ctx) { return false; }
  13581. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13582. bool loaded = false;
  13583. #ifdef _WIN32
  13584. // Load from Windows certificate store
  13585. HCERTSTORE hStore = CertOpenSystemStoreW(0, L"ROOT");
  13586. if (hStore) {
  13587. PCCERT_CONTEXT pContext = nullptr;
  13588. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  13589. nullptr) {
  13590. int ret = mbedtls_x509_crt_parse_der(
  13591. &mctx->ca_chain, pContext->pbCertEncoded, pContext->cbCertEncoded);
  13592. if (ret == 0) { loaded = true; }
  13593. }
  13594. CertCloseStore(hStore, 0);
  13595. }
  13596. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  13597. // Load from macOS Keychain
  13598. CFArrayRef certs = nullptr;
  13599. OSStatus status = SecTrustCopyAnchorCertificates(&certs);
  13600. if (status == errSecSuccess && certs) {
  13601. CFIndex count = CFArrayGetCount(certs);
  13602. for (CFIndex i = 0; i < count; i++) {
  13603. SecCertificateRef cert =
  13604. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  13605. CFDataRef data = SecCertificateCopyData(cert);
  13606. if (data) {
  13607. int ret = mbedtls_x509_crt_parse_der(
  13608. &mctx->ca_chain, CFDataGetBytePtr(data),
  13609. static_cast<size_t>(CFDataGetLength(data)));
  13610. if (ret == 0) { loaded = true; }
  13611. CFRelease(data);
  13612. }
  13613. }
  13614. CFRelease(certs);
  13615. }
  13616. #else
  13617. // Try common CA certificate locations on Linux/Unix
  13618. static const char *ca_paths[] = {
  13619. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  13620. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  13621. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  13622. "/etc/pki/tls/cacert.pem", // OpenELEC
  13623. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  13624. nullptr};
  13625. for (const char **path = ca_paths; *path; ++path) {
  13626. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path);
  13627. if (ret >= 0) {
  13628. loaded = true;
  13629. break;
  13630. }
  13631. }
  13632. // Also try the CA directory
  13633. if (!loaded) {
  13634. static const char *ca_dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  13635. "/etc/pki/tls/certs", // RHEL/CentOS
  13636. "/usr/share/ca-certificates", nullptr};
  13637. for (const char **dir = ca_dirs; *dir; ++dir) {
  13638. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir);
  13639. if (ret >= 0) {
  13640. loaded = true;
  13641. break;
  13642. }
  13643. }
  13644. }
  13645. #endif
  13646. if (loaded) {
  13647. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  13648. }
  13649. return loaded;
  13650. }
  13651. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  13652. const char *password) {
  13653. if (!ctx || !cert || !key) { return false; }
  13654. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13655. // Parse certificate
  13656. std::string cert_str(cert);
  13657. int ret = mbedtls_x509_crt_parse(
  13658. &mctx->own_cert,
  13659. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  13660. cert_str.size() + 1);
  13661. if (ret != 0) {
  13662. impl::mbedtls_last_error() = ret;
  13663. return false;
  13664. }
  13665. // Parse private key
  13666. std::string key_str(key);
  13667. const unsigned char *pwd =
  13668. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  13669. size_t pwd_len = password ? strlen(password) : 0;
  13670. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13671. ret = mbedtls_pk_parse_key(
  13672. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  13673. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  13674. &mctx->ctr_drbg);
  13675. #else
  13676. ret = mbedtls_pk_parse_key(
  13677. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  13678. key_str.size() + 1, pwd, pwd_len);
  13679. #endif
  13680. if (ret != 0) {
  13681. impl::mbedtls_last_error() = ret;
  13682. return false;
  13683. }
  13684. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  13685. if (ret != 0) {
  13686. impl::mbedtls_last_error() = ret;
  13687. return false;
  13688. }
  13689. return true;
  13690. }
  13691. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  13692. const char *key_path, const char *password) {
  13693. if (!ctx || !cert_path || !key_path) { return false; }
  13694. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13695. // Parse certificate file
  13696. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  13697. if (ret != 0) {
  13698. impl::mbedtls_last_error() = ret;
  13699. return false;
  13700. }
  13701. // Parse private key file
  13702. #ifdef CPPHTTPLIB_MBEDTLS_V3
  13703. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  13704. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  13705. #else
  13706. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  13707. #endif
  13708. if (ret != 0) {
  13709. impl::mbedtls_last_error() = ret;
  13710. return false;
  13711. }
  13712. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  13713. if (ret != 0) {
  13714. impl::mbedtls_last_error() = ret;
  13715. return false;
  13716. }
  13717. return true;
  13718. }
  13719. inline void set_verify_client(ctx_t ctx, bool require) {
  13720. if (!ctx) { return; }
  13721. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13722. mctx->verify_client = require;
  13723. if (require) {
  13724. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13725. } else {
  13726. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  13727. // is called (matching OpenSSL behavior). Otherwise use NONE.
  13728. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  13729. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  13730. : MBEDTLS_SSL_VERIFY_NONE);
  13731. }
  13732. }
  13733. inline session_t create_session(ctx_t ctx, socket_t sock) {
  13734. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  13735. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  13736. auto session = new (std::nothrow) impl::MbedTlsSession();
  13737. if (!session) { return nullptr; }
  13738. session->sock = sock;
  13739. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  13740. if (ret != 0) {
  13741. impl::mbedtls_last_error() = ret;
  13742. delete session;
  13743. return nullptr;
  13744. }
  13745. // Set BIO callbacks
  13746. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  13747. impl::mbedtls_net_recv_cb, nullptr);
  13748. // Set per-session verify callback with session pointer if callback is
  13749. // registered
  13750. if (mctx->has_verify_callback) {
  13751. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  13752. session);
  13753. }
  13754. return static_cast<session_t>(session);
  13755. }
  13756. inline void free_session(session_t session) {
  13757. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  13758. }
  13759. inline bool set_sni(session_t session, const char *hostname) {
  13760. if (!session || !hostname) { return false; }
  13761. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13762. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  13763. if (ret != 0) {
  13764. impl::mbedtls_last_error() = ret;
  13765. return false;
  13766. }
  13767. msession->hostname = hostname;
  13768. return true;
  13769. }
  13770. inline bool set_hostname(session_t session, const char *hostname) {
  13771. // In Mbed TLS, set_hostname also sets up hostname verification
  13772. return set_sni(session, hostname);
  13773. }
  13774. inline TlsError connect(session_t session) {
  13775. TlsError err;
  13776. if (!session) {
  13777. err.code = ErrorCode::Fatal;
  13778. return err;
  13779. }
  13780. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13781. int ret = mbedtls_ssl_handshake(&msession->ssl);
  13782. if (ret == 0) {
  13783. err.code = ErrorCode::Success;
  13784. } else {
  13785. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  13786. err.backend_code = static_cast<uint64_t>(-ret);
  13787. impl::mbedtls_last_error() = ret;
  13788. }
  13789. return err;
  13790. }
  13791. inline TlsError accept(session_t session) {
  13792. // Same as connect for Mbed TLS - handshake works for both client and server
  13793. auto result = connect(session);
  13794. // After successful handshake, capture SNI from thread-local storage
  13795. if (result.code == ErrorCode::Success && session) {
  13796. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13797. msession->sni_hostname = std::move(impl::mbedpending_sni());
  13798. impl::mbedpending_sni().clear();
  13799. }
  13800. return result;
  13801. }
  13802. inline bool connect_nonblocking(session_t session, socket_t sock,
  13803. time_t timeout_sec, time_t timeout_usec,
  13804. TlsError *err) {
  13805. if (!session) {
  13806. if (err) { err->code = ErrorCode::Fatal; }
  13807. return false;
  13808. }
  13809. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13810. // Set socket to non-blocking mode
  13811. detail::set_nonblocking(sock, true);
  13812. auto cleanup =
  13813. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  13814. int ret;
  13815. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  13816. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  13817. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  13818. continue;
  13819. }
  13820. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  13821. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  13822. continue;
  13823. }
  13824. }
  13825. // TlsError or timeout
  13826. if (err) {
  13827. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  13828. err->backend_code = static_cast<uint64_t>(-ret);
  13829. }
  13830. impl::mbedtls_last_error() = ret;
  13831. return false;
  13832. }
  13833. if (err) { err->code = ErrorCode::Success; }
  13834. return true;
  13835. }
  13836. inline bool accept_nonblocking(session_t session, socket_t sock,
  13837. time_t timeout_sec, time_t timeout_usec,
  13838. TlsError *err) {
  13839. // Same implementation as connect for Mbed TLS
  13840. bool result =
  13841. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  13842. // After successful handshake, capture SNI from thread-local storage
  13843. if (result && session) {
  13844. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13845. msession->sni_hostname = std::move(impl::mbedpending_sni());
  13846. impl::mbedpending_sni().clear();
  13847. }
  13848. return result;
  13849. }
  13850. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  13851. if (!session || !buf) {
  13852. err.code = ErrorCode::Fatal;
  13853. return -1;
  13854. }
  13855. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13856. int ret =
  13857. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  13858. if (ret > 0) {
  13859. err.code = ErrorCode::Success;
  13860. return static_cast<ssize_t>(ret);
  13861. }
  13862. if (ret == 0) {
  13863. err.code = ErrorCode::PeerClosed;
  13864. return 0;
  13865. }
  13866. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  13867. err.backend_code = static_cast<uint64_t>(-ret);
  13868. impl::mbedtls_last_error() = ret;
  13869. return -1;
  13870. }
  13871. inline ssize_t write(session_t session, const void *buf, size_t len,
  13872. TlsError &err) {
  13873. if (!session || !buf) {
  13874. err.code = ErrorCode::Fatal;
  13875. return -1;
  13876. }
  13877. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13878. int ret = mbedtls_ssl_write(&msession->ssl,
  13879. static_cast<const unsigned char *>(buf), len);
  13880. if (ret > 0) {
  13881. err.code = ErrorCode::Success;
  13882. return static_cast<ssize_t>(ret);
  13883. }
  13884. if (ret == 0) {
  13885. err.code = ErrorCode::PeerClosed;
  13886. return 0;
  13887. }
  13888. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  13889. err.backend_code = static_cast<uint64_t>(-ret);
  13890. impl::mbedtls_last_error() = ret;
  13891. return -1;
  13892. }
  13893. inline int pending(const_session_t session) {
  13894. if (!session) { return 0; }
  13895. auto msession =
  13896. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  13897. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  13898. }
  13899. inline void shutdown(session_t session, bool graceful) {
  13900. if (!session) { return; }
  13901. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13902. if (graceful) {
  13903. // Try to send close_notify, but don't block forever
  13904. int ret;
  13905. int attempts = 0;
  13906. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  13907. attempts < 3) {
  13908. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  13909. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  13910. break;
  13911. }
  13912. attempts++;
  13913. }
  13914. }
  13915. }
  13916. inline bool is_peer_closed(session_t session, socket_t sock) {
  13917. if (!session || sock == INVALID_SOCKET) { return true; }
  13918. auto msession = static_cast<impl::MbedTlsSession *>(session);
  13919. // Check if there's already decrypted data available in the TLS buffer
  13920. // If so, the connection is definitely alive
  13921. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  13922. // Set socket to non-blocking to avoid blocking on read
  13923. detail::set_nonblocking(sock, true);
  13924. auto cleanup =
  13925. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  13926. // Try a 1-byte read to check connection status
  13927. // Note: This will consume the byte if data is available, but for the
  13928. // purpose of checking if peer is closed, this should be acceptable
  13929. // since we're only called when we expect the connection might be closing
  13930. unsigned char buf;
  13931. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  13932. // If we got data or WANT_READ (would block), connection is alive
  13933. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  13934. // If we get a peer close notify or a connection reset, the peer is closed
  13935. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  13936. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  13937. }
  13938. inline cert_t get_peer_cert(const_session_t session) {
  13939. if (!session) { return nullptr; }
  13940. auto msession =
  13941. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  13942. // Mbed TLS returns a pointer to the internal peer cert chain.
  13943. // WARNING: This pointer is only valid while the session is active.
  13944. // Do not use the certificate after calling free_session().
  13945. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  13946. return const_cast<mbedtls_x509_crt *>(cert);
  13947. }
  13948. inline void free_cert(cert_t cert) {
  13949. // Mbed TLS: peer certificate is owned by the SSL context.
  13950. // No-op here, but callers should still call this for cross-backend
  13951. // portability.
  13952. (void)cert;
  13953. }
  13954. inline bool verify_hostname(cert_t cert, const char *hostname) {
  13955. if (!cert || !hostname) { return false; }
  13956. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  13957. std::string host_str(hostname);
  13958. // Check if hostname is an IP address
  13959. bool is_ip = impl::is_ipv4_address(host_str);
  13960. unsigned char ip_bytes[4];
  13961. if (is_ip) { impl::parse_ipv4(host_str, ip_bytes); }
  13962. // Check Subject Alternative Names (SAN)
  13963. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  13964. // - DNS names: raw string bytes
  13965. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  13966. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  13967. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  13968. const unsigned char *p = san->buf.p;
  13969. size_t len = san->buf.len;
  13970. if (is_ip) {
  13971. // Check if this SAN is an IPv4 address (4 bytes)
  13972. if (len == 4 && memcmp(p, ip_bytes, 4) == 0) { return true; }
  13973. // Check if this SAN is an IPv6 address (16 bytes) - skip for now
  13974. } else {
  13975. // Check if this SAN is a DNS name (printable ASCII string)
  13976. bool is_dns = len > 0;
  13977. for (size_t i = 0; i < len && is_dns; i++) {
  13978. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  13979. }
  13980. if (is_dns) {
  13981. std::string san_name(reinterpret_cast<const char *>(p), len);
  13982. if (detail::match_hostname(san_name, host_str)) { return true; }
  13983. }
  13984. }
  13985. san = san->next;
  13986. }
  13987. // Fallback: Check Common Name (CN) in subject
  13988. char cn[256];
  13989. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  13990. if (ret > 0) {
  13991. std::string cn_str(cn);
  13992. // Look for "CN=" in the DN string
  13993. size_t cn_pos = cn_str.find("CN=");
  13994. if (cn_pos != std::string::npos) {
  13995. size_t start = cn_pos + 3;
  13996. size_t end = cn_str.find(',', start);
  13997. std::string cn_value =
  13998. cn_str.substr(start, end == std::string::npos ? end : end - start);
  13999. if (detail::match_hostname(cn_value, host_str)) { return true; }
  14000. }
  14001. }
  14002. return false;
  14003. }
  14004. inline uint64_t hostname_mismatch_code() {
  14005. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  14006. }
  14007. inline long get_verify_result(const_session_t session) {
  14008. if (!session) { return -1; }
  14009. auto msession =
  14010. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  14011. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  14012. // Return 0 (X509_V_OK equivalent) if verification passed
  14013. return flags == 0 ? 0 : static_cast<long>(flags);
  14014. }
  14015. inline std::string get_cert_subject_cn(cert_t cert) {
  14016. if (!cert) return "";
  14017. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14018. // Find the CN in the subject
  14019. const mbedtls_x509_name *name = &x509->subject;
  14020. while (name != nullptr) {
  14021. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  14022. return std::string(reinterpret_cast<const char *>(name->val.p),
  14023. name->val.len);
  14024. }
  14025. name = name->next;
  14026. }
  14027. return "";
  14028. }
  14029. inline std::string get_cert_issuer_name(cert_t cert) {
  14030. if (!cert) return "";
  14031. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14032. // Build a human-readable issuer name string
  14033. char buf[512];
  14034. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  14035. if (ret < 0) return "";
  14036. return std::string(buf);
  14037. }
  14038. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14039. sans.clear();
  14040. if (!cert) return false;
  14041. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14042. // Parse the Subject Alternative Name extension
  14043. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  14044. while (cur != nullptr) {
  14045. if (cur->buf.len > 0) {
  14046. // Mbed TLS stores SAN as ASN.1 sequences
  14047. // The tag byte indicates the type
  14048. const unsigned char *p = cur->buf.p;
  14049. size_t len = cur->buf.len;
  14050. // First byte is the tag
  14051. unsigned char tag = *p;
  14052. p++;
  14053. len--;
  14054. // Parse length (simple single-byte length assumed)
  14055. if (len > 0 && *p < 0x80) {
  14056. size_t value_len = *p;
  14057. p++;
  14058. len--;
  14059. if (value_len <= len) {
  14060. SanEntry entry;
  14061. // ASN.1 context tags for GeneralName
  14062. switch (tag & 0x1F) {
  14063. case 2: // dNSName
  14064. entry.type = SanType::DNS;
  14065. entry.value =
  14066. std::string(reinterpret_cast<const char *>(p), value_len);
  14067. break;
  14068. case 7: // iPAddress
  14069. entry.type = SanType::IP;
  14070. if (value_len == 4) {
  14071. // IPv4
  14072. char buf[16];
  14073. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  14074. entry.value = buf;
  14075. } else if (value_len == 16) {
  14076. // IPv6
  14077. char buf[64];
  14078. snprintf(buf, sizeof(buf),
  14079. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  14080. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  14081. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  14082. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  14083. entry.value = buf;
  14084. }
  14085. break;
  14086. case 1: // rfc822Name (email)
  14087. entry.type = SanType::EMAIL;
  14088. entry.value =
  14089. std::string(reinterpret_cast<const char *>(p), value_len);
  14090. break;
  14091. case 6: // uniformResourceIdentifier
  14092. entry.type = SanType::URI;
  14093. entry.value =
  14094. std::string(reinterpret_cast<const char *>(p), value_len);
  14095. break;
  14096. default: entry.type = SanType::OTHER; break;
  14097. }
  14098. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14099. }
  14100. }
  14101. }
  14102. cur = cur->next;
  14103. }
  14104. return true;
  14105. }
  14106. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14107. time_t &not_after) {
  14108. if (!cert) return false;
  14109. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14110. // Convert mbedtls_x509_time to time_t
  14111. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  14112. struct tm tm_time = {};
  14113. tm_time.tm_year = t.year - 1900;
  14114. tm_time.tm_mon = t.mon - 1;
  14115. tm_time.tm_mday = t.day;
  14116. tm_time.tm_hour = t.hour;
  14117. tm_time.tm_min = t.min;
  14118. tm_time.tm_sec = t.sec;
  14119. #ifdef _WIN32
  14120. return _mkgmtime(&tm_time);
  14121. #else
  14122. return timegm(&tm_time);
  14123. #endif
  14124. };
  14125. not_before = to_time_t(x509->valid_from);
  14126. not_after = to_time_t(x509->valid_to);
  14127. return true;
  14128. }
  14129. inline std::string get_cert_serial(cert_t cert) {
  14130. if (!cert) return "";
  14131. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  14132. // Convert serial number to hex string
  14133. std::string result;
  14134. result.reserve(x509->serial.len * 2);
  14135. for (size_t i = 0; i < x509->serial.len; i++) {
  14136. char hex[3];
  14137. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  14138. result += hex;
  14139. }
  14140. return result;
  14141. }
  14142. inline const char *get_sni(const_session_t session) {
  14143. if (!session) return nullptr;
  14144. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  14145. // For server: return SNI received from client during handshake
  14146. if (!msession->sni_hostname.empty()) {
  14147. return msession->sni_hostname.c_str();
  14148. }
  14149. // For client: return the hostname set via set_sni
  14150. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  14151. return nullptr;
  14152. }
  14153. inline uint64_t peek_error() {
  14154. // Mbed TLS doesn't have an error queue, return the last error
  14155. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  14156. }
  14157. inline uint64_t get_error() {
  14158. // Mbed TLS doesn't have an error queue, return and clear the last error
  14159. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  14160. impl::mbedtls_last_error() = 0;
  14161. return err;
  14162. }
  14163. inline std::string error_string(uint64_t code) {
  14164. char buf[256];
  14165. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  14166. return std::string(buf);
  14167. }
  14168. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14169. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  14170. if (!ca_chain) { return nullptr; }
  14171. mbedtls_x509_crt_init(ca_chain);
  14172. // mbedtls_x509_crt_parse expects null-terminated PEM
  14173. int ret = mbedtls_x509_crt_parse(ca_chain,
  14174. reinterpret_cast<const unsigned char *>(pem),
  14175. len + 1); // +1 for null terminator
  14176. if (ret != 0) {
  14177. // Try without +1 in case PEM is already null-terminated
  14178. ret = mbedtls_x509_crt_parse(
  14179. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  14180. if (ret != 0) {
  14181. mbedtls_x509_crt_free(ca_chain);
  14182. delete ca_chain;
  14183. return nullptr;
  14184. }
  14185. }
  14186. return static_cast<ca_store_t>(ca_chain);
  14187. }
  14188. inline void free_ca_store(ca_store_t store) {
  14189. if (store) {
  14190. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  14191. mbedtls_x509_crt_free(ca_chain);
  14192. delete ca_chain;
  14193. }
  14194. }
  14195. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  14196. if (!ctx || !store) { return false; }
  14197. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14198. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  14199. // Free existing CA chain
  14200. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  14201. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  14202. // Copy the CA chain (deep copy)
  14203. // Parse from the raw data of the source cert
  14204. mbedtls_x509_crt *src = ca_chain;
  14205. while (src != nullptr) {
  14206. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  14207. src->raw.len);
  14208. if (ret != 0) { return false; }
  14209. src = src->next;
  14210. }
  14211. // Update the SSL config to use the new CA chain
  14212. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  14213. return true;
  14214. }
  14215. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  14216. certs.clear();
  14217. if (!ctx) { return 0; }
  14218. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14219. // Iterate through the CA chain
  14220. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  14221. while (cert != nullptr && cert->raw.len > 0) {
  14222. // Create a copy of the certificate for the caller
  14223. auto *copy = new mbedtls_x509_crt;
  14224. mbedtls_x509_crt_init(copy);
  14225. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  14226. if (ret == 0) {
  14227. certs.push_back(static_cast<cert_t>(copy));
  14228. } else {
  14229. mbedtls_x509_crt_free(copy);
  14230. delete copy;
  14231. }
  14232. cert = cert->next;
  14233. }
  14234. return certs.size();
  14235. }
  14236. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  14237. std::vector<std::string> names;
  14238. if (!ctx) { return names; }
  14239. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14240. // Iterate through the CA chain
  14241. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  14242. while (cert != nullptr && cert->raw.len > 0) {
  14243. char buf[512];
  14244. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  14245. if (ret > 0) { names.push_back(buf); }
  14246. cert = cert->next;
  14247. }
  14248. return names;
  14249. }
  14250. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  14251. const char *key_pem, const char *password) {
  14252. if (!ctx || !cert_pem || !key_pem) { return false; }
  14253. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14254. // Free existing certificate and key
  14255. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  14256. mbedtls_pk_free(&mbed_ctx->own_key);
  14257. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  14258. mbedtls_pk_init(&mbed_ctx->own_key);
  14259. // Parse certificate PEM
  14260. int ret = mbedtls_x509_crt_parse(
  14261. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  14262. strlen(cert_pem) + 1);
  14263. if (ret != 0) {
  14264. impl::mbedtls_last_error() = ret;
  14265. return false;
  14266. }
  14267. // Parse private key PEM
  14268. #ifdef CPPHTTPLIB_MBEDTLS_V3
  14269. ret = mbedtls_pk_parse_key(
  14270. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  14271. strlen(key_pem) + 1,
  14272. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  14273. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  14274. &mbed_ctx->ctr_drbg);
  14275. #else
  14276. ret = mbedtls_pk_parse_key(
  14277. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  14278. strlen(key_pem) + 1,
  14279. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  14280. password ? strlen(password) : 0);
  14281. #endif
  14282. if (ret != 0) {
  14283. impl::mbedtls_last_error() = ret;
  14284. return false;
  14285. }
  14286. // Configure SSL to use the new certificate and key
  14287. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  14288. &mbed_ctx->own_key);
  14289. if (ret != 0) {
  14290. impl::mbedtls_last_error() = ret;
  14291. return false;
  14292. }
  14293. return true;
  14294. }
  14295. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  14296. if (!ctx || !ca_pem) { return false; }
  14297. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14298. // Free existing CA chain
  14299. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  14300. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  14301. // Parse CA PEM
  14302. int ret = mbedtls_x509_crt_parse(
  14303. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  14304. strlen(ca_pem) + 1);
  14305. if (ret != 0) {
  14306. impl::mbedtls_last_error() = ret;
  14307. return false;
  14308. }
  14309. // Update SSL config to use new CA chain
  14310. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  14311. return true;
  14312. }
  14313. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  14314. if (!ctx) { return false; }
  14315. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  14316. impl::get_verify_callback() = std::move(callback);
  14317. mbed_ctx->has_verify_callback =
  14318. static_cast<bool>(impl::get_verify_callback());
  14319. if (mbed_ctx->has_verify_callback) {
  14320. // Set OPTIONAL mode to ensure callback is called even when verification
  14321. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  14322. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  14323. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  14324. nullptr);
  14325. } else {
  14326. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  14327. }
  14328. return true;
  14329. }
  14330. inline long get_verify_error(const_session_t session) {
  14331. if (!session) { return -1; }
  14332. auto *msession =
  14333. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  14334. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  14335. }
  14336. inline std::string verify_error_string(long error_code) {
  14337. if (error_code == 0) { return ""; }
  14338. char buf[256];
  14339. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  14340. static_cast<uint32_t>(error_code));
  14341. // Remove trailing newline if present
  14342. std::string result(buf);
  14343. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  14344. result.pop_back();
  14345. }
  14346. return result;
  14347. }
  14348. } // namespace tls
  14349. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  14350. // ----------------------------------------------------------------------------
  14351. } // namespace httplib
  14352. #endif // CPPHTTPLIB_HTTPLIB_H