1
0

httplib.h 477 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180
  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_ZLIB_SUPPORT
  314. #include <zlib.h>
  315. #endif
  316. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  317. #include <brotli/decode.h>
  318. #include <brotli/encode.h>
  319. #endif
  320. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  321. #include <zstd.h>
  322. #endif
  323. /*
  324. * Declaration
  325. */
  326. namespace httplib {
  327. namespace detail {
  328. /*
  329. * Backport std::make_unique from C++14.
  330. *
  331. * NOTE: This code came up with the following stackoverflow post:
  332. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  333. *
  334. */
  335. template <class T, class... Args>
  336. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  337. make_unique(Args &&...args) {
  338. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  339. }
  340. template <class T>
  341. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  342. make_unique(std::size_t n) {
  343. typedef typename std::remove_extent<T>::type RT;
  344. return std::unique_ptr<T>(new RT[n]);
  345. }
  346. namespace case_ignore {
  347. inline unsigned char to_lower(int c) {
  348. const static unsigned char table[256] = {
  349. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  350. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  351. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  352. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  353. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  354. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  355. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  356. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  357. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  358. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  359. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  360. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  361. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  362. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  363. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  364. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  365. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  366. 255,
  367. };
  368. return table[(unsigned char)(char)c];
  369. }
  370. inline bool equal(const std::string &a, const std::string &b) {
  371. return a.size() == b.size() &&
  372. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  373. return to_lower(ca) == to_lower(cb);
  374. });
  375. }
  376. struct equal_to {
  377. bool operator()(const std::string &a, const std::string &b) const {
  378. return equal(a, b);
  379. }
  380. };
  381. struct hash {
  382. size_t operator()(const std::string &key) const {
  383. return hash_core(key.data(), key.size(), 0);
  384. }
  385. size_t hash_core(const char *s, size_t l, size_t h) const {
  386. return (l == 0) ? h
  387. : hash_core(s + 1, l - 1,
  388. // Unsets the 6 high bits of h, therefore no
  389. // overflow happens
  390. (((std::numeric_limits<size_t>::max)() >> 6) &
  391. h * 33) ^
  392. static_cast<unsigned char>(to_lower(*s)));
  393. }
  394. };
  395. template <typename T>
  396. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  397. detail::case_ignore::equal_to>;
  398. } // namespace case_ignore
  399. // This is based on
  400. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  401. struct scope_exit {
  402. explicit scope_exit(std::function<void(void)> &&f)
  403. : exit_function(std::move(f)), execute_on_destruction{true} {}
  404. scope_exit(scope_exit &&rhs) noexcept
  405. : exit_function(std::move(rhs.exit_function)),
  406. execute_on_destruction{rhs.execute_on_destruction} {
  407. rhs.release();
  408. }
  409. ~scope_exit() {
  410. if (execute_on_destruction) { this->exit_function(); }
  411. }
  412. void release() { this->execute_on_destruction = false; }
  413. private:
  414. scope_exit(const scope_exit &) = delete;
  415. void operator=(const scope_exit &) = delete;
  416. scope_exit &operator=(scope_exit &&) = delete;
  417. std::function<void(void)> exit_function;
  418. bool execute_on_destruction;
  419. };
  420. // Simple from_chars implementation for integer and double types (C++17
  421. // substitute)
  422. template <typename T> struct from_chars_result {
  423. const char *ptr;
  424. std::errc ec;
  425. };
  426. template <typename T>
  427. inline from_chars_result<T> from_chars(const char *first, const char *last,
  428. T &value, int base = 10) {
  429. value = 0;
  430. const char *p = first;
  431. bool negative = false;
  432. if (p != last && *p == '-') {
  433. negative = true;
  434. ++p;
  435. }
  436. if (p == last) { return {first, std::errc::invalid_argument}; }
  437. T result = 0;
  438. for (; p != last; ++p) {
  439. char c = *p;
  440. int digit = -1;
  441. if ('0' <= c && c <= '9') {
  442. digit = c - '0';
  443. } else if ('a' <= c && c <= 'z') {
  444. digit = c - 'a' + 10;
  445. } else if ('A' <= c && c <= 'Z') {
  446. digit = c - 'A' + 10;
  447. } else {
  448. break;
  449. }
  450. if (digit < 0 || digit >= base) { break; }
  451. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  452. return {p, std::errc::result_out_of_range};
  453. }
  454. result = result * base + digit;
  455. }
  456. if (p == first || (negative && p == first + 1)) {
  457. return {first, std::errc::invalid_argument};
  458. }
  459. value = negative ? -result : result;
  460. return {p, std::errc{}};
  461. }
  462. // from_chars for double (simple wrapper for strtod)
  463. inline from_chars_result<double> from_chars(const char *first, const char *last,
  464. double &value) {
  465. std::string s(first, last);
  466. char *endptr = nullptr;
  467. errno = 0;
  468. value = std::strtod(s.c_str(), &endptr);
  469. if (endptr == s.c_str()) { return {first, std::errc::invalid_argument}; }
  470. if (errno == ERANGE) {
  471. return {first + (endptr - s.c_str()), std::errc::result_out_of_range};
  472. }
  473. return {first + (endptr - s.c_str()), std::errc{}};
  474. }
  475. } // namespace detail
  476. enum SSLVerifierResponse {
  477. // no decision has been made, use the built-in certificate verifier
  478. NoDecisionMade,
  479. // connection certificate is verified and accepted
  480. CertificateAccepted,
  481. // connection certificate was processed but is rejected
  482. CertificateRejected
  483. };
  484. enum StatusCode {
  485. // Information responses
  486. Continue_100 = 100,
  487. SwitchingProtocol_101 = 101,
  488. Processing_102 = 102,
  489. EarlyHints_103 = 103,
  490. // Successful responses
  491. OK_200 = 200,
  492. Created_201 = 201,
  493. Accepted_202 = 202,
  494. NonAuthoritativeInformation_203 = 203,
  495. NoContent_204 = 204,
  496. ResetContent_205 = 205,
  497. PartialContent_206 = 206,
  498. MultiStatus_207 = 207,
  499. AlreadyReported_208 = 208,
  500. IMUsed_226 = 226,
  501. // Redirection messages
  502. MultipleChoices_300 = 300,
  503. MovedPermanently_301 = 301,
  504. Found_302 = 302,
  505. SeeOther_303 = 303,
  506. NotModified_304 = 304,
  507. UseProxy_305 = 305,
  508. unused_306 = 306,
  509. TemporaryRedirect_307 = 307,
  510. PermanentRedirect_308 = 308,
  511. // Client error responses
  512. BadRequest_400 = 400,
  513. Unauthorized_401 = 401,
  514. PaymentRequired_402 = 402,
  515. Forbidden_403 = 403,
  516. NotFound_404 = 404,
  517. MethodNotAllowed_405 = 405,
  518. NotAcceptable_406 = 406,
  519. ProxyAuthenticationRequired_407 = 407,
  520. RequestTimeout_408 = 408,
  521. Conflict_409 = 409,
  522. Gone_410 = 410,
  523. LengthRequired_411 = 411,
  524. PreconditionFailed_412 = 412,
  525. PayloadTooLarge_413 = 413,
  526. UriTooLong_414 = 414,
  527. UnsupportedMediaType_415 = 415,
  528. RangeNotSatisfiable_416 = 416,
  529. ExpectationFailed_417 = 417,
  530. ImATeapot_418 = 418,
  531. MisdirectedRequest_421 = 421,
  532. UnprocessableContent_422 = 422,
  533. Locked_423 = 423,
  534. FailedDependency_424 = 424,
  535. TooEarly_425 = 425,
  536. UpgradeRequired_426 = 426,
  537. PreconditionRequired_428 = 428,
  538. TooManyRequests_429 = 429,
  539. RequestHeaderFieldsTooLarge_431 = 431,
  540. UnavailableForLegalReasons_451 = 451,
  541. // Server error responses
  542. InternalServerError_500 = 500,
  543. NotImplemented_501 = 501,
  544. BadGateway_502 = 502,
  545. ServiceUnavailable_503 = 503,
  546. GatewayTimeout_504 = 504,
  547. HttpVersionNotSupported_505 = 505,
  548. VariantAlsoNegotiates_506 = 506,
  549. InsufficientStorage_507 = 507,
  550. LoopDetected_508 = 508,
  551. NotExtended_510 = 510,
  552. NetworkAuthenticationRequired_511 = 511,
  553. };
  554. using Headers =
  555. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  556. detail::case_ignore::equal_to>;
  557. using Params = std::multimap<std::string, std::string>;
  558. using Match = std::smatch;
  559. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  560. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  561. struct Response;
  562. using ResponseHandler = std::function<bool(const Response &response)>;
  563. struct FormData {
  564. std::string name;
  565. std::string content;
  566. std::string filename;
  567. std::string content_type;
  568. Headers headers;
  569. };
  570. struct FormField {
  571. std::string name;
  572. std::string content;
  573. Headers headers;
  574. };
  575. using FormFields = std::multimap<std::string, FormField>;
  576. using FormFiles = std::multimap<std::string, FormData>;
  577. struct MultipartFormData {
  578. FormFields fields; // Text fields from multipart
  579. FormFiles files; // Files from multipart
  580. // Text field access
  581. std::string get_field(const std::string &key, size_t id = 0) const;
  582. std::vector<std::string> get_fields(const std::string &key) const;
  583. bool has_field(const std::string &key) const;
  584. size_t get_field_count(const std::string &key) const;
  585. // File access
  586. FormData get_file(const std::string &key, size_t id = 0) const;
  587. std::vector<FormData> get_files(const std::string &key) const;
  588. bool has_file(const std::string &key) const;
  589. size_t get_file_count(const std::string &key) const;
  590. };
  591. struct UploadFormData {
  592. std::string name;
  593. std::string content;
  594. std::string filename;
  595. std::string content_type;
  596. };
  597. using UploadFormDataItems = std::vector<UploadFormData>;
  598. class DataSink {
  599. public:
  600. DataSink() : os(&sb_), sb_(*this) {}
  601. DataSink(const DataSink &) = delete;
  602. DataSink &operator=(const DataSink &) = delete;
  603. DataSink(DataSink &&) = delete;
  604. DataSink &operator=(DataSink &&) = delete;
  605. std::function<bool(const char *data, size_t data_len)> write;
  606. std::function<bool()> is_writable;
  607. std::function<void()> done;
  608. std::function<void(const Headers &trailer)> done_with_trailer;
  609. std::ostream os;
  610. private:
  611. class data_sink_streambuf final : public std::streambuf {
  612. public:
  613. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  614. protected:
  615. std::streamsize xsputn(const char *s, std::streamsize n) override {
  616. sink_.write(s, static_cast<size_t>(n));
  617. return n;
  618. }
  619. private:
  620. DataSink &sink_;
  621. };
  622. data_sink_streambuf sb_;
  623. };
  624. using ContentProvider =
  625. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  626. using ContentProviderWithoutLength =
  627. std::function<bool(size_t offset, DataSink &sink)>;
  628. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  629. struct FormDataProvider {
  630. std::string name;
  631. ContentProviderWithoutLength provider;
  632. std::string filename;
  633. std::string content_type;
  634. };
  635. using FormDataProviderItems = std::vector<FormDataProvider>;
  636. using ContentReceiverWithProgress = std::function<bool(
  637. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  638. using ContentReceiver =
  639. std::function<bool(const char *data, size_t data_length)>;
  640. using FormDataHeader = std::function<bool(const FormData &file)>;
  641. class ContentReader {
  642. public:
  643. using Reader = std::function<bool(ContentReceiver receiver)>;
  644. using FormDataReader =
  645. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  646. ContentReader(Reader reader, FormDataReader multipart_reader)
  647. : reader_(std::move(reader)),
  648. formdata_reader_(std::move(multipart_reader)) {}
  649. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  650. return formdata_reader_(std::move(header), std::move(receiver));
  651. }
  652. bool operator()(ContentReceiver receiver) const {
  653. return reader_(std::move(receiver));
  654. }
  655. Reader reader_;
  656. FormDataReader formdata_reader_;
  657. };
  658. using Range = std::pair<ssize_t, ssize_t>;
  659. using Ranges = std::vector<Range>;
  660. struct Request {
  661. std::string method;
  662. std::string path;
  663. std::string matched_route;
  664. Params params;
  665. Headers headers;
  666. Headers trailers;
  667. std::string body;
  668. std::string remote_addr;
  669. int remote_port = -1;
  670. std::string local_addr;
  671. int local_port = -1;
  672. // for server
  673. std::string version;
  674. std::string target;
  675. MultipartFormData form;
  676. Ranges ranges;
  677. Match matches;
  678. std::unordered_map<std::string, std::string> path_params;
  679. std::function<bool()> is_connection_closed = []() { return true; };
  680. // for client
  681. std::vector<std::string> accept_content_types;
  682. ResponseHandler response_handler;
  683. ContentReceiverWithProgress content_receiver;
  684. DownloadProgress download_progress;
  685. UploadProgress upload_progress;
  686. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  687. const SSL *ssl = nullptr;
  688. #endif
  689. bool has_header(const std::string &key) const;
  690. std::string get_header_value(const std::string &key, const char *def = "",
  691. size_t id = 0) const;
  692. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  693. size_t id = 0) const;
  694. size_t get_header_value_count(const std::string &key) const;
  695. void set_header(const std::string &key, const std::string &val);
  696. bool has_trailer(const std::string &key) const;
  697. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  698. size_t get_trailer_value_count(const std::string &key) const;
  699. bool has_param(const std::string &key) const;
  700. std::string get_param_value(const std::string &key, size_t id = 0) const;
  701. size_t get_param_value_count(const std::string &key) const;
  702. bool is_multipart_form_data() const;
  703. // private members...
  704. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  705. size_t content_length_ = 0;
  706. ContentProvider content_provider_;
  707. bool is_chunked_content_provider_ = false;
  708. size_t authorization_count_ = 0;
  709. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  710. (std::chrono::steady_clock::time_point::min)();
  711. };
  712. struct Response {
  713. std::string version;
  714. int status = -1;
  715. std::string reason;
  716. Headers headers;
  717. Headers trailers;
  718. std::string body;
  719. std::string location; // Redirect location
  720. bool has_header(const std::string &key) const;
  721. std::string get_header_value(const std::string &key, const char *def = "",
  722. size_t id = 0) const;
  723. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  724. size_t id = 0) const;
  725. size_t get_header_value_count(const std::string &key) const;
  726. void set_header(const std::string &key, const std::string &val);
  727. bool has_trailer(const std::string &key) const;
  728. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  729. size_t get_trailer_value_count(const std::string &key) const;
  730. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  731. void set_content(const char *s, size_t n, const std::string &content_type);
  732. void set_content(const std::string &s, const std::string &content_type);
  733. void set_content(std::string &&s, const std::string &content_type);
  734. void set_content_provider(
  735. size_t length, const std::string &content_type, ContentProvider provider,
  736. ContentProviderResourceReleaser resource_releaser = nullptr);
  737. void set_content_provider(
  738. const std::string &content_type, ContentProviderWithoutLength provider,
  739. ContentProviderResourceReleaser resource_releaser = nullptr);
  740. void set_chunked_content_provider(
  741. const std::string &content_type, ContentProviderWithoutLength provider,
  742. ContentProviderResourceReleaser resource_releaser = nullptr);
  743. void set_file_content(const std::string &path,
  744. const std::string &content_type);
  745. void set_file_content(const std::string &path);
  746. Response() = default;
  747. Response(const Response &) = default;
  748. Response &operator=(const Response &) = default;
  749. Response(Response &&) = default;
  750. Response &operator=(Response &&) = default;
  751. ~Response() {
  752. if (content_provider_resource_releaser_) {
  753. content_provider_resource_releaser_(content_provider_success_);
  754. }
  755. }
  756. // private members...
  757. size_t content_length_ = 0;
  758. ContentProvider content_provider_;
  759. ContentProviderResourceReleaser content_provider_resource_releaser_;
  760. bool is_chunked_content_provider_ = false;
  761. bool content_provider_success_ = false;
  762. std::string file_content_path_;
  763. std::string file_content_content_type_;
  764. };
  765. enum class Error {
  766. Success = 0,
  767. Unknown,
  768. Connection,
  769. BindIPAddress,
  770. Read,
  771. Write,
  772. ExceedRedirectCount,
  773. Canceled,
  774. SSLConnection,
  775. SSLLoadingCerts,
  776. SSLServerVerification,
  777. SSLServerHostnameVerification,
  778. UnsupportedMultipartBoundaryChars,
  779. Compression,
  780. ConnectionTimeout,
  781. ProxyConnection,
  782. ConnectionClosed,
  783. Timeout,
  784. ResourceExhaustion,
  785. TooManyFormDataFiles,
  786. ExceedMaxPayloadSize,
  787. ExceedUriMaxLength,
  788. ExceedMaxSocketDescriptorCount,
  789. InvalidRequestLine,
  790. InvalidHTTPMethod,
  791. InvalidHTTPVersion,
  792. InvalidHeaders,
  793. MultipartParsing,
  794. OpenFile,
  795. Listen,
  796. GetSockName,
  797. UnsupportedAddressFamily,
  798. HTTPParsing,
  799. InvalidRangeHeader,
  800. // For internal use only
  801. SSLPeerCouldBeClosed_,
  802. };
  803. std::string to_string(Error error);
  804. std::ostream &operator<<(std::ostream &os, const Error &obj);
  805. class Stream {
  806. public:
  807. virtual ~Stream() = default;
  808. virtual bool is_readable() const = 0;
  809. virtual bool wait_readable() const = 0;
  810. virtual bool wait_writable() const = 0;
  811. virtual ssize_t read(char *ptr, size_t size) = 0;
  812. virtual ssize_t write(const char *ptr, size_t size) = 0;
  813. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  814. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  815. virtual socket_t socket() const = 0;
  816. virtual time_t duration() const = 0;
  817. ssize_t write(const char *ptr);
  818. ssize_t write(const std::string &s);
  819. Error get_error() const { return error_; }
  820. protected:
  821. Error error_ = Error::Success;
  822. };
  823. class TaskQueue {
  824. public:
  825. TaskQueue() = default;
  826. virtual ~TaskQueue() = default;
  827. virtual bool enqueue(std::function<void()> fn) = 0;
  828. virtual void shutdown() = 0;
  829. virtual void on_idle() {}
  830. };
  831. class ThreadPool final : public TaskQueue {
  832. public:
  833. explicit ThreadPool(size_t n, size_t mqr = 0)
  834. : shutdown_(false), max_queued_requests_(mqr) {
  835. threads_.reserve(n);
  836. while (n) {
  837. threads_.emplace_back(worker(*this));
  838. n--;
  839. }
  840. }
  841. ThreadPool(const ThreadPool &) = delete;
  842. ~ThreadPool() override = default;
  843. bool enqueue(std::function<void()> fn) override {
  844. {
  845. std::unique_lock<std::mutex> lock(mutex_);
  846. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  847. return false;
  848. }
  849. jobs_.push_back(std::move(fn));
  850. }
  851. cond_.notify_one();
  852. return true;
  853. }
  854. void shutdown() override {
  855. // Stop all worker threads...
  856. {
  857. std::unique_lock<std::mutex> lock(mutex_);
  858. shutdown_ = true;
  859. }
  860. cond_.notify_all();
  861. // Join...
  862. for (auto &t : threads_) {
  863. t.join();
  864. }
  865. }
  866. private:
  867. struct worker {
  868. explicit worker(ThreadPool &pool) : pool_(pool) {}
  869. void operator()() {
  870. for (;;) {
  871. std::function<void()> fn;
  872. {
  873. std::unique_lock<std::mutex> lock(pool_.mutex_);
  874. pool_.cond_.wait(
  875. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  876. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  877. fn = pool_.jobs_.front();
  878. pool_.jobs_.pop_front();
  879. }
  880. assert(true == static_cast<bool>(fn));
  881. fn();
  882. }
  883. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  884. !defined(LIBRESSL_VERSION_NUMBER)
  885. OPENSSL_thread_stop();
  886. #endif
  887. }
  888. ThreadPool &pool_;
  889. };
  890. friend struct worker;
  891. std::vector<std::thread> threads_;
  892. std::list<std::function<void()>> jobs_;
  893. bool shutdown_;
  894. size_t max_queued_requests_ = 0;
  895. std::condition_variable cond_;
  896. std::mutex mutex_;
  897. };
  898. using Logger = std::function<void(const Request &, const Response &)>;
  899. // Forward declaration for Error type
  900. enum class Error;
  901. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  902. using SocketOptions = std::function<void(socket_t sock)>;
  903. void default_socket_options(socket_t sock);
  904. const char *status_message(int status);
  905. std::string to_string(Error error);
  906. std::ostream &operator<<(std::ostream &os, const Error &obj);
  907. std::string get_bearer_token_auth(const Request &req);
  908. namespace detail {
  909. class MatcherBase {
  910. public:
  911. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  912. virtual ~MatcherBase() = default;
  913. const std::string &pattern() const { return pattern_; }
  914. // Match request path and populate its matches and
  915. virtual bool match(Request &request) const = 0;
  916. private:
  917. std::string pattern_;
  918. };
  919. /**
  920. * Captures parameters in request path and stores them in Request::path_params
  921. *
  922. * Capture name is a substring of a pattern from : to /.
  923. * The rest of the pattern is matched against the request path directly
  924. * Parameters are captured starting from the next character after
  925. * the end of the last matched static pattern fragment until the next /.
  926. *
  927. * Example pattern:
  928. * "/path/fragments/:capture/more/fragments/:second_capture"
  929. * Static fragments:
  930. * "/path/fragments/", "more/fragments/"
  931. *
  932. * Given the following request path:
  933. * "/path/fragments/:1/more/fragments/:2"
  934. * the resulting capture will be
  935. * {{"capture", "1"}, {"second_capture", "2"}}
  936. */
  937. class PathParamsMatcher final : public MatcherBase {
  938. public:
  939. PathParamsMatcher(const std::string &pattern);
  940. bool match(Request &request) const override;
  941. private:
  942. // Treat segment separators as the end of path parameter capture
  943. // Does not need to handle query parameters as they are parsed before path
  944. // matching
  945. static constexpr char separator = '/';
  946. // Contains static path fragments to match against, excluding the '/' after
  947. // path params
  948. // Fragments are separated by path params
  949. std::vector<std::string> static_fragments_;
  950. // Stores the names of the path parameters to be used as keys in the
  951. // Request::path_params map
  952. std::vector<std::string> param_names_;
  953. };
  954. /**
  955. * Performs std::regex_match on request path
  956. * and stores the result in Request::matches
  957. *
  958. * Note that regex match is performed directly on the whole request.
  959. * This means that wildcard patterns may match multiple path segments with /:
  960. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  961. */
  962. class RegexMatcher final : public MatcherBase {
  963. public:
  964. RegexMatcher(const std::string &pattern)
  965. : MatcherBase(pattern), regex_(pattern) {}
  966. bool match(Request &request) const override;
  967. private:
  968. std::regex regex_;
  969. };
  970. int close_socket(socket_t sock);
  971. ssize_t write_headers(Stream &strm, const Headers &headers);
  972. } // namespace detail
  973. class Server {
  974. public:
  975. using Handler = std::function<void(const Request &, Response &)>;
  976. using ExceptionHandler =
  977. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  978. enum class HandlerResponse {
  979. Handled,
  980. Unhandled,
  981. };
  982. using HandlerWithResponse =
  983. std::function<HandlerResponse(const Request &, Response &)>;
  984. using HandlerWithContentReader = std::function<void(
  985. const Request &, Response &, const ContentReader &content_reader)>;
  986. using Expect100ContinueHandler =
  987. std::function<int(const Request &, Response &)>;
  988. Server();
  989. virtual ~Server();
  990. virtual bool is_valid() const;
  991. Server &Get(const std::string &pattern, Handler handler);
  992. Server &Post(const std::string &pattern, Handler handler);
  993. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  994. Server &Put(const std::string &pattern, Handler handler);
  995. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  996. Server &Patch(const std::string &pattern, Handler handler);
  997. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  998. Server &Delete(const std::string &pattern, Handler handler);
  999. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1000. Server &Options(const std::string &pattern, Handler handler);
  1001. bool set_base_dir(const std::string &dir,
  1002. const std::string &mount_point = std::string());
  1003. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1004. Headers headers = Headers());
  1005. bool remove_mount_point(const std::string &mount_point);
  1006. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1007. const std::string &mime);
  1008. Server &set_default_file_mimetype(const std::string &mime);
  1009. Server &set_file_request_handler(Handler handler);
  1010. template <class ErrorHandlerFunc>
  1011. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1012. return set_error_handler_core(
  1013. std::forward<ErrorHandlerFunc>(handler),
  1014. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1015. }
  1016. Server &set_exception_handler(ExceptionHandler handler);
  1017. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1018. Server &set_post_routing_handler(Handler handler);
  1019. Server &set_pre_request_handler(HandlerWithResponse handler);
  1020. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1021. Server &set_logger(Logger logger);
  1022. Server &set_pre_compression_logger(Logger logger);
  1023. Server &set_error_logger(ErrorLogger error_logger);
  1024. Server &set_address_family(int family);
  1025. Server &set_tcp_nodelay(bool on);
  1026. Server &set_ipv6_v6only(bool on);
  1027. Server &set_socket_options(SocketOptions socket_options);
  1028. Server &set_default_headers(Headers headers);
  1029. Server &
  1030. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1031. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1032. Server &set_keep_alive_max_count(size_t count);
  1033. Server &set_keep_alive_timeout(time_t sec);
  1034. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1035. template <class Rep, class Period>
  1036. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1037. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1038. template <class Rep, class Period>
  1039. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1040. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1041. template <class Rep, class Period>
  1042. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1043. Server &set_payload_max_length(size_t length);
  1044. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1045. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1046. bool listen_after_bind();
  1047. bool listen(const std::string &host, int port, int socket_flags = 0);
  1048. bool is_running() const;
  1049. void wait_until_ready() const;
  1050. void stop();
  1051. void decommission();
  1052. std::function<TaskQueue *(void)> new_task_queue;
  1053. protected:
  1054. bool process_request(Stream &strm, const std::string &remote_addr,
  1055. int remote_port, const std::string &local_addr,
  1056. int local_port, bool close_connection,
  1057. bool &connection_closed,
  1058. const std::function<void(Request &)> &setup_request);
  1059. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1060. std::vector<std::string> trusted_proxies_;
  1061. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1062. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1063. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1064. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1065. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1066. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1067. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1068. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1069. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1070. private:
  1071. using Handlers =
  1072. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1073. using HandlersForContentReader =
  1074. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1075. HandlerWithContentReader>>;
  1076. static std::unique_ptr<detail::MatcherBase>
  1077. make_matcher(const std::string &pattern);
  1078. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1079. Server &set_error_handler_core(Handler handler, std::false_type);
  1080. socket_t create_server_socket(const std::string &host, int port,
  1081. int socket_flags,
  1082. SocketOptions socket_options) const;
  1083. int bind_internal(const std::string &host, int port, int socket_flags);
  1084. bool listen_internal();
  1085. bool routing(Request &req, Response &res, Stream &strm);
  1086. bool handle_file_request(Request &req, Response &res);
  1087. bool check_if_not_modified(const Request &req, Response &res,
  1088. const std::string &etag, time_t mtime) const;
  1089. bool check_if_range(Request &req, const std::string &etag,
  1090. time_t mtime) const;
  1091. bool dispatch_request(Request &req, Response &res,
  1092. const Handlers &handlers) const;
  1093. bool dispatch_request_for_content_reader(
  1094. Request &req, Response &res, ContentReader content_reader,
  1095. const HandlersForContentReader &handlers) const;
  1096. bool parse_request_line(const char *s, Request &req) const;
  1097. void apply_ranges(const Request &req, Response &res,
  1098. std::string &content_type, std::string &boundary) const;
  1099. bool write_response(Stream &strm, bool close_connection, Request &req,
  1100. Response &res);
  1101. bool write_response_with_content(Stream &strm, bool close_connection,
  1102. const Request &req, Response &res);
  1103. bool write_response_core(Stream &strm, bool close_connection,
  1104. const Request &req, Response &res,
  1105. bool need_apply_ranges);
  1106. bool write_content_with_provider(Stream &strm, const Request &req,
  1107. Response &res, const std::string &boundary,
  1108. const std::string &content_type);
  1109. bool read_content(Stream &strm, Request &req, Response &res);
  1110. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1111. Response &res,
  1112. ContentReceiver receiver,
  1113. FormDataHeader multipart_header,
  1114. ContentReceiver multipart_receiver);
  1115. bool read_content_core(Stream &strm, Request &req, Response &res,
  1116. ContentReceiver receiver,
  1117. FormDataHeader multipart_header,
  1118. ContentReceiver multipart_receiver) const;
  1119. virtual bool process_and_close_socket(socket_t sock);
  1120. void output_log(const Request &req, const Response &res) const;
  1121. void output_pre_compression_log(const Request &req,
  1122. const Response &res) const;
  1123. void output_error_log(const Error &err, const Request *req) const;
  1124. std::atomic<bool> is_running_{false};
  1125. std::atomic<bool> is_decommissioned{false};
  1126. struct MountPointEntry {
  1127. std::string mount_point;
  1128. std::string base_dir;
  1129. Headers headers;
  1130. };
  1131. std::vector<MountPointEntry> base_dirs_;
  1132. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1133. std::string default_file_mimetype_ = "application/octet-stream";
  1134. Handler file_request_handler_;
  1135. Handlers get_handlers_;
  1136. Handlers post_handlers_;
  1137. HandlersForContentReader post_handlers_for_content_reader_;
  1138. Handlers put_handlers_;
  1139. HandlersForContentReader put_handlers_for_content_reader_;
  1140. Handlers patch_handlers_;
  1141. HandlersForContentReader patch_handlers_for_content_reader_;
  1142. Handlers delete_handlers_;
  1143. HandlersForContentReader delete_handlers_for_content_reader_;
  1144. Handlers options_handlers_;
  1145. HandlerWithResponse error_handler_;
  1146. ExceptionHandler exception_handler_;
  1147. HandlerWithResponse pre_routing_handler_;
  1148. Handler post_routing_handler_;
  1149. HandlerWithResponse pre_request_handler_;
  1150. Expect100ContinueHandler expect_100_continue_handler_;
  1151. mutable std::mutex logger_mutex_;
  1152. Logger logger_;
  1153. Logger pre_compression_logger_;
  1154. ErrorLogger error_logger_;
  1155. int address_family_ = AF_UNSPEC;
  1156. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1157. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1158. SocketOptions socket_options_ = default_socket_options;
  1159. Headers default_headers_;
  1160. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1161. detail::write_headers;
  1162. };
  1163. class Result {
  1164. public:
  1165. Result() = default;
  1166. Result(std::unique_ptr<Response> &&res, Error err,
  1167. Headers &&request_headers = Headers{})
  1168. : res_(std::move(res)), err_(err),
  1169. request_headers_(std::move(request_headers)) {}
  1170. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1171. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1172. int ssl_error)
  1173. : res_(std::move(res)), err_(err),
  1174. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1175. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1176. int ssl_error, unsigned long ssl_openssl_error)
  1177. : res_(std::move(res)), err_(err),
  1178. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1179. ssl_openssl_error_(ssl_openssl_error) {}
  1180. #endif
  1181. // Response
  1182. operator bool() const { return res_ != nullptr; }
  1183. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1184. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1185. const Response &value() const { return *res_; }
  1186. Response &value() { return *res_; }
  1187. const Response &operator*() const { return *res_; }
  1188. Response &operator*() { return *res_; }
  1189. const Response *operator->() const { return res_.get(); }
  1190. Response *operator->() { return res_.get(); }
  1191. // Error
  1192. Error error() const { return err_; }
  1193. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1194. // SSL Error
  1195. int ssl_error() const { return ssl_error_; }
  1196. // OpenSSL Error
  1197. unsigned long ssl_openssl_error() const { return ssl_openssl_error_; }
  1198. #endif
  1199. // Request Headers
  1200. bool has_request_header(const std::string &key) const;
  1201. std::string get_request_header_value(const std::string &key,
  1202. const char *def = "",
  1203. size_t id = 0) const;
  1204. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1205. size_t id = 0) const;
  1206. size_t get_request_header_value_count(const std::string &key) const;
  1207. private:
  1208. std::unique_ptr<Response> res_;
  1209. Error err_ = Error::Unknown;
  1210. Headers request_headers_;
  1211. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1212. int ssl_error_ = 0;
  1213. unsigned long ssl_openssl_error_ = 0;
  1214. #endif
  1215. };
  1216. struct ClientConnection {
  1217. socket_t sock = INVALID_SOCKET;
  1218. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1219. SSL *ssl = nullptr;
  1220. #endif
  1221. bool is_open() const { return sock != INVALID_SOCKET; }
  1222. ClientConnection() = default;
  1223. ~ClientConnection() {
  1224. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1225. if (ssl) {
  1226. SSL_free(ssl);
  1227. ssl = nullptr;
  1228. }
  1229. #endif
  1230. if (sock != INVALID_SOCKET) {
  1231. detail::close_socket(sock);
  1232. sock = INVALID_SOCKET;
  1233. }
  1234. }
  1235. ClientConnection(const ClientConnection &) = delete;
  1236. ClientConnection &operator=(const ClientConnection &) = delete;
  1237. ClientConnection(ClientConnection &&other) noexcept
  1238. : sock(other.sock)
  1239. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1240. ,
  1241. ssl(other.ssl)
  1242. #endif
  1243. {
  1244. other.sock = INVALID_SOCKET;
  1245. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1246. other.ssl = nullptr;
  1247. #endif
  1248. }
  1249. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1250. if (this != &other) {
  1251. sock = other.sock;
  1252. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1253. ssl = other.ssl;
  1254. #endif
  1255. other.sock = INVALID_SOCKET;
  1256. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1257. other.ssl = nullptr;
  1258. #endif
  1259. }
  1260. return *this;
  1261. }
  1262. };
  1263. namespace detail {
  1264. struct ChunkedDecoder;
  1265. struct BodyReader {
  1266. Stream *stream = nullptr;
  1267. size_t content_length = 0;
  1268. size_t bytes_read = 0;
  1269. bool chunked = false;
  1270. bool eof = false;
  1271. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1272. Error last_error = Error::Success;
  1273. ssize_t read(char *buf, size_t len);
  1274. bool has_error() const { return last_error != Error::Success; }
  1275. };
  1276. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1277. size_t len) {
  1278. (void)stream;
  1279. return br.read(buf, len);
  1280. }
  1281. class decompressor;
  1282. } // namespace detail
  1283. class ClientImpl {
  1284. public:
  1285. explicit ClientImpl(const std::string &host);
  1286. explicit ClientImpl(const std::string &host, int port);
  1287. explicit ClientImpl(const std::string &host, int port,
  1288. const std::string &client_cert_path,
  1289. const std::string &client_key_path);
  1290. virtual ~ClientImpl();
  1291. virtual bool is_valid() const;
  1292. struct StreamHandle {
  1293. std::unique_ptr<Response> response;
  1294. Error error = Error::Success;
  1295. StreamHandle() = default;
  1296. StreamHandle(const StreamHandle &) = delete;
  1297. StreamHandle &operator=(const StreamHandle &) = delete;
  1298. StreamHandle(StreamHandle &&) = default;
  1299. StreamHandle &operator=(StreamHandle &&) = default;
  1300. ~StreamHandle() = default;
  1301. bool is_valid() const {
  1302. return response != nullptr && error == Error::Success;
  1303. }
  1304. ssize_t read(char *buf, size_t len);
  1305. void parse_trailers_if_needed();
  1306. Error get_read_error() const { return body_reader_.last_error; }
  1307. bool has_read_error() const { return body_reader_.has_error(); }
  1308. bool trailers_parsed_ = false;
  1309. private:
  1310. friend class ClientImpl;
  1311. ssize_t read_with_decompression(char *buf, size_t len);
  1312. std::unique_ptr<ClientConnection> connection_;
  1313. std::unique_ptr<Stream> socket_stream_;
  1314. Stream *stream_ = nullptr;
  1315. detail::BodyReader body_reader_;
  1316. std::unique_ptr<detail::decompressor> decompressor_;
  1317. std::string decompress_buffer_;
  1318. size_t decompress_offset_ = 0;
  1319. };
  1320. // clang-format off
  1321. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1322. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1323. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1324. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1325. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1326. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1327. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1328. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1329. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1330. Result Head(const std::string &path);
  1331. Result Head(const std::string &path, const Headers &headers);
  1332. Result Post(const std::string &path);
  1333. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1334. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1335. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1336. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1337. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1338. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1339. Result Post(const std::string &path, const Params &params);
  1340. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1341. Result Post(const std::string &path, const Headers &headers);
  1342. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1343. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1344. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1345. 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);
  1346. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1347. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1348. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1349. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1350. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1351. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1352. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1353. Result Put(const std::string &path);
  1354. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1355. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1356. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1357. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1358. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1359. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1360. Result Put(const std::string &path, const Params &params);
  1361. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1362. Result Put(const std::string &path, const Headers &headers);
  1363. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1364. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1365. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1366. 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);
  1367. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1368. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1369. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1370. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1371. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1372. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1373. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1374. Result Patch(const std::string &path);
  1375. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1376. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1377. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1378. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1379. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1380. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1381. Result Patch(const std::string &path, const Params &params);
  1382. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1383. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1384. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1385. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1386. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1387. 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);
  1388. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1389. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1390. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1391. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1392. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1393. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1394. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1395. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1396. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1397. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1398. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1399. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1400. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1401. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1402. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1403. Result Options(const std::string &path);
  1404. Result Options(const std::string &path, const Headers &headers);
  1405. // clang-format on
  1406. // Streaming API: Open a stream for reading response body incrementally
  1407. // Socket ownership is transferred to StreamHandle for true streaming
  1408. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1409. StreamHandle open_stream(const std::string &method, const std::string &path,
  1410. const Params &params = {},
  1411. const Headers &headers = {},
  1412. const std::string &body = {},
  1413. const std::string &content_type = {});
  1414. bool send(Request &req, Response &res, Error &error);
  1415. Result send(const Request &req);
  1416. void stop();
  1417. std::string host() const;
  1418. int port() const;
  1419. size_t is_socket_open() const;
  1420. socket_t socket() const;
  1421. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1422. void set_default_headers(Headers headers);
  1423. void
  1424. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1425. void set_address_family(int family);
  1426. void set_tcp_nodelay(bool on);
  1427. void set_ipv6_v6only(bool on);
  1428. void set_socket_options(SocketOptions socket_options);
  1429. void set_connection_timeout(time_t sec, time_t usec = 0);
  1430. template <class Rep, class Period>
  1431. void
  1432. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1433. void set_read_timeout(time_t sec, time_t usec = 0);
  1434. template <class Rep, class Period>
  1435. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1436. void set_write_timeout(time_t sec, time_t usec = 0);
  1437. template <class Rep, class Period>
  1438. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1439. void set_max_timeout(time_t msec);
  1440. template <class Rep, class Period>
  1441. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1442. void set_basic_auth(const std::string &username, const std::string &password);
  1443. void set_bearer_token_auth(const std::string &token);
  1444. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1445. void set_digest_auth(const std::string &username,
  1446. const std::string &password);
  1447. #endif
  1448. void set_keep_alive(bool on);
  1449. void set_follow_location(bool on);
  1450. void set_path_encode(bool on);
  1451. void set_compress(bool on);
  1452. void set_decompress(bool on);
  1453. void set_interface(const std::string &intf);
  1454. void set_proxy(const std::string &host, int port);
  1455. void set_proxy_basic_auth(const std::string &username,
  1456. const std::string &password);
  1457. void set_proxy_bearer_token_auth(const std::string &token);
  1458. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1459. void set_proxy_digest_auth(const std::string &username,
  1460. const std::string &password);
  1461. #endif
  1462. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1463. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1464. const std::string &ca_cert_dir_path = std::string());
  1465. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1466. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1467. #endif
  1468. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1469. void enable_server_certificate_verification(bool enabled);
  1470. void enable_server_hostname_verification(bool enabled);
  1471. void set_server_certificate_verifier(
  1472. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1473. #endif
  1474. void set_logger(Logger logger);
  1475. void set_error_logger(ErrorLogger error_logger);
  1476. protected:
  1477. struct Socket {
  1478. socket_t sock = INVALID_SOCKET;
  1479. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1480. SSL *ssl = nullptr;
  1481. #endif
  1482. bool is_open() const { return sock != INVALID_SOCKET; }
  1483. };
  1484. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1485. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1486. // All of:
  1487. // shutdown_ssl
  1488. // shutdown_socket
  1489. // close_socket
  1490. // should ONLY be called when socket_mutex_ is locked.
  1491. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1492. // with a DIFFERENT thread sending requests using that socket.
  1493. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1494. void shutdown_socket(Socket &socket) const;
  1495. void close_socket(Socket &socket);
  1496. bool process_request(Stream &strm, Request &req, Response &res,
  1497. bool close_connection, Error &error);
  1498. bool write_content_with_provider(Stream &strm, const Request &req,
  1499. Error &error) const;
  1500. void copy_settings(const ClientImpl &rhs);
  1501. void output_log(const Request &req, const Response &res) const;
  1502. void output_error_log(const Error &err, const Request *req) const;
  1503. // Socket endpoint information
  1504. const std::string host_;
  1505. const int port_;
  1506. // Current open socket
  1507. Socket socket_;
  1508. mutable std::mutex socket_mutex_;
  1509. std::recursive_mutex request_mutex_;
  1510. // These are all protected under socket_mutex
  1511. size_t socket_requests_in_flight_ = 0;
  1512. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1513. bool socket_should_be_closed_when_request_is_done_ = false;
  1514. // Hostname-IP map
  1515. std::map<std::string, std::string> addr_map_;
  1516. // Default headers
  1517. Headers default_headers_;
  1518. // Header writer
  1519. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1520. detail::write_headers;
  1521. // Settings
  1522. std::string client_cert_path_;
  1523. std::string client_key_path_;
  1524. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1525. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1526. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1527. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1528. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1529. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1530. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1531. std::string basic_auth_username_;
  1532. std::string basic_auth_password_;
  1533. std::string bearer_token_auth_token_;
  1534. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1535. std::string digest_auth_username_;
  1536. std::string digest_auth_password_;
  1537. #endif
  1538. bool keep_alive_ = false;
  1539. bool follow_location_ = false;
  1540. bool path_encode_ = true;
  1541. int address_family_ = AF_UNSPEC;
  1542. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1543. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1544. SocketOptions socket_options_ = nullptr;
  1545. bool compress_ = false;
  1546. bool decompress_ = true;
  1547. std::string interface_;
  1548. std::string proxy_host_;
  1549. int proxy_port_ = -1;
  1550. std::string proxy_basic_auth_username_;
  1551. std::string proxy_basic_auth_password_;
  1552. std::string proxy_bearer_token_auth_token_;
  1553. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1554. std::string proxy_digest_auth_username_;
  1555. std::string proxy_digest_auth_password_;
  1556. #endif
  1557. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1558. std::string ca_cert_file_path_;
  1559. std::string ca_cert_dir_path_;
  1560. X509_STORE *ca_cert_store_ = nullptr;
  1561. #endif
  1562. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1563. bool server_certificate_verification_ = true;
  1564. bool server_hostname_verification_ = true;
  1565. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1566. #endif
  1567. mutable std::mutex logger_mutex_;
  1568. Logger logger_;
  1569. ErrorLogger error_logger_;
  1570. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1571. int last_ssl_error_ = 0;
  1572. unsigned long last_openssl_error_ = 0;
  1573. #endif
  1574. private:
  1575. bool send_(Request &req, Response &res, Error &error);
  1576. Result send_(Request &&req);
  1577. socket_t create_client_socket(Error &error) const;
  1578. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1579. bool skip_100_continue = true) const;
  1580. bool write_request(Stream &strm, Request &req, bool close_connection,
  1581. Error &error, bool skip_body = false);
  1582. bool write_request_body(Stream &strm, Request &req, Error &error);
  1583. void prepare_default_headers(Request &r, bool for_stream,
  1584. const std::string &ct);
  1585. bool redirect(Request &req, Response &res, Error &error);
  1586. bool create_redirect_client(const std::string &scheme,
  1587. const std::string &host, int port, Request &req,
  1588. Response &res, const std::string &path,
  1589. const std::string &location, Error &error);
  1590. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1591. bool handle_request(Stream &strm, Request &req, Response &res,
  1592. bool close_connection, Error &error);
  1593. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1594. Request &req, const char *body, size_t content_length,
  1595. ContentProvider content_provider,
  1596. ContentProviderWithoutLength content_provider_without_length,
  1597. const std::string &content_type, ContentReceiver content_receiver,
  1598. Error &error);
  1599. Result send_with_content_provider_and_receiver(
  1600. const std::string &method, const std::string &path,
  1601. const Headers &headers, const char *body, size_t content_length,
  1602. ContentProvider content_provider,
  1603. ContentProviderWithoutLength content_provider_without_length,
  1604. const std::string &content_type, ContentReceiver content_receiver,
  1605. UploadProgress progress);
  1606. ContentProviderWithoutLength get_multipart_content_provider(
  1607. const std::string &boundary, const UploadFormDataItems &items,
  1608. const FormDataProviderItems &provider_items) const;
  1609. virtual bool
  1610. process_socket(const Socket &socket,
  1611. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1612. std::function<bool(Stream &strm)> callback);
  1613. virtual bool is_ssl() const;
  1614. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1615. };
  1616. class Client {
  1617. public:
  1618. // Universal interface
  1619. explicit Client(const std::string &scheme_host_port);
  1620. explicit Client(const std::string &scheme_host_port,
  1621. const std::string &client_cert_path,
  1622. const std::string &client_key_path);
  1623. // HTTP only interface
  1624. explicit Client(const std::string &host, int port);
  1625. explicit Client(const std::string &host, int port,
  1626. const std::string &client_cert_path,
  1627. const std::string &client_key_path);
  1628. Client(Client &&) = default;
  1629. Client &operator=(Client &&) = default;
  1630. ~Client();
  1631. bool is_valid() const;
  1632. // clang-format off
  1633. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1634. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1635. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1636. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1637. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1638. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1639. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1640. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1641. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1642. Result Head(const std::string &path);
  1643. Result Head(const std::string &path, const Headers &headers);
  1644. Result Post(const std::string &path);
  1645. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1646. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1647. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1648. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1649. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1650. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1651. Result Post(const std::string &path, const Params &params);
  1652. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1653. Result Post(const std::string &path, const Headers &headers);
  1654. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1655. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1656. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1657. 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);
  1658. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1659. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1660. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1661. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1662. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1663. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1664. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1665. Result Put(const std::string &path);
  1666. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1667. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1668. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1669. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1670. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1671. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1672. Result Put(const std::string &path, const Params &params);
  1673. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1674. Result Put(const std::string &path, const Headers &headers);
  1675. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1676. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1677. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1678. 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);
  1679. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1680. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1681. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1682. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1683. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1684. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1685. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1686. Result Patch(const std::string &path);
  1687. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1688. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1689. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1690. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1691. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1692. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1693. Result Patch(const std::string &path, const Params &params);
  1694. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1695. Result Patch(const std::string &path, const Headers &headers);
  1696. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1697. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1698. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1699. 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);
  1700. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1701. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1702. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1703. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1704. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1705. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1706. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1707. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1708. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1709. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1710. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1711. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1712. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1713. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1714. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1715. Result Options(const std::string &path);
  1716. Result Options(const std::string &path, const Headers &headers);
  1717. // clang-format on
  1718. // Streaming API: Open a stream for reading response body incrementally
  1719. // Socket ownership is transferred to StreamHandle for true streaming
  1720. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1721. ClientImpl::StreamHandle open_stream(const std::string &method,
  1722. const std::string &path,
  1723. const Params &params = {},
  1724. const Headers &headers = {},
  1725. const std::string &body = {},
  1726. const std::string &content_type = {});
  1727. bool send(Request &req, Response &res, Error &error);
  1728. Result send(const Request &req);
  1729. void stop();
  1730. std::string host() const;
  1731. int port() const;
  1732. size_t is_socket_open() const;
  1733. socket_t socket() const;
  1734. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1735. void set_default_headers(Headers headers);
  1736. void
  1737. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1738. void set_address_family(int family);
  1739. void set_tcp_nodelay(bool on);
  1740. void set_socket_options(SocketOptions socket_options);
  1741. void set_connection_timeout(time_t sec, time_t usec = 0);
  1742. template <class Rep, class Period>
  1743. void
  1744. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1745. void set_read_timeout(time_t sec, time_t usec = 0);
  1746. template <class Rep, class Period>
  1747. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1748. void set_write_timeout(time_t sec, time_t usec = 0);
  1749. template <class Rep, class Period>
  1750. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1751. void set_max_timeout(time_t msec);
  1752. template <class Rep, class Period>
  1753. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1754. void set_basic_auth(const std::string &username, const std::string &password);
  1755. void set_bearer_token_auth(const std::string &token);
  1756. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1757. void set_digest_auth(const std::string &username,
  1758. const std::string &password);
  1759. #endif
  1760. void set_keep_alive(bool on);
  1761. void set_follow_location(bool on);
  1762. void set_path_encode(bool on);
  1763. void set_url_encode(bool on);
  1764. void set_compress(bool on);
  1765. void set_decompress(bool on);
  1766. void set_interface(const std::string &intf);
  1767. void set_proxy(const std::string &host, int port);
  1768. void set_proxy_basic_auth(const std::string &username,
  1769. const std::string &password);
  1770. void set_proxy_bearer_token_auth(const std::string &token);
  1771. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1772. void set_proxy_digest_auth(const std::string &username,
  1773. const std::string &password);
  1774. #endif
  1775. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1776. void enable_server_certificate_verification(bool enabled);
  1777. void enable_server_hostname_verification(bool enabled);
  1778. void set_server_certificate_verifier(
  1779. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1780. #endif
  1781. void set_logger(Logger logger);
  1782. void set_error_logger(ErrorLogger error_logger);
  1783. // SSL
  1784. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1785. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1786. const std::string &ca_cert_dir_path = std::string());
  1787. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1788. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1789. long get_openssl_verify_result() const;
  1790. SSL_CTX *ssl_context() const;
  1791. #endif
  1792. private:
  1793. std::unique_ptr<ClientImpl> cli_;
  1794. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1795. bool is_ssl_ = false;
  1796. #endif
  1797. };
  1798. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1799. class SSLServer : public Server {
  1800. public:
  1801. SSLServer(const char *cert_path, const char *private_key_path,
  1802. const char *client_ca_cert_file_path = nullptr,
  1803. const char *client_ca_cert_dir_path = nullptr,
  1804. const char *private_key_password = nullptr);
  1805. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1806. X509_STORE *client_ca_cert_store = nullptr);
  1807. SSLServer(
  1808. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1809. ~SSLServer() override;
  1810. bool is_valid() const override;
  1811. SSL_CTX *ssl_context() const;
  1812. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1813. X509_STORE *client_ca_cert_store = nullptr);
  1814. int ssl_last_error() const { return last_ssl_error_; }
  1815. private:
  1816. bool process_and_close_socket(socket_t sock) override;
  1817. STACK_OF(X509_NAME) * extract_ca_names_from_x509_store(X509_STORE *store);
  1818. SSL_CTX *ctx_;
  1819. std::mutex ctx_mutex_;
  1820. int last_ssl_error_ = 0;
  1821. };
  1822. class SSLClient final : public ClientImpl {
  1823. public:
  1824. explicit SSLClient(const std::string &host);
  1825. explicit SSLClient(const std::string &host, int port);
  1826. explicit SSLClient(const std::string &host, int port,
  1827. const std::string &client_cert_path,
  1828. const std::string &client_key_path,
  1829. const std::string &private_key_password = std::string());
  1830. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1831. EVP_PKEY *client_key,
  1832. const std::string &private_key_password = std::string());
  1833. ~SSLClient() override;
  1834. bool is_valid() const override;
  1835. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1836. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1837. long get_openssl_verify_result() const;
  1838. SSL_CTX *ssl_context() const;
  1839. private:
  1840. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1841. bool ensure_socket_connection(Socket &socket, Error &error) override;
  1842. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1843. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1844. bool
  1845. process_socket(const Socket &socket,
  1846. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1847. std::function<bool(Stream &strm)> callback) override;
  1848. bool is_ssl() const override;
  1849. bool connect_with_proxy(
  1850. Socket &sock,
  1851. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1852. Response &res, bool &success, Error &error);
  1853. bool initialize_ssl(Socket &socket, Error &error);
  1854. bool load_certs();
  1855. bool verify_host(X509 *server_cert) const;
  1856. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1857. bool verify_host_with_common_name(X509 *server_cert) const;
  1858. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1859. SSL_CTX *ctx_;
  1860. std::mutex ctx_mutex_;
  1861. std::once_flag initialize_cert_;
  1862. std::vector<std::string> host_components_;
  1863. long verify_result_ = 0;
  1864. friend class ClientImpl;
  1865. };
  1866. #endif
  1867. /*
  1868. * Implementation of template methods.
  1869. */
  1870. namespace detail {
  1871. template <typename T, typename U>
  1872. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1873. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1874. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1875. duration - std::chrono::seconds(sec))
  1876. .count();
  1877. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1878. }
  1879. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1880. return N - 1;
  1881. }
  1882. inline bool is_numeric(const std::string &str) {
  1883. return !str.empty() &&
  1884. std::all_of(str.cbegin(), str.cend(),
  1885. [](unsigned char c) { return std::isdigit(c); });
  1886. }
  1887. inline size_t get_header_value_u64(const Headers &headers,
  1888. const std::string &key, size_t def,
  1889. size_t id, bool &is_invalid_value) {
  1890. is_invalid_value = false;
  1891. auto rng = headers.equal_range(key);
  1892. auto it = rng.first;
  1893. std::advance(it, static_cast<ssize_t>(id));
  1894. if (it != rng.second) {
  1895. if (is_numeric(it->second)) {
  1896. return std::strtoull(it->second.data(), nullptr, 10);
  1897. } else {
  1898. is_invalid_value = true;
  1899. }
  1900. }
  1901. return def;
  1902. }
  1903. inline size_t get_header_value_u64(const Headers &headers,
  1904. const std::string &key, size_t def,
  1905. size_t id) {
  1906. auto dummy = false;
  1907. return get_header_value_u64(headers, key, def, id, dummy);
  1908. }
  1909. } // namespace detail
  1910. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  1911. size_t id) const {
  1912. return detail::get_header_value_u64(headers, key, def, id);
  1913. }
  1914. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  1915. size_t id) const {
  1916. return detail::get_header_value_u64(headers, key, def, id);
  1917. }
  1918. namespace detail {
  1919. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1920. const void *optval, socklen_t optlen) {
  1921. return setsockopt(sock, level, optname,
  1922. #ifdef _WIN32
  1923. reinterpret_cast<const char *>(optval),
  1924. #else
  1925. optval,
  1926. #endif
  1927. optlen) == 0;
  1928. }
  1929. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1930. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1931. }
  1932. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1933. time_t sec, time_t usec) {
  1934. #ifdef _WIN32
  1935. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1936. #else
  1937. timeval timeout;
  1938. timeout.tv_sec = static_cast<long>(sec);
  1939. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1940. #endif
  1941. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  1942. }
  1943. } // namespace detail
  1944. inline void default_socket_options(socket_t sock) {
  1945. detail::set_socket_opt(sock, SOL_SOCKET,
  1946. #ifdef SO_REUSEPORT
  1947. SO_REUSEPORT,
  1948. #else
  1949. SO_REUSEADDR,
  1950. #endif
  1951. 1);
  1952. }
  1953. inline std::string get_bearer_token_auth(const Request &req) {
  1954. if (req.has_header("Authorization")) {
  1955. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  1956. return req.get_header_value("Authorization")
  1957. .substr(bearer_header_prefix_len);
  1958. }
  1959. return "";
  1960. }
  1961. template <class Rep, class Period>
  1962. inline Server &
  1963. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1964. detail::duration_to_sec_and_usec(
  1965. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1966. return *this;
  1967. }
  1968. template <class Rep, class Period>
  1969. inline Server &
  1970. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1971. detail::duration_to_sec_and_usec(
  1972. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1973. return *this;
  1974. }
  1975. template <class Rep, class Period>
  1976. inline Server &
  1977. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  1978. detail::duration_to_sec_and_usec(
  1979. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  1980. return *this;
  1981. }
  1982. inline size_t Result::get_request_header_value_u64(const std::string &key,
  1983. size_t def,
  1984. size_t id) const {
  1985. return detail::get_header_value_u64(request_headers_, key, def, id);
  1986. }
  1987. template <class Rep, class Period>
  1988. inline void ClientImpl::set_connection_timeout(
  1989. const std::chrono::duration<Rep, Period> &duration) {
  1990. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  1991. set_connection_timeout(sec, usec);
  1992. });
  1993. }
  1994. template <class Rep, class Period>
  1995. inline void ClientImpl::set_read_timeout(
  1996. const std::chrono::duration<Rep, Period> &duration) {
  1997. detail::duration_to_sec_and_usec(
  1998. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1999. }
  2000. template <class Rep, class Period>
  2001. inline void ClientImpl::set_write_timeout(
  2002. const std::chrono::duration<Rep, Period> &duration) {
  2003. detail::duration_to_sec_and_usec(
  2004. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2005. }
  2006. template <class Rep, class Period>
  2007. inline void ClientImpl::set_max_timeout(
  2008. const std::chrono::duration<Rep, Period> &duration) {
  2009. auto msec =
  2010. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2011. set_max_timeout(msec);
  2012. }
  2013. template <class Rep, class Period>
  2014. inline void Client::set_connection_timeout(
  2015. const std::chrono::duration<Rep, Period> &duration) {
  2016. cli_->set_connection_timeout(duration);
  2017. }
  2018. template <class Rep, class Period>
  2019. inline void
  2020. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2021. cli_->set_read_timeout(duration);
  2022. }
  2023. template <class Rep, class Period>
  2024. inline void
  2025. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2026. cli_->set_write_timeout(duration);
  2027. }
  2028. inline void Client::set_max_timeout(time_t msec) {
  2029. cli_->set_max_timeout(msec);
  2030. }
  2031. template <class Rep, class Period>
  2032. inline void
  2033. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2034. cli_->set_max_timeout(duration);
  2035. }
  2036. /*
  2037. * Forward declarations and types that will be part of the .h file if split into
  2038. * .h + .cc.
  2039. */
  2040. std::string hosted_at(const std::string &hostname);
  2041. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2042. // JavaScript-style URL encoding/decoding functions
  2043. std::string encode_uri_component(const std::string &value);
  2044. std::string encode_uri(const std::string &value);
  2045. std::string decode_uri_component(const std::string &value);
  2046. std::string decode_uri(const std::string &value);
  2047. // RFC 3986 compliant URL component encoding/decoding functions
  2048. std::string encode_path_component(const std::string &component);
  2049. std::string decode_path_component(const std::string &component);
  2050. std::string encode_query_component(const std::string &component,
  2051. bool space_as_plus = true);
  2052. std::string decode_query_component(const std::string &component,
  2053. bool plus_as_space = true);
  2054. std::string append_query_params(const std::string &path, const Params &params);
  2055. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2056. std::pair<std::string, std::string>
  2057. make_basic_authentication_header(const std::string &username,
  2058. const std::string &password,
  2059. bool is_proxy = false);
  2060. namespace detail {
  2061. #if defined(_WIN32)
  2062. inline std::wstring u8string_to_wstring(const char *s) {
  2063. if (!s) { return std::wstring(); }
  2064. auto len = static_cast<int>(strlen(s));
  2065. if (!len) { return std::wstring(); }
  2066. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2067. if (!wlen) { return std::wstring(); }
  2068. std::wstring ws;
  2069. ws.resize(wlen);
  2070. wlen = ::MultiByteToWideChar(
  2071. CP_UTF8, 0, s, len,
  2072. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2073. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2074. return ws;
  2075. }
  2076. #endif
  2077. struct FileStat {
  2078. FileStat(const std::string &path);
  2079. bool is_file() const;
  2080. bool is_dir() const;
  2081. time_t mtime() const;
  2082. size_t size() const;
  2083. private:
  2084. #if defined(_WIN32)
  2085. struct _stat st_;
  2086. #else
  2087. struct stat st_;
  2088. #endif
  2089. int ret_ = -1;
  2090. };
  2091. std::string make_host_and_port_string(const std::string &host, int port,
  2092. bool is_ssl);
  2093. std::string trim_copy(const std::string &s);
  2094. void divide(
  2095. const char *data, std::size_t size, char d,
  2096. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2097. fn);
  2098. void divide(
  2099. const std::string &str, char d,
  2100. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2101. fn);
  2102. void split(const char *b, const char *e, char d,
  2103. std::function<void(const char *, const char *)> fn);
  2104. void split(const char *b, const char *e, char d, size_t m,
  2105. std::function<void(const char *, const char *)> fn);
  2106. bool process_client_socket(
  2107. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2108. time_t write_timeout_sec, time_t write_timeout_usec,
  2109. time_t max_timeout_msec,
  2110. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2111. std::function<bool(Stream &)> callback);
  2112. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2113. int port, int address_family, bool tcp_nodelay,
  2114. bool ipv6_v6only, SocketOptions socket_options,
  2115. time_t connection_timeout_sec,
  2116. time_t connection_timeout_usec,
  2117. time_t read_timeout_sec, time_t read_timeout_usec,
  2118. time_t write_timeout_sec,
  2119. time_t write_timeout_usec,
  2120. const std::string &intf, Error &error);
  2121. const char *get_header_value(const Headers &headers, const std::string &key,
  2122. const char *def, size_t id);
  2123. std::string params_to_query_str(const Params &params);
  2124. void parse_query_text(const char *data, std::size_t size, Params &params);
  2125. void parse_query_text(const std::string &s, Params &params);
  2126. bool parse_multipart_boundary(const std::string &content_type,
  2127. std::string &boundary);
  2128. bool parse_range_header(const std::string &s, Ranges &ranges);
  2129. bool parse_accept_header(const std::string &s,
  2130. std::vector<std::string> &content_types);
  2131. int close_socket(socket_t sock);
  2132. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2133. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2134. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2135. EncodingType encoding_type(const Request &req, const Response &res);
  2136. class BufferStream final : public Stream {
  2137. public:
  2138. BufferStream() = default;
  2139. ~BufferStream() override = default;
  2140. bool is_readable() const override;
  2141. bool wait_readable() const override;
  2142. bool wait_writable() const override;
  2143. ssize_t read(char *ptr, size_t size) override;
  2144. ssize_t write(const char *ptr, size_t size) override;
  2145. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2146. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2147. socket_t socket() const override;
  2148. time_t duration() const override;
  2149. const std::string &get_buffer() const;
  2150. private:
  2151. std::string buffer;
  2152. size_t position = 0;
  2153. };
  2154. class compressor {
  2155. public:
  2156. virtual ~compressor() = default;
  2157. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2158. virtual bool compress(const char *data, size_t data_length, bool last,
  2159. Callback callback) = 0;
  2160. };
  2161. class decompressor {
  2162. public:
  2163. virtual ~decompressor() = default;
  2164. virtual bool is_valid() const = 0;
  2165. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2166. virtual bool decompress(const char *data, size_t data_length,
  2167. Callback callback) = 0;
  2168. };
  2169. class nocompressor final : public compressor {
  2170. public:
  2171. ~nocompressor() override = default;
  2172. bool compress(const char *data, size_t data_length, bool /*last*/,
  2173. Callback callback) override;
  2174. };
  2175. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2176. class gzip_compressor final : public compressor {
  2177. public:
  2178. gzip_compressor();
  2179. ~gzip_compressor() override;
  2180. bool compress(const char *data, size_t data_length, bool last,
  2181. Callback callback) override;
  2182. private:
  2183. bool is_valid_ = false;
  2184. z_stream strm_;
  2185. };
  2186. class gzip_decompressor final : public decompressor {
  2187. public:
  2188. gzip_decompressor();
  2189. ~gzip_decompressor() override;
  2190. bool is_valid() const override;
  2191. bool decompress(const char *data, size_t data_length,
  2192. Callback callback) override;
  2193. private:
  2194. bool is_valid_ = false;
  2195. z_stream strm_;
  2196. };
  2197. #endif
  2198. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2199. class brotli_compressor final : public compressor {
  2200. public:
  2201. brotli_compressor();
  2202. ~brotli_compressor();
  2203. bool compress(const char *data, size_t data_length, bool last,
  2204. Callback callback) override;
  2205. private:
  2206. BrotliEncoderState *state_ = nullptr;
  2207. };
  2208. class brotli_decompressor final : public decompressor {
  2209. public:
  2210. brotli_decompressor();
  2211. ~brotli_decompressor();
  2212. bool is_valid() const override;
  2213. bool decompress(const char *data, size_t data_length,
  2214. Callback callback) override;
  2215. private:
  2216. BrotliDecoderResult decoder_r;
  2217. BrotliDecoderState *decoder_s = nullptr;
  2218. };
  2219. #endif
  2220. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2221. class zstd_compressor : public compressor {
  2222. public:
  2223. zstd_compressor();
  2224. ~zstd_compressor();
  2225. bool compress(const char *data, size_t data_length, bool last,
  2226. Callback callback) override;
  2227. private:
  2228. ZSTD_CCtx *ctx_ = nullptr;
  2229. };
  2230. class zstd_decompressor : public decompressor {
  2231. public:
  2232. zstd_decompressor();
  2233. ~zstd_decompressor();
  2234. bool is_valid() const override;
  2235. bool decompress(const char *data, size_t data_length,
  2236. Callback callback) override;
  2237. private:
  2238. ZSTD_DCtx *ctx_ = nullptr;
  2239. };
  2240. #endif
  2241. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2242. // to store data. The call can set memory on stack for performance.
  2243. class stream_line_reader {
  2244. public:
  2245. stream_line_reader(Stream &strm, char *fixed_buffer,
  2246. size_t fixed_buffer_size);
  2247. const char *ptr() const;
  2248. size_t size() const;
  2249. bool end_with_crlf() const;
  2250. bool getline();
  2251. private:
  2252. void append(char c);
  2253. Stream &strm_;
  2254. char *fixed_buffer_;
  2255. const size_t fixed_buffer_size_;
  2256. size_t fixed_buffer_used_size_ = 0;
  2257. std::string growable_buffer_;
  2258. };
  2259. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2260. const Headers &src_headers);
  2261. struct ChunkedDecoder {
  2262. Stream &strm;
  2263. size_t chunk_remaining = 0;
  2264. bool finished = false;
  2265. char line_buf[64];
  2266. size_t last_chunk_total = 0;
  2267. size_t last_chunk_offset = 0;
  2268. explicit ChunkedDecoder(Stream &s);
  2269. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2270. size_t &out_chunk_total);
  2271. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2272. };
  2273. class mmap {
  2274. public:
  2275. mmap(const char *path);
  2276. ~mmap();
  2277. bool open(const char *path);
  2278. void close();
  2279. bool is_open() const;
  2280. size_t size() const;
  2281. const char *data() const;
  2282. private:
  2283. #if defined(_WIN32)
  2284. HANDLE hFile_ = NULL;
  2285. HANDLE hMapping_ = NULL;
  2286. #else
  2287. int fd_ = -1;
  2288. #endif
  2289. size_t size_ = 0;
  2290. void *addr_ = nullptr;
  2291. bool is_open_empty_file = false;
  2292. };
  2293. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2294. namespace fields {
  2295. bool is_token_char(char c);
  2296. bool is_token(const std::string &s);
  2297. bool is_field_name(const std::string &s);
  2298. bool is_vchar(char c);
  2299. bool is_obs_text(char c);
  2300. bool is_field_vchar(char c);
  2301. bool is_field_content(const std::string &s);
  2302. bool is_field_value(const std::string &s);
  2303. } // namespace fields
  2304. } // namespace detail
  2305. namespace stream {
  2306. class Result {
  2307. public:
  2308. Result() : chunk_size_(8192) {}
  2309. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192)
  2310. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  2311. Result(Result &&other) noexcept
  2312. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  2313. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  2314. finished_(other.finished_) {
  2315. other.current_size_ = 0;
  2316. other.finished_ = true;
  2317. }
  2318. Result &operator=(Result &&other) noexcept {
  2319. if (this != &other) {
  2320. handle_ = std::move(other.handle_);
  2321. buffer_ = std::move(other.buffer_);
  2322. current_size_ = other.current_size_;
  2323. chunk_size_ = other.chunk_size_;
  2324. finished_ = other.finished_;
  2325. other.current_size_ = 0;
  2326. other.finished_ = true;
  2327. }
  2328. return *this;
  2329. }
  2330. Result(const Result &) = delete;
  2331. Result &operator=(const Result &) = delete;
  2332. // Check if the result is valid (connection succeeded and response received)
  2333. bool is_valid() const { return handle_.is_valid(); }
  2334. explicit operator bool() const { return is_valid(); }
  2335. // Response status code
  2336. int status() const {
  2337. return handle_.response ? handle_.response->status : -1;
  2338. }
  2339. // Response headers
  2340. const Headers &headers() const {
  2341. static const Headers empty_headers;
  2342. return handle_.response ? handle_.response->headers : empty_headers;
  2343. }
  2344. std::string get_header_value(const std::string &key,
  2345. const char *def = "") const {
  2346. return handle_.response ? handle_.response->get_header_value(key, def)
  2347. : def;
  2348. }
  2349. bool has_header(const std::string &key) const {
  2350. return handle_.response ? handle_.response->has_header(key) : false;
  2351. }
  2352. // Error information
  2353. Error error() const { return handle_.error; }
  2354. Error read_error() const { return handle_.get_read_error(); }
  2355. bool has_read_error() const { return handle_.has_read_error(); }
  2356. // Streaming iteration API
  2357. // Call next() to read the next chunk, then access data via data()/size()
  2358. // Returns true if data was read, false when stream is exhausted
  2359. bool next() {
  2360. if (!handle_.is_valid() || finished_) { return false; }
  2361. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  2362. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  2363. if (n > 0) {
  2364. current_size_ = static_cast<size_t>(n);
  2365. return true;
  2366. }
  2367. current_size_ = 0;
  2368. finished_ = true;
  2369. return false;
  2370. }
  2371. // Pointer to current chunk data (valid after next() returns true)
  2372. const char *data() const { return buffer_.data(); }
  2373. // Size of current chunk (valid after next() returns true)
  2374. size_t size() const { return current_size_; }
  2375. // Convenience method: read all remaining data into a string
  2376. std::string read_all() {
  2377. std::string result;
  2378. while (next()) {
  2379. result.append(data(), size());
  2380. }
  2381. return result;
  2382. }
  2383. private:
  2384. ClientImpl::StreamHandle handle_;
  2385. std::string buffer_;
  2386. size_t current_size_ = 0;
  2387. size_t chunk_size_;
  2388. bool finished_ = false;
  2389. };
  2390. // GET
  2391. template <typename ClientType>
  2392. inline Result Get(ClientType &cli, const std::string &path,
  2393. size_t chunk_size = 8192) {
  2394. return Result{cli.open_stream("GET", path), chunk_size};
  2395. }
  2396. template <typename ClientType>
  2397. inline Result Get(ClientType &cli, const std::string &path,
  2398. const Headers &headers, size_t chunk_size = 8192) {
  2399. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2400. }
  2401. template <typename ClientType>
  2402. inline Result Get(ClientType &cli, const std::string &path,
  2403. const Params &params, size_t chunk_size = 8192) {
  2404. return Result{cli.open_stream("GET", path, params), chunk_size};
  2405. }
  2406. template <typename ClientType>
  2407. inline Result Get(ClientType &cli, const std::string &path,
  2408. const Params &params, const Headers &headers,
  2409. size_t chunk_size = 8192) {
  2410. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2411. }
  2412. // POST
  2413. template <typename ClientType>
  2414. inline Result Post(ClientType &cli, const std::string &path,
  2415. const std::string &body, const std::string &content_type,
  2416. size_t chunk_size = 8192) {
  2417. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2418. chunk_size};
  2419. }
  2420. template <typename ClientType>
  2421. inline Result Post(ClientType &cli, const std::string &path,
  2422. const Headers &headers, const std::string &body,
  2423. const std::string &content_type, size_t chunk_size = 8192) {
  2424. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2425. chunk_size};
  2426. }
  2427. template <typename ClientType>
  2428. inline Result Post(ClientType &cli, const std::string &path,
  2429. const Params &params, const std::string &body,
  2430. const std::string &content_type, size_t chunk_size = 8192) {
  2431. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2432. chunk_size};
  2433. }
  2434. template <typename ClientType>
  2435. inline Result Post(ClientType &cli, const std::string &path,
  2436. const Params &params, const Headers &headers,
  2437. const std::string &body, const std::string &content_type,
  2438. size_t chunk_size = 8192) {
  2439. return Result{
  2440. cli.open_stream("POST", path, params, headers, body, content_type),
  2441. chunk_size};
  2442. }
  2443. // PUT
  2444. template <typename ClientType>
  2445. inline Result Put(ClientType &cli, const std::string &path,
  2446. const std::string &body, const std::string &content_type,
  2447. size_t chunk_size = 8192) {
  2448. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2449. chunk_size};
  2450. }
  2451. template <typename ClientType>
  2452. inline Result Put(ClientType &cli, const std::string &path,
  2453. const Headers &headers, const std::string &body,
  2454. const std::string &content_type, size_t chunk_size = 8192) {
  2455. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2456. chunk_size};
  2457. }
  2458. template <typename ClientType>
  2459. inline Result Put(ClientType &cli, const std::string &path,
  2460. const Params &params, const std::string &body,
  2461. const std::string &content_type, size_t chunk_size = 8192) {
  2462. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2463. chunk_size};
  2464. }
  2465. template <typename ClientType>
  2466. inline Result Put(ClientType &cli, const std::string &path,
  2467. const Params &params, const Headers &headers,
  2468. const std::string &body, const std::string &content_type,
  2469. size_t chunk_size = 8192) {
  2470. return Result{
  2471. cli.open_stream("PUT", path, params, headers, body, content_type),
  2472. chunk_size};
  2473. }
  2474. // PATCH
  2475. template <typename ClientType>
  2476. inline Result Patch(ClientType &cli, const std::string &path,
  2477. const std::string &body, const std::string &content_type,
  2478. size_t chunk_size = 8192) {
  2479. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2480. chunk_size};
  2481. }
  2482. template <typename ClientType>
  2483. inline Result Patch(ClientType &cli, const std::string &path,
  2484. const Headers &headers, const std::string &body,
  2485. const std::string &content_type, size_t chunk_size = 8192) {
  2486. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2487. chunk_size};
  2488. }
  2489. template <typename ClientType>
  2490. inline Result Patch(ClientType &cli, const std::string &path,
  2491. const Params &params, const std::string &body,
  2492. const std::string &content_type, size_t chunk_size = 8192) {
  2493. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2494. chunk_size};
  2495. }
  2496. template <typename ClientType>
  2497. inline Result Patch(ClientType &cli, const std::string &path,
  2498. const Params &params, const Headers &headers,
  2499. const std::string &body, const std::string &content_type,
  2500. size_t chunk_size = 8192) {
  2501. return Result{
  2502. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2503. chunk_size};
  2504. }
  2505. // DELETE
  2506. template <typename ClientType>
  2507. inline Result Delete(ClientType &cli, const std::string &path,
  2508. size_t chunk_size = 8192) {
  2509. return Result{cli.open_stream("DELETE", path), chunk_size};
  2510. }
  2511. template <typename ClientType>
  2512. inline Result Delete(ClientType &cli, const std::string &path,
  2513. const Headers &headers, size_t chunk_size = 8192) {
  2514. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2515. }
  2516. template <typename ClientType>
  2517. inline Result Delete(ClientType &cli, const std::string &path,
  2518. const std::string &body, const std::string &content_type,
  2519. size_t chunk_size = 8192) {
  2520. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2521. chunk_size};
  2522. }
  2523. template <typename ClientType>
  2524. inline Result Delete(ClientType &cli, const std::string &path,
  2525. const Headers &headers, const std::string &body,
  2526. const std::string &content_type,
  2527. size_t chunk_size = 8192) {
  2528. return Result{
  2529. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2530. chunk_size};
  2531. }
  2532. template <typename ClientType>
  2533. inline Result Delete(ClientType &cli, const std::string &path,
  2534. const Params &params, size_t chunk_size = 8192) {
  2535. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2536. }
  2537. template <typename ClientType>
  2538. inline Result Delete(ClientType &cli, const std::string &path,
  2539. const Params &params, const Headers &headers,
  2540. size_t chunk_size = 8192) {
  2541. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2542. }
  2543. template <typename ClientType>
  2544. inline Result Delete(ClientType &cli, const std::string &path,
  2545. const Params &params, const std::string &body,
  2546. const std::string &content_type,
  2547. size_t chunk_size = 8192) {
  2548. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2549. chunk_size};
  2550. }
  2551. template <typename ClientType>
  2552. inline Result Delete(ClientType &cli, const std::string &path,
  2553. const Params &params, const Headers &headers,
  2554. const std::string &body, const std::string &content_type,
  2555. size_t chunk_size = 8192) {
  2556. return Result{
  2557. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2558. chunk_size};
  2559. }
  2560. // HEAD
  2561. template <typename ClientType>
  2562. inline Result Head(ClientType &cli, const std::string &path,
  2563. size_t chunk_size = 8192) {
  2564. return Result{cli.open_stream("HEAD", path), chunk_size};
  2565. }
  2566. template <typename ClientType>
  2567. inline Result Head(ClientType &cli, const std::string &path,
  2568. const Headers &headers, size_t chunk_size = 8192) {
  2569. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2570. }
  2571. template <typename ClientType>
  2572. inline Result Head(ClientType &cli, const std::string &path,
  2573. const Params &params, size_t chunk_size = 8192) {
  2574. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2575. }
  2576. template <typename ClientType>
  2577. inline Result Head(ClientType &cli, const std::string &path,
  2578. const Params &params, const Headers &headers,
  2579. size_t chunk_size = 8192) {
  2580. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2581. }
  2582. // OPTIONS
  2583. template <typename ClientType>
  2584. inline Result Options(ClientType &cli, const std::string &path,
  2585. size_t chunk_size = 8192) {
  2586. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2587. }
  2588. template <typename ClientType>
  2589. inline Result Options(ClientType &cli, const std::string &path,
  2590. const Headers &headers, size_t chunk_size = 8192) {
  2591. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2592. }
  2593. template <typename ClientType>
  2594. inline Result Options(ClientType &cli, const std::string &path,
  2595. const Params &params, size_t chunk_size = 8192) {
  2596. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2597. }
  2598. template <typename ClientType>
  2599. inline Result Options(ClientType &cli, const std::string &path,
  2600. const Params &params, const Headers &headers,
  2601. size_t chunk_size = 8192) {
  2602. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2603. }
  2604. } // namespace stream
  2605. namespace sse {
  2606. struct SSEMessage {
  2607. std::string event; // Event type (default: "message")
  2608. std::string data; // Event payload
  2609. std::string id; // Event ID for Last-Event-ID header
  2610. SSEMessage() : event("message") {}
  2611. void clear() {
  2612. event = "message";
  2613. data.clear();
  2614. id.clear();
  2615. }
  2616. };
  2617. class SSEClient {
  2618. public:
  2619. using MessageHandler = std::function<void(const SSEMessage &)>;
  2620. using ErrorHandler = std::function<void(Error)>;
  2621. using OpenHandler = std::function<void()>;
  2622. SSEClient(Client &client, const std::string &path)
  2623. : client_(client), path_(path) {}
  2624. SSEClient(Client &client, const std::string &path, const Headers &headers)
  2625. : client_(client), path_(path), headers_(headers) {}
  2626. ~SSEClient() { stop(); }
  2627. SSEClient(const SSEClient &) = delete;
  2628. SSEClient &operator=(const SSEClient &) = delete;
  2629. // Event handlers
  2630. SSEClient &on_message(MessageHandler handler) {
  2631. on_message_ = std::move(handler);
  2632. return *this;
  2633. }
  2634. SSEClient &on_event(const std::string &type, MessageHandler handler) {
  2635. event_handlers_[type] = std::move(handler);
  2636. return *this;
  2637. }
  2638. SSEClient &on_open(OpenHandler handler) {
  2639. on_open_ = std::move(handler);
  2640. return *this;
  2641. }
  2642. SSEClient &on_error(ErrorHandler handler) {
  2643. on_error_ = std::move(handler);
  2644. return *this;
  2645. }
  2646. SSEClient &set_reconnect_interval(int ms) {
  2647. reconnect_interval_ms_ = ms;
  2648. return *this;
  2649. }
  2650. SSEClient &set_max_reconnect_attempts(int n) {
  2651. max_reconnect_attempts_ = n;
  2652. return *this;
  2653. }
  2654. // State accessors
  2655. bool is_connected() const { return connected_.load(); }
  2656. const std::string &last_event_id() const { return last_event_id_; }
  2657. // Blocking start - runs event loop with auto-reconnect
  2658. void start() {
  2659. running_.store(true);
  2660. run_event_loop();
  2661. }
  2662. // Non-blocking start - runs in background thread
  2663. void start_async() {
  2664. running_.store(true);
  2665. async_thread_ = std::thread([this]() { run_event_loop(); });
  2666. }
  2667. // Stop the client (thread-safe)
  2668. void stop() {
  2669. running_.store(false);
  2670. client_.stop(); // Cancel any pending operations
  2671. if (async_thread_.joinable()) { async_thread_.join(); }
  2672. }
  2673. private:
  2674. // Parse a single SSE field line
  2675. // Returns true if this line ends an event (blank line)
  2676. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms) {
  2677. // Blank line signals end of event
  2678. if (line.empty() || line == "\r") { return true; }
  2679. // Lines starting with ':' are comments (ignored)
  2680. if (!line.empty() && line[0] == ':') { return false; }
  2681. // Find the colon separator
  2682. auto colon_pos = line.find(':');
  2683. if (colon_pos == std::string::npos) {
  2684. // Line with no colon is treated as field name with empty value
  2685. return false;
  2686. }
  2687. auto field = line.substr(0, colon_pos);
  2688. std::string value;
  2689. // Value starts after colon, skip optional single space
  2690. if (colon_pos + 1 < line.size()) {
  2691. auto value_start = colon_pos + 1;
  2692. if (line[value_start] == ' ') { value_start++; }
  2693. value = line.substr(value_start);
  2694. // Remove trailing \r if present
  2695. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  2696. }
  2697. // Handle known fields
  2698. if (field == "event") {
  2699. msg.event = value;
  2700. } else if (field == "data") {
  2701. // Multiple data lines are concatenated with newlines
  2702. if (!msg.data.empty()) { msg.data += "\n"; }
  2703. msg.data += value;
  2704. } else if (field == "id") {
  2705. // Empty id is valid (clears the last event ID)
  2706. msg.id = value;
  2707. } else if (field == "retry") {
  2708. // Parse retry interval in milliseconds
  2709. {
  2710. int v = 0;
  2711. auto res =
  2712. detail::from_chars(value.data(), value.data() + value.size(), v);
  2713. if (res.ec == std::errc{}) { retry_ms = v; }
  2714. }
  2715. }
  2716. // Unknown fields are ignored per SSE spec
  2717. return false;
  2718. }
  2719. // Main event loop with auto-reconnect
  2720. void run_event_loop() {
  2721. auto reconnect_count = 0;
  2722. while (running_.load()) {
  2723. // Build headers, including Last-Event-ID if we have one
  2724. auto request_headers = headers_;
  2725. if (!last_event_id_.empty()) {
  2726. request_headers.emplace("Last-Event-ID", last_event_id_);
  2727. }
  2728. // Open streaming connection
  2729. auto result = stream::Get(client_, path_, request_headers);
  2730. // Connection error handling
  2731. if (!result) {
  2732. connected_.store(false);
  2733. if (on_error_) { on_error_(result.error()); }
  2734. if (!should_reconnect(reconnect_count)) { break; }
  2735. wait_for_reconnect();
  2736. reconnect_count++;
  2737. continue;
  2738. }
  2739. if (result.status() != 200) {
  2740. connected_.store(false);
  2741. // For certain errors, don't reconnect
  2742. if (result.status() == 204 || // No Content - server wants us to stop
  2743. result.status() == 404 || // Not Found
  2744. result.status() == 401 || // Unauthorized
  2745. result.status() == 403) { // Forbidden
  2746. if (on_error_) { on_error_(Error::Connection); }
  2747. break;
  2748. }
  2749. if (on_error_) { on_error_(Error::Connection); }
  2750. if (!should_reconnect(reconnect_count)) { break; }
  2751. wait_for_reconnect();
  2752. reconnect_count++;
  2753. continue;
  2754. }
  2755. // Connection successful
  2756. connected_.store(true);
  2757. reconnect_count = 0;
  2758. if (on_open_) { on_open_(); }
  2759. // Event receiving loop
  2760. std::string buffer;
  2761. SSEMessage current_msg;
  2762. while (running_.load() && result.next()) {
  2763. buffer.append(result.data(), result.size());
  2764. // Process complete lines in the buffer
  2765. size_t line_start = 0;
  2766. size_t newline_pos;
  2767. while ((newline_pos = buffer.find('\n', line_start)) !=
  2768. std::string::npos) {
  2769. auto line = buffer.substr(line_start, newline_pos - line_start);
  2770. line_start = newline_pos + 1;
  2771. // Parse the line and check if event is complete
  2772. auto event_complete =
  2773. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  2774. if (event_complete && !current_msg.data.empty()) {
  2775. // Update last_event_id for reconnection
  2776. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  2777. // Dispatch event to appropriate handler
  2778. dispatch_event(current_msg);
  2779. current_msg.clear();
  2780. }
  2781. }
  2782. // Keep unprocessed data in buffer
  2783. buffer.erase(0, line_start);
  2784. }
  2785. // Connection ended
  2786. connected_.store(false);
  2787. if (!running_.load()) { break; }
  2788. // Check for read errors
  2789. if (result.has_read_error()) {
  2790. if (on_error_) { on_error_(result.read_error()); }
  2791. }
  2792. if (!should_reconnect(reconnect_count)) { break; }
  2793. wait_for_reconnect();
  2794. reconnect_count++;
  2795. }
  2796. connected_.store(false);
  2797. }
  2798. // Dispatch event to appropriate handler
  2799. void dispatch_event(const SSEMessage &msg) {
  2800. // Check for specific event type handler first
  2801. auto it = event_handlers_.find(msg.event);
  2802. if (it != event_handlers_.end()) {
  2803. it->second(msg);
  2804. return;
  2805. }
  2806. // Fall back to generic message handler
  2807. if (on_message_) { on_message_(msg); }
  2808. }
  2809. // Check if we should attempt to reconnect
  2810. bool should_reconnect(int count) const {
  2811. if (!running_.load()) { return false; }
  2812. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  2813. return count < max_reconnect_attempts_;
  2814. }
  2815. // Wait for reconnect interval
  2816. void wait_for_reconnect() {
  2817. // Use small increments to check running_ flag frequently
  2818. auto waited = 0;
  2819. while (running_.load() && waited < reconnect_interval_ms_) {
  2820. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2821. waited += 100;
  2822. }
  2823. }
  2824. // Client and path
  2825. Client &client_;
  2826. std::string path_;
  2827. Headers headers_;
  2828. // Callbacks
  2829. MessageHandler on_message_;
  2830. std::map<std::string, MessageHandler> event_handlers_;
  2831. OpenHandler on_open_;
  2832. ErrorHandler on_error_;
  2833. // Configuration
  2834. int reconnect_interval_ms_ = 3000;
  2835. int max_reconnect_attempts_ = 0; // 0 = unlimited
  2836. // State
  2837. std::atomic<bool> running_{false};
  2838. std::atomic<bool> connected_{false};
  2839. std::string last_event_id_;
  2840. // Async support
  2841. std::thread async_thread_;
  2842. };
  2843. } // namespace sse
  2844. // ----------------------------------------------------------------------------
  2845. /*
  2846. * Implementation that will be part of the .cc file if split into .h + .cc.
  2847. */
  2848. namespace detail {
  2849. inline bool is_hex(char c, int &v) {
  2850. if (isdigit(c)) {
  2851. v = c - '0';
  2852. return true;
  2853. } else if ('A' <= c && c <= 'F') {
  2854. v = c - 'A' + 10;
  2855. return true;
  2856. } else if ('a' <= c && c <= 'f') {
  2857. v = c - 'a' + 10;
  2858. return true;
  2859. }
  2860. return false;
  2861. }
  2862. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  2863. int &val) {
  2864. if (i >= s.size()) { return false; }
  2865. val = 0;
  2866. for (; cnt; i++, cnt--) {
  2867. if (!s[i]) { return false; }
  2868. auto v = 0;
  2869. if (is_hex(s[i], v)) {
  2870. val = val * 16 + v;
  2871. } else {
  2872. return false;
  2873. }
  2874. }
  2875. return true;
  2876. }
  2877. inline std::string from_i_to_hex(size_t n) {
  2878. static const auto charset = "0123456789abcdef";
  2879. std::string ret;
  2880. do {
  2881. ret = charset[n & 15] + ret;
  2882. n >>= 4;
  2883. } while (n > 0);
  2884. return ret;
  2885. }
  2886. inline std::string compute_etag(const FileStat &fs) {
  2887. if (!fs.is_file()) { return std::string(); }
  2888. // If mtime cannot be determined (negative value indicates an error
  2889. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  2890. // value like 0 could collide with a real file that legitimately has
  2891. // mtime == 0 (epoch) and lead to misleading validators.
  2892. auto mtime_raw = fs.mtime();
  2893. if (mtime_raw < 0) { return std::string(); }
  2894. auto mtime = static_cast<size_t>(mtime_raw);
  2895. auto size = fs.size();
  2896. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  2897. from_i_to_hex(size) + "\"";
  2898. }
  2899. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  2900. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  2901. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  2902. inline std::string file_mtime_to_http_date(time_t mtime) {
  2903. if (mtime < 0) { return std::string(); }
  2904. struct tm tm_buf;
  2905. #ifdef _WIN32
  2906. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  2907. #else
  2908. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  2909. #endif
  2910. char buf[64];
  2911. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  2912. return std::string();
  2913. }
  2914. return std::string(buf);
  2915. }
  2916. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  2917. inline time_t parse_http_date(const std::string &date_str) {
  2918. struct tm tm_buf;
  2919. // Create a classic locale object once for all parsing attempts
  2920. const std::locale classic_locale = std::locale::classic();
  2921. // Try to parse using std::get_time (C++11, cross-platform)
  2922. auto try_parse = [&](const char *fmt) -> bool {
  2923. std::istringstream ss(date_str);
  2924. ss.imbue(classic_locale);
  2925. memset(&tm_buf, 0, sizeof(tm_buf));
  2926. ss >> std::get_time(&tm_buf, fmt);
  2927. return !ss.fail();
  2928. };
  2929. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  2930. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  2931. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  2932. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  2933. // asctime format: "Sun Nov 6 08:49:37 1994"
  2934. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  2935. return static_cast<time_t>(-1);
  2936. }
  2937. }
  2938. }
  2939. #ifdef _WIN32
  2940. return _mkgmtime(&tm_buf);
  2941. #elif defined _AIX
  2942. return mktime(&tm_buf);
  2943. #else
  2944. return timegm(&tm_buf);
  2945. #endif
  2946. }
  2947. inline bool is_weak_etag(const std::string &s) {
  2948. // Check if the string is a weak ETag (starts with 'W/"')
  2949. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  2950. }
  2951. inline bool is_strong_etag(const std::string &s) {
  2952. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  2953. // chars)
  2954. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  2955. }
  2956. inline size_t to_utf8(int code, char *buff) {
  2957. if (code < 0x0080) {
  2958. buff[0] = static_cast<char>(code & 0x7F);
  2959. return 1;
  2960. } else if (code < 0x0800) {
  2961. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  2962. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  2963. return 2;
  2964. } else if (code < 0xD800) {
  2965. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2966. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2967. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2968. return 3;
  2969. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  2970. return 0;
  2971. } else if (code < 0x10000) {
  2972. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2973. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2974. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2975. return 3;
  2976. } else if (code < 0x110000) {
  2977. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  2978. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  2979. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2980. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  2981. return 4;
  2982. }
  2983. // NOTREACHED
  2984. return 0;
  2985. }
  2986. // NOTE: This code came up with the following stackoverflow post:
  2987. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  2988. inline std::string base64_encode(const std::string &in) {
  2989. static const auto lookup =
  2990. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2991. std::string out;
  2992. out.reserve(in.size());
  2993. auto val = 0;
  2994. auto valb = -6;
  2995. for (auto c : in) {
  2996. val = (val << 8) + static_cast<uint8_t>(c);
  2997. valb += 8;
  2998. while (valb >= 0) {
  2999. out.push_back(lookup[(val >> valb) & 0x3F]);
  3000. valb -= 6;
  3001. }
  3002. }
  3003. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3004. while (out.size() % 4) {
  3005. out.push_back('=');
  3006. }
  3007. return out;
  3008. }
  3009. inline bool is_valid_path(const std::string &path) {
  3010. size_t level = 0;
  3011. size_t i = 0;
  3012. // Skip slash
  3013. while (i < path.size() && path[i] == '/') {
  3014. i++;
  3015. }
  3016. while (i < path.size()) {
  3017. // Read component
  3018. auto beg = i;
  3019. while (i < path.size() && path[i] != '/') {
  3020. if (path[i] == '\0') {
  3021. return false;
  3022. } else if (path[i] == '\\') {
  3023. return false;
  3024. }
  3025. i++;
  3026. }
  3027. auto len = i - beg;
  3028. assert(len > 0);
  3029. if (!path.compare(beg, len, ".")) {
  3030. ;
  3031. } else if (!path.compare(beg, len, "..")) {
  3032. if (level == 0) { return false; }
  3033. level--;
  3034. } else {
  3035. level++;
  3036. }
  3037. // Skip slash
  3038. while (i < path.size() && path[i] == '/') {
  3039. i++;
  3040. }
  3041. }
  3042. return true;
  3043. }
  3044. inline FileStat::FileStat(const std::string &path) {
  3045. #if defined(_WIN32)
  3046. auto wpath = u8string_to_wstring(path.c_str());
  3047. ret_ = _wstat(wpath.c_str(), &st_);
  3048. #else
  3049. ret_ = stat(path.c_str(), &st_);
  3050. #endif
  3051. }
  3052. inline bool FileStat::is_file() const {
  3053. return ret_ >= 0 && S_ISREG(st_.st_mode);
  3054. }
  3055. inline bool FileStat::is_dir() const {
  3056. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  3057. }
  3058. inline time_t FileStat::mtime() const {
  3059. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  3060. : static_cast<time_t>(-1);
  3061. }
  3062. inline size_t FileStat::size() const {
  3063. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  3064. }
  3065. inline std::string encode_path(const std::string &s) {
  3066. std::string result;
  3067. result.reserve(s.size());
  3068. for (size_t i = 0; s[i]; i++) {
  3069. switch (s[i]) {
  3070. case ' ': result += "%20"; break;
  3071. case '+': result += "%2B"; break;
  3072. case '\r': result += "%0D"; break;
  3073. case '\n': result += "%0A"; break;
  3074. case '\'': result += "%27"; break;
  3075. case ',': result += "%2C"; break;
  3076. // case ':': result += "%3A"; break; // ok? probably...
  3077. case ';': result += "%3B"; break;
  3078. default:
  3079. auto c = static_cast<uint8_t>(s[i]);
  3080. if (c >= 0x80) {
  3081. result += '%';
  3082. char hex[4];
  3083. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  3084. assert(len == 2);
  3085. result.append(hex, static_cast<size_t>(len));
  3086. } else {
  3087. result += s[i];
  3088. }
  3089. break;
  3090. }
  3091. }
  3092. return result;
  3093. }
  3094. inline std::string file_extension(const std::string &path) {
  3095. std::smatch m;
  3096. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  3097. if (std::regex_search(path, m, re)) { return m[1].str(); }
  3098. return std::string();
  3099. }
  3100. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  3101. template <typename T>
  3102. inline bool parse_header(const char *beg, const char *end, T fn);
  3103. template <typename T>
  3104. inline bool parse_header(const char *beg, const char *end, T fn) {
  3105. // Skip trailing spaces and tabs.
  3106. while (beg < end && is_space_or_tab(end[-1])) {
  3107. end--;
  3108. }
  3109. auto p = beg;
  3110. while (p < end && *p != ':') {
  3111. p++;
  3112. }
  3113. auto name = std::string(beg, p);
  3114. if (!detail::fields::is_field_name(name)) { return false; }
  3115. if (p == end) { return false; }
  3116. auto key_end = p;
  3117. if (*p++ != ':') { return false; }
  3118. while (p < end && is_space_or_tab(*p)) {
  3119. p++;
  3120. }
  3121. if (p <= end) {
  3122. auto key_len = key_end - beg;
  3123. if (!key_len) { return false; }
  3124. auto key = std::string(beg, key_end);
  3125. auto val = std::string(p, end);
  3126. if (!detail::fields::is_field_value(val)) { return false; }
  3127. if (case_ignore::equal(key, "Location") ||
  3128. case_ignore::equal(key, "Referer")) {
  3129. fn(key, val);
  3130. } else {
  3131. fn(key, decode_path_component(val));
  3132. }
  3133. return true;
  3134. }
  3135. return false;
  3136. }
  3137. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3138. const Headers &src_headers) {
  3139. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3140. // transfer coding is complete when a chunk with a chunk-size of zero is
  3141. // received, possibly followed by a trailer section, and finally terminated by
  3142. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3143. //
  3144. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3145. // doesn't care for the existence of the final CRLF. In other words, it seems
  3146. // to be ok whether the final CRLF exists or not in the chunked data.
  3147. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3148. //
  3149. // According to the reference code in RFC 9112, cpp-httplib now allows
  3150. // chunked transfer coding data without the final CRLF.
  3151. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3152. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3153. "transfer-encoding",
  3154. "content-length",
  3155. "host",
  3156. "authorization",
  3157. "www-authenticate",
  3158. "proxy-authenticate",
  3159. "proxy-authorization",
  3160. "cookie",
  3161. "set-cookie",
  3162. "cache-control",
  3163. "expect",
  3164. "max-forwards",
  3165. "pragma",
  3166. "range",
  3167. "te",
  3168. "age",
  3169. "expires",
  3170. "date",
  3171. "location",
  3172. "retry-after",
  3173. "vary",
  3174. "warning",
  3175. "content-encoding",
  3176. "content-type",
  3177. "content-range",
  3178. "trailer"};
  3179. case_ignore::unordered_set<std::string> declared_trailers;
  3180. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  3181. if (trailer_header && std::strlen(trailer_header)) {
  3182. auto len = std::strlen(trailer_header);
  3183. split(trailer_header, trailer_header + len, ',',
  3184. [&](const char *b, const char *e) {
  3185. const char *kbeg = b;
  3186. const char *kend = e;
  3187. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  3188. ++kbeg;
  3189. }
  3190. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  3191. --kend;
  3192. }
  3193. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  3194. if (!key.empty() &&
  3195. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  3196. declared_trailers.insert(key);
  3197. }
  3198. });
  3199. }
  3200. size_t trailer_header_count = 0;
  3201. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3202. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3203. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3204. constexpr auto line_terminator_len = 2;
  3205. auto line_beg = line_reader.ptr();
  3206. auto line_end =
  3207. line_reader.ptr() + line_reader.size() - line_terminator_len;
  3208. if (!parse_header(line_beg, line_end,
  3209. [&](const std::string &key, const std::string &val) {
  3210. if (declared_trailers.find(key) !=
  3211. declared_trailers.end()) {
  3212. dest.emplace(key, val);
  3213. trailer_header_count++;
  3214. }
  3215. })) {
  3216. return false;
  3217. }
  3218. if (!line_reader.getline()) { return false; }
  3219. }
  3220. return true;
  3221. }
  3222. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  3223. size_t right) {
  3224. while (b + left < e && is_space_or_tab(b[left])) {
  3225. left++;
  3226. }
  3227. while (right > 0 && is_space_or_tab(b[right - 1])) {
  3228. right--;
  3229. }
  3230. return std::make_pair(left, right);
  3231. }
  3232. inline std::string trim_copy(const std::string &s) {
  3233. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  3234. return s.substr(r.first, r.second - r.first);
  3235. }
  3236. inline std::string trim_double_quotes_copy(const std::string &s) {
  3237. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  3238. return s.substr(1, s.size() - 2);
  3239. }
  3240. return s;
  3241. }
  3242. inline void
  3243. divide(const char *data, std::size_t size, char d,
  3244. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3245. fn) {
  3246. const auto it = std::find(data, data + size, d);
  3247. const auto found = static_cast<std::size_t>(it != data + size);
  3248. const auto lhs_data = data;
  3249. const auto lhs_size = static_cast<std::size_t>(it - data);
  3250. const auto rhs_data = it + found;
  3251. const auto rhs_size = size - lhs_size - found;
  3252. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  3253. }
  3254. inline void
  3255. divide(const std::string &str, char d,
  3256. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3257. fn) {
  3258. divide(str.data(), str.size(), d, std::move(fn));
  3259. }
  3260. inline void split(const char *b, const char *e, char d,
  3261. std::function<void(const char *, const char *)> fn) {
  3262. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  3263. }
  3264. inline void split(const char *b, const char *e, char d, size_t m,
  3265. std::function<void(const char *, const char *)> fn) {
  3266. size_t i = 0;
  3267. size_t beg = 0;
  3268. size_t count = 1;
  3269. while (e ? (b + i < e) : (b[i] != '\0')) {
  3270. if (b[i] == d && count < m) {
  3271. auto r = trim(b, e, beg, i);
  3272. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3273. beg = i + 1;
  3274. count++;
  3275. }
  3276. i++;
  3277. }
  3278. if (i) {
  3279. auto r = trim(b, e, beg, i);
  3280. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3281. }
  3282. }
  3283. inline bool split_find(const char *b, const char *e, char d, size_t m,
  3284. std::function<bool(const char *, const char *)> fn) {
  3285. size_t i = 0;
  3286. size_t beg = 0;
  3287. size_t count = 1;
  3288. while (e ? (b + i < e) : (b[i] != '\0')) {
  3289. if (b[i] == d && count < m) {
  3290. auto r = trim(b, e, beg, i);
  3291. if (r.first < r.second) {
  3292. auto found = fn(&b[r.first], &b[r.second]);
  3293. if (found) { return true; }
  3294. }
  3295. beg = i + 1;
  3296. count++;
  3297. }
  3298. i++;
  3299. }
  3300. if (i) {
  3301. auto r = trim(b, e, beg, i);
  3302. if (r.first < r.second) {
  3303. auto found = fn(&b[r.first], &b[r.second]);
  3304. if (found) { return true; }
  3305. }
  3306. }
  3307. return false;
  3308. }
  3309. inline bool split_find(const char *b, const char *e, char d,
  3310. std::function<bool(const char *, const char *)> fn) {
  3311. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  3312. std::move(fn));
  3313. }
  3314. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  3315. size_t fixed_buffer_size)
  3316. : strm_(strm), fixed_buffer_(fixed_buffer),
  3317. fixed_buffer_size_(fixed_buffer_size) {}
  3318. inline const char *stream_line_reader::ptr() const {
  3319. if (growable_buffer_.empty()) {
  3320. return fixed_buffer_;
  3321. } else {
  3322. return growable_buffer_.data();
  3323. }
  3324. }
  3325. inline size_t stream_line_reader::size() const {
  3326. if (growable_buffer_.empty()) {
  3327. return fixed_buffer_used_size_;
  3328. } else {
  3329. return growable_buffer_.size();
  3330. }
  3331. }
  3332. inline bool stream_line_reader::end_with_crlf() const {
  3333. auto end = ptr() + size();
  3334. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  3335. }
  3336. inline bool stream_line_reader::getline() {
  3337. fixed_buffer_used_size_ = 0;
  3338. growable_buffer_.clear();
  3339. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3340. char prev_byte = 0;
  3341. #endif
  3342. for (size_t i = 0;; i++) {
  3343. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  3344. // Treat exceptionally long lines as an error to
  3345. // prevent infinite loops/memory exhaustion
  3346. return false;
  3347. }
  3348. char byte;
  3349. auto n = strm_.read(&byte, 1);
  3350. if (n < 0) {
  3351. return false;
  3352. } else if (n == 0) {
  3353. if (i == 0) {
  3354. return false;
  3355. } else {
  3356. break;
  3357. }
  3358. }
  3359. append(byte);
  3360. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3361. if (byte == '\n') { break; }
  3362. #else
  3363. if (prev_byte == '\r' && byte == '\n') { break; }
  3364. prev_byte = byte;
  3365. #endif
  3366. }
  3367. return true;
  3368. }
  3369. inline void stream_line_reader::append(char c) {
  3370. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  3371. fixed_buffer_[fixed_buffer_used_size_++] = c;
  3372. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  3373. } else {
  3374. if (growable_buffer_.empty()) {
  3375. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  3376. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  3377. }
  3378. growable_buffer_ += c;
  3379. }
  3380. }
  3381. inline mmap::mmap(const char *path) { open(path); }
  3382. inline mmap::~mmap() { close(); }
  3383. inline bool mmap::open(const char *path) {
  3384. close();
  3385. #if defined(_WIN32)
  3386. auto wpath = u8string_to_wstring(path);
  3387. if (wpath.empty()) { return false; }
  3388. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  3389. OPEN_EXISTING, NULL);
  3390. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  3391. LARGE_INTEGER size{};
  3392. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  3393. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  3394. // See:
  3395. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  3396. if (static_cast<ULONGLONG>(size.QuadPart) >
  3397. (std::numeric_limits<decltype(size_)>::max)()) {
  3398. // `size_t` might be 32-bits, on 32-bits Windows.
  3399. return false;
  3400. }
  3401. size_ = static_cast<size_t>(size.QuadPart);
  3402. hMapping_ =
  3403. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  3404. // Special treatment for an empty file...
  3405. if (hMapping_ == NULL && size_ == 0) {
  3406. close();
  3407. is_open_empty_file = true;
  3408. return true;
  3409. }
  3410. if (hMapping_ == NULL) {
  3411. close();
  3412. return false;
  3413. }
  3414. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  3415. if (addr_ == nullptr) {
  3416. close();
  3417. return false;
  3418. }
  3419. #else
  3420. fd_ = ::open(path, O_RDONLY);
  3421. if (fd_ == -1) { return false; }
  3422. struct stat sb;
  3423. if (fstat(fd_, &sb) == -1) {
  3424. close();
  3425. return false;
  3426. }
  3427. size_ = static_cast<size_t>(sb.st_size);
  3428. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  3429. // Special treatment for an empty file...
  3430. if (addr_ == MAP_FAILED && size_ == 0) {
  3431. close();
  3432. is_open_empty_file = true;
  3433. return false;
  3434. }
  3435. #endif
  3436. return true;
  3437. }
  3438. inline bool mmap::is_open() const {
  3439. return is_open_empty_file ? true : addr_ != nullptr;
  3440. }
  3441. inline size_t mmap::size() const { return size_; }
  3442. inline const char *mmap::data() const {
  3443. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  3444. }
  3445. inline void mmap::close() {
  3446. #if defined(_WIN32)
  3447. if (addr_) {
  3448. ::UnmapViewOfFile(addr_);
  3449. addr_ = nullptr;
  3450. }
  3451. if (hMapping_) {
  3452. ::CloseHandle(hMapping_);
  3453. hMapping_ = NULL;
  3454. }
  3455. if (hFile_ != INVALID_HANDLE_VALUE) {
  3456. ::CloseHandle(hFile_);
  3457. hFile_ = INVALID_HANDLE_VALUE;
  3458. }
  3459. is_open_empty_file = false;
  3460. #else
  3461. if (addr_ != nullptr) {
  3462. munmap(addr_, size_);
  3463. addr_ = nullptr;
  3464. }
  3465. if (fd_ != -1) {
  3466. ::close(fd_);
  3467. fd_ = -1;
  3468. }
  3469. #endif
  3470. size_ = 0;
  3471. }
  3472. inline int close_socket(socket_t sock) {
  3473. #ifdef _WIN32
  3474. return closesocket(sock);
  3475. #else
  3476. return close(sock);
  3477. #endif
  3478. }
  3479. template <typename T> inline ssize_t handle_EINTR(T fn) {
  3480. ssize_t res = 0;
  3481. while (true) {
  3482. res = fn();
  3483. if (res < 0 && errno == EINTR) {
  3484. std::this_thread::sleep_for(std::chrono::microseconds{1});
  3485. continue;
  3486. }
  3487. break;
  3488. }
  3489. return res;
  3490. }
  3491. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  3492. return handle_EINTR([&]() {
  3493. return recv(sock,
  3494. #ifdef _WIN32
  3495. static_cast<char *>(ptr), static_cast<int>(size),
  3496. #else
  3497. ptr, size,
  3498. #endif
  3499. flags);
  3500. });
  3501. }
  3502. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  3503. int flags) {
  3504. return handle_EINTR([&]() {
  3505. return send(sock,
  3506. #ifdef _WIN32
  3507. static_cast<const char *>(ptr), static_cast<int>(size),
  3508. #else
  3509. ptr, size,
  3510. #endif
  3511. flags);
  3512. });
  3513. }
  3514. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  3515. #ifdef _WIN32
  3516. return ::WSAPoll(fds, nfds, timeout);
  3517. #else
  3518. return ::poll(fds, nfds, timeout);
  3519. #endif
  3520. }
  3521. template <bool Read>
  3522. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  3523. #ifdef __APPLE__
  3524. if (sock >= FD_SETSIZE) { return -1; }
  3525. fd_set fds, *rfds, *wfds;
  3526. FD_ZERO(&fds);
  3527. FD_SET(sock, &fds);
  3528. rfds = (Read ? &fds : nullptr);
  3529. wfds = (Read ? nullptr : &fds);
  3530. timeval tv;
  3531. tv.tv_sec = static_cast<long>(sec);
  3532. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3533. return handle_EINTR([&]() {
  3534. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  3535. });
  3536. #else
  3537. struct pollfd pfd;
  3538. pfd.fd = sock;
  3539. pfd.events = (Read ? POLLIN : POLLOUT);
  3540. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3541. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  3542. #endif
  3543. }
  3544. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  3545. return select_impl<true>(sock, sec, usec);
  3546. }
  3547. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  3548. return select_impl<false>(sock, sec, usec);
  3549. }
  3550. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  3551. time_t usec) {
  3552. #ifdef __APPLE__
  3553. if (sock >= FD_SETSIZE) { return Error::Connection; }
  3554. fd_set fdsr, fdsw;
  3555. FD_ZERO(&fdsr);
  3556. FD_ZERO(&fdsw);
  3557. FD_SET(sock, &fdsr);
  3558. FD_SET(sock, &fdsw);
  3559. timeval tv;
  3560. tv.tv_sec = static_cast<long>(sec);
  3561. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3562. auto ret = handle_EINTR([&]() {
  3563. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  3564. });
  3565. if (ret == 0) { return Error::ConnectionTimeout; }
  3566. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  3567. auto error = 0;
  3568. socklen_t len = sizeof(error);
  3569. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3570. reinterpret_cast<char *>(&error), &len);
  3571. auto successful = res >= 0 && !error;
  3572. return successful ? Error::Success : Error::Connection;
  3573. }
  3574. return Error::Connection;
  3575. #else
  3576. struct pollfd pfd_read;
  3577. pfd_read.fd = sock;
  3578. pfd_read.events = POLLIN | POLLOUT;
  3579. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3580. auto poll_res =
  3581. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  3582. if (poll_res == 0) { return Error::ConnectionTimeout; }
  3583. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  3584. auto error = 0;
  3585. socklen_t len = sizeof(error);
  3586. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3587. reinterpret_cast<char *>(&error), &len);
  3588. auto successful = res >= 0 && !error;
  3589. return successful ? Error::Success : Error::Connection;
  3590. }
  3591. return Error::Connection;
  3592. #endif
  3593. }
  3594. inline bool is_socket_alive(socket_t sock) {
  3595. const auto val = detail::select_read(sock, 0, 0);
  3596. if (val == 0) {
  3597. return true;
  3598. } else if (val < 0 && errno == EBADF) {
  3599. return false;
  3600. }
  3601. char buf[1];
  3602. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  3603. }
  3604. class SocketStream final : public Stream {
  3605. public:
  3606. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3607. time_t write_timeout_sec, time_t write_timeout_usec,
  3608. time_t max_timeout_msec = 0,
  3609. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3610. (std::chrono::steady_clock::time_point::min)());
  3611. ~SocketStream() override;
  3612. bool is_readable() const override;
  3613. bool wait_readable() const override;
  3614. bool wait_writable() const override;
  3615. ssize_t read(char *ptr, size_t size) override;
  3616. ssize_t write(const char *ptr, size_t size) override;
  3617. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3618. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3619. socket_t socket() const override;
  3620. time_t duration() const override;
  3621. private:
  3622. socket_t sock_;
  3623. time_t read_timeout_sec_;
  3624. time_t read_timeout_usec_;
  3625. time_t write_timeout_sec_;
  3626. time_t write_timeout_usec_;
  3627. time_t max_timeout_msec_;
  3628. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3629. std::vector<char> read_buff_;
  3630. size_t read_buff_off_ = 0;
  3631. size_t read_buff_content_size_ = 0;
  3632. static const size_t read_buff_size_ = 1024l * 4;
  3633. };
  3634. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3635. class SSLSocketStream final : public Stream {
  3636. public:
  3637. SSLSocketStream(
  3638. socket_t sock, SSL *ssl, time_t read_timeout_sec,
  3639. time_t read_timeout_usec, time_t write_timeout_sec,
  3640. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  3641. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3642. (std::chrono::steady_clock::time_point::min)());
  3643. ~SSLSocketStream() override;
  3644. bool is_readable() const override;
  3645. bool wait_readable() const override;
  3646. bool wait_writable() const override;
  3647. ssize_t read(char *ptr, size_t size) override;
  3648. ssize_t write(const char *ptr, size_t size) override;
  3649. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3650. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3651. socket_t socket() const override;
  3652. time_t duration() const override;
  3653. private:
  3654. socket_t sock_;
  3655. SSL *ssl_;
  3656. time_t read_timeout_sec_;
  3657. time_t read_timeout_usec_;
  3658. time_t write_timeout_sec_;
  3659. time_t write_timeout_usec_;
  3660. time_t max_timeout_msec_;
  3661. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3662. };
  3663. #endif
  3664. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3665. time_t keep_alive_timeout_sec) {
  3666. using namespace std::chrono;
  3667. const auto interval_usec =
  3668. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  3669. // Avoid expensive `steady_clock::now()` call for the first time
  3670. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  3671. const auto start = steady_clock::now() - microseconds{interval_usec};
  3672. const auto timeout = seconds{keep_alive_timeout_sec};
  3673. while (true) {
  3674. if (svr_sock == INVALID_SOCKET) {
  3675. break; // Server socket is closed
  3676. }
  3677. auto val = select_read(sock, 0, interval_usec);
  3678. if (val < 0) {
  3679. break; // Ssocket error
  3680. } else if (val == 0) {
  3681. if (steady_clock::now() - start > timeout) {
  3682. break; // Timeout
  3683. }
  3684. } else {
  3685. return true; // Ready for read
  3686. }
  3687. }
  3688. return false;
  3689. }
  3690. template <typename T>
  3691. inline bool
  3692. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3693. size_t keep_alive_max_count,
  3694. time_t keep_alive_timeout_sec, T callback) {
  3695. assert(keep_alive_max_count > 0);
  3696. auto ret = false;
  3697. auto count = keep_alive_max_count;
  3698. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  3699. auto close_connection = count == 1;
  3700. auto connection_closed = false;
  3701. ret = callback(close_connection, connection_closed);
  3702. if (!ret || connection_closed) { break; }
  3703. count--;
  3704. }
  3705. return ret;
  3706. }
  3707. template <typename T>
  3708. inline bool
  3709. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3710. size_t keep_alive_max_count,
  3711. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  3712. time_t read_timeout_usec, time_t write_timeout_sec,
  3713. time_t write_timeout_usec, T callback) {
  3714. return process_server_socket_core(
  3715. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  3716. [&](bool close_connection, bool &connection_closed) {
  3717. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3718. write_timeout_sec, write_timeout_usec);
  3719. return callback(strm, close_connection, connection_closed);
  3720. });
  3721. }
  3722. inline bool process_client_socket(
  3723. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3724. time_t write_timeout_sec, time_t write_timeout_usec,
  3725. time_t max_timeout_msec,
  3726. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3727. std::function<bool(Stream &)> callback) {
  3728. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3729. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  3730. start_time);
  3731. return callback(strm);
  3732. }
  3733. inline int shutdown_socket(socket_t sock) {
  3734. #ifdef _WIN32
  3735. return shutdown(sock, SD_BOTH);
  3736. #else
  3737. return shutdown(sock, SHUT_RDWR);
  3738. #endif
  3739. }
  3740. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  3741. if (s.size() > 1 && s[0] == '\0') {
  3742. auto ret = s;
  3743. ret[0] = '@';
  3744. return ret;
  3745. }
  3746. return s;
  3747. }
  3748. inline std::string
  3749. unescape_abstract_namespace_unix_domain(const std::string &s) {
  3750. if (s.size() > 1 && s[0] == '@') {
  3751. auto ret = s;
  3752. ret[0] = '\0';
  3753. return ret;
  3754. }
  3755. return s;
  3756. }
  3757. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  3758. const struct addrinfo *hints,
  3759. struct addrinfo **res, time_t timeout_sec) {
  3760. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  3761. if (timeout_sec <= 0) {
  3762. // No timeout specified, use standard getaddrinfo
  3763. return getaddrinfo(node, service, hints, res);
  3764. }
  3765. #ifdef _WIN32
  3766. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  3767. OVERLAPPED overlapped = {0};
  3768. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  3769. if (!event) { return EAI_FAIL; }
  3770. overlapped.hEvent = event;
  3771. PADDRINFOEXW result_addrinfo = nullptr;
  3772. HANDLE cancel_handle = nullptr;
  3773. ADDRINFOEXW hints_ex = {0};
  3774. if (hints) {
  3775. hints_ex.ai_flags = hints->ai_flags;
  3776. hints_ex.ai_family = hints->ai_family;
  3777. hints_ex.ai_socktype = hints->ai_socktype;
  3778. hints_ex.ai_protocol = hints->ai_protocol;
  3779. }
  3780. auto wnode = u8string_to_wstring(node);
  3781. auto wservice = u8string_to_wstring(service);
  3782. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  3783. hints ? &hints_ex : nullptr, &result_addrinfo,
  3784. nullptr, &overlapped, nullptr, &cancel_handle);
  3785. if (ret == WSA_IO_PENDING) {
  3786. auto wait_result =
  3787. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  3788. if (wait_result == WAIT_TIMEOUT) {
  3789. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  3790. ::CloseHandle(event);
  3791. return EAI_AGAIN;
  3792. }
  3793. DWORD bytes_returned;
  3794. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  3795. &bytes_returned, FALSE)) {
  3796. ::CloseHandle(event);
  3797. return ::WSAGetLastError();
  3798. }
  3799. }
  3800. ::CloseHandle(event);
  3801. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  3802. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  3803. return 0;
  3804. }
  3805. return ret;
  3806. #elif TARGET_OS_MAC
  3807. if (!node) { return EAI_NONAME; }
  3808. // macOS implementation using CFHost API for asynchronous DNS resolution
  3809. CFStringRef hostname_ref = CFStringCreateWithCString(
  3810. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  3811. if (!hostname_ref) { return EAI_MEMORY; }
  3812. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  3813. CFRelease(hostname_ref);
  3814. if (!host_ref) { return EAI_MEMORY; }
  3815. // Set up context for callback
  3816. struct CFHostContext {
  3817. bool completed = false;
  3818. bool success = false;
  3819. CFArrayRef addresses = nullptr;
  3820. std::mutex mutex;
  3821. std::condition_variable cv;
  3822. } context;
  3823. CFHostClientContext client_context;
  3824. memset(&client_context, 0, sizeof(client_context));
  3825. client_context.info = &context;
  3826. // Set callback
  3827. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  3828. const CFStreamError *error, void *info) {
  3829. auto ctx = static_cast<CFHostContext *>(info);
  3830. std::lock_guard<std::mutex> lock(ctx->mutex);
  3831. if (error && error->error != 0) {
  3832. ctx->success = false;
  3833. } else {
  3834. Boolean hasBeenResolved;
  3835. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  3836. if (ctx->addresses && hasBeenResolved) {
  3837. CFRetain(ctx->addresses);
  3838. ctx->success = true;
  3839. } else {
  3840. ctx->success = false;
  3841. }
  3842. }
  3843. ctx->completed = true;
  3844. ctx->cv.notify_one();
  3845. };
  3846. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  3847. CFRelease(host_ref);
  3848. return EAI_SYSTEM;
  3849. }
  3850. // Schedule on run loop
  3851. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  3852. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3853. // Start resolution
  3854. CFStreamError stream_error;
  3855. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  3856. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3857. CFRelease(host_ref);
  3858. return EAI_FAIL;
  3859. }
  3860. // Wait for completion with timeout
  3861. auto timeout_time =
  3862. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  3863. bool timed_out = false;
  3864. {
  3865. std::unique_lock<std::mutex> lock(context.mutex);
  3866. while (!context.completed) {
  3867. auto now = std::chrono::steady_clock::now();
  3868. if (now >= timeout_time) {
  3869. timed_out = true;
  3870. break;
  3871. }
  3872. // Run the runloop for a short time
  3873. lock.unlock();
  3874. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  3875. lock.lock();
  3876. }
  3877. }
  3878. // Clean up
  3879. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3880. CFHostSetClient(host_ref, nullptr, nullptr);
  3881. if (timed_out || !context.completed) {
  3882. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  3883. CFRelease(host_ref);
  3884. return EAI_AGAIN;
  3885. }
  3886. if (!context.success || !context.addresses) {
  3887. CFRelease(host_ref);
  3888. return EAI_NODATA;
  3889. }
  3890. // Convert CFArray to addrinfo
  3891. CFIndex count = CFArrayGetCount(context.addresses);
  3892. if (count == 0) {
  3893. CFRelease(context.addresses);
  3894. CFRelease(host_ref);
  3895. return EAI_NODATA;
  3896. }
  3897. struct addrinfo *result_addrinfo = nullptr;
  3898. struct addrinfo **current = &result_addrinfo;
  3899. for (CFIndex i = 0; i < count; i++) {
  3900. CFDataRef addr_data =
  3901. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  3902. if (!addr_data) continue;
  3903. const struct sockaddr *sockaddr_ptr =
  3904. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  3905. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  3906. // Allocate addrinfo structure
  3907. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  3908. if (!*current) {
  3909. freeaddrinfo(result_addrinfo);
  3910. CFRelease(context.addresses);
  3911. CFRelease(host_ref);
  3912. return EAI_MEMORY;
  3913. }
  3914. memset(*current, 0, sizeof(struct addrinfo));
  3915. // Set up addrinfo fields
  3916. (*current)->ai_family = sockaddr_ptr->sa_family;
  3917. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  3918. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  3919. (*current)->ai_addrlen = sockaddr_len;
  3920. // Copy sockaddr
  3921. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  3922. if (!(*current)->ai_addr) {
  3923. freeaddrinfo(result_addrinfo);
  3924. CFRelease(context.addresses);
  3925. CFRelease(host_ref);
  3926. return EAI_MEMORY;
  3927. }
  3928. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  3929. // Set port if service is specified
  3930. if (service && strlen(service) > 0) {
  3931. int port = atoi(service);
  3932. if (port > 0) {
  3933. if (sockaddr_ptr->sa_family == AF_INET) {
  3934. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  3935. ->sin_port = htons(static_cast<uint16_t>(port));
  3936. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  3937. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  3938. ->sin6_port = htons(static_cast<uint16_t>(port));
  3939. }
  3940. }
  3941. }
  3942. current = &((*current)->ai_next);
  3943. }
  3944. CFRelease(context.addresses);
  3945. CFRelease(host_ref);
  3946. *res = result_addrinfo;
  3947. return 0;
  3948. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  3949. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  3950. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  3951. struct gaicb request;
  3952. struct gaicb *requests[1] = {&request};
  3953. struct sigevent sevp;
  3954. struct timespec timeout;
  3955. // Initialize the request structure
  3956. memset(&request, 0, sizeof(request));
  3957. request.ar_name = node;
  3958. request.ar_service = service;
  3959. request.ar_request = hints;
  3960. // Set up timeout
  3961. timeout.tv_sec = timeout_sec;
  3962. timeout.tv_nsec = 0;
  3963. // Initialize sigevent structure (not used, but required)
  3964. memset(&sevp, 0, sizeof(sevp));
  3965. sevp.sigev_notify = SIGEV_NONE;
  3966. // Start asynchronous resolution
  3967. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  3968. if (start_result != 0) { return start_result; }
  3969. // Wait for completion with timeout
  3970. int wait_result =
  3971. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  3972. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  3973. // Completed successfully, get the result
  3974. int gai_result = gai_error(&request);
  3975. if (gai_result == 0) {
  3976. *res = request.ar_result;
  3977. return 0;
  3978. } else {
  3979. // Clean up on error
  3980. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  3981. return gai_result;
  3982. }
  3983. } else if (wait_result == EAI_AGAIN) {
  3984. // Timeout occurred, cancel the request
  3985. gai_cancel(&request);
  3986. return EAI_AGAIN;
  3987. } else {
  3988. // Other error occurred
  3989. gai_cancel(&request);
  3990. return wait_result;
  3991. }
  3992. #else
  3993. // Fallback implementation using thread-based timeout for other Unix systems
  3994. struct GetAddrInfoState {
  3995. ~GetAddrInfoState() {
  3996. if (info) { freeaddrinfo(info); }
  3997. }
  3998. std::mutex mutex;
  3999. std::condition_variable result_cv;
  4000. bool completed = false;
  4001. int result = EAI_SYSTEM;
  4002. std::string node;
  4003. std::string service;
  4004. struct addrinfo hints;
  4005. struct addrinfo *info = nullptr;
  4006. };
  4007. // Allocate on the heap, so the resolver thread can keep using the data.
  4008. auto state = std::make_shared<GetAddrInfoState>();
  4009. if (node) { state->node = node; }
  4010. state->service = service;
  4011. state->hints = *hints;
  4012. std::thread resolve_thread([state]() {
  4013. auto thread_result =
  4014. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  4015. &state->info);
  4016. std::lock_guard<std::mutex> lock(state->mutex);
  4017. state->result = thread_result;
  4018. state->completed = true;
  4019. state->result_cv.notify_one();
  4020. });
  4021. // Wait for completion or timeout
  4022. std::unique_lock<std::mutex> lock(state->mutex);
  4023. auto finished =
  4024. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  4025. [&] { return state->completed; });
  4026. if (finished) {
  4027. // Operation completed within timeout
  4028. resolve_thread.join();
  4029. *res = state->info;
  4030. state->info = nullptr; // Pass ownership to caller
  4031. return state->result;
  4032. } else {
  4033. // Timeout occurred
  4034. resolve_thread.detach(); // Let the thread finish in background
  4035. return EAI_AGAIN; // Return timeout error
  4036. }
  4037. #endif
  4038. #else
  4039. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  4040. return getaddrinfo(node, service, hints, res);
  4041. #endif
  4042. }
  4043. template <typename BindOrConnect>
  4044. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  4045. int address_family, int socket_flags, bool tcp_nodelay,
  4046. bool ipv6_v6only, SocketOptions socket_options,
  4047. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  4048. // Get address info
  4049. const char *node = nullptr;
  4050. struct addrinfo hints;
  4051. struct addrinfo *result;
  4052. memset(&hints, 0, sizeof(struct addrinfo));
  4053. hints.ai_socktype = SOCK_STREAM;
  4054. hints.ai_protocol = IPPROTO_IP;
  4055. if (!ip.empty()) {
  4056. node = ip.c_str();
  4057. // Ask getaddrinfo to convert IP in c-string to address
  4058. hints.ai_family = AF_UNSPEC;
  4059. hints.ai_flags = AI_NUMERICHOST;
  4060. } else {
  4061. if (!host.empty()) { node = host.c_str(); }
  4062. hints.ai_family = address_family;
  4063. hints.ai_flags = socket_flags;
  4064. }
  4065. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  4066. if (hints.ai_family == AF_UNIX) {
  4067. const auto addrlen = host.length();
  4068. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  4069. #ifdef SOCK_CLOEXEC
  4070. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  4071. hints.ai_protocol);
  4072. #else
  4073. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4074. #endif
  4075. if (sock != INVALID_SOCKET) {
  4076. sockaddr_un addr{};
  4077. addr.sun_family = AF_UNIX;
  4078. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  4079. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  4080. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  4081. hints.ai_addrlen = static_cast<socklen_t>(
  4082. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  4083. #ifndef SOCK_CLOEXEC
  4084. #ifndef _WIN32
  4085. fcntl(sock, F_SETFD, FD_CLOEXEC);
  4086. #endif
  4087. #endif
  4088. if (socket_options) { socket_options(sock); }
  4089. #ifdef _WIN32
  4090. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  4091. // remove the option.
  4092. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  4093. #endif
  4094. bool dummy;
  4095. if (!bind_or_connect(sock, hints, dummy)) {
  4096. close_socket(sock);
  4097. sock = INVALID_SOCKET;
  4098. }
  4099. }
  4100. return sock;
  4101. }
  4102. #endif
  4103. auto service = std::to_string(port);
  4104. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  4105. timeout_sec)) {
  4106. #if defined __linux__ && !defined __ANDROID__
  4107. res_init();
  4108. #endif
  4109. return INVALID_SOCKET;
  4110. }
  4111. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4112. for (auto rp = result; rp; rp = rp->ai_next) {
  4113. // Create a socket
  4114. #ifdef _WIN32
  4115. auto sock =
  4116. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  4117. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  4118. /**
  4119. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  4120. * and above the socket creation fails on older Windows Systems.
  4121. *
  4122. * Let's try to create a socket the old way in this case.
  4123. *
  4124. * Reference:
  4125. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  4126. *
  4127. * WSA_FLAG_NO_HANDLE_INHERIT:
  4128. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  4129. * SP1, and later
  4130. *
  4131. */
  4132. if (sock == INVALID_SOCKET) {
  4133. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4134. }
  4135. #else
  4136. #ifdef SOCK_CLOEXEC
  4137. auto sock =
  4138. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  4139. #else
  4140. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4141. #endif
  4142. #endif
  4143. if (sock == INVALID_SOCKET) { continue; }
  4144. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  4145. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  4146. close_socket(sock);
  4147. continue;
  4148. }
  4149. #endif
  4150. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  4151. if (rp->ai_family == AF_INET6) {
  4152. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  4153. }
  4154. if (socket_options) { socket_options(sock); }
  4155. // bind or connect
  4156. auto quit = false;
  4157. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  4158. close_socket(sock);
  4159. if (quit) { break; }
  4160. }
  4161. return INVALID_SOCKET;
  4162. }
  4163. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  4164. #ifdef _WIN32
  4165. auto flags = nonblocking ? 1UL : 0UL;
  4166. ioctlsocket(sock, FIONBIO, &flags);
  4167. #else
  4168. auto flags = fcntl(sock, F_GETFL, 0);
  4169. fcntl(sock, F_SETFL,
  4170. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  4171. #endif
  4172. }
  4173. inline bool is_connection_error() {
  4174. #ifdef _WIN32
  4175. return WSAGetLastError() != WSAEWOULDBLOCK;
  4176. #else
  4177. return errno != EINPROGRESS;
  4178. #endif
  4179. }
  4180. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  4181. struct addrinfo hints;
  4182. struct addrinfo *result;
  4183. memset(&hints, 0, sizeof(struct addrinfo));
  4184. hints.ai_family = AF_UNSPEC;
  4185. hints.ai_socktype = SOCK_STREAM;
  4186. hints.ai_protocol = 0;
  4187. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  4188. return false;
  4189. }
  4190. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4191. auto ret = false;
  4192. for (auto rp = result; rp; rp = rp->ai_next) {
  4193. const auto &ai = *rp;
  4194. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4195. ret = true;
  4196. break;
  4197. }
  4198. }
  4199. return ret;
  4200. }
  4201. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  4202. #define USE_IF2IP
  4203. #endif
  4204. #ifdef USE_IF2IP
  4205. inline std::string if2ip(int address_family, const std::string &ifn) {
  4206. struct ifaddrs *ifap;
  4207. getifaddrs(&ifap);
  4208. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  4209. std::string addr_candidate;
  4210. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  4211. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  4212. (AF_UNSPEC == address_family ||
  4213. ifa->ifa_addr->sa_family == address_family)) {
  4214. if (ifa->ifa_addr->sa_family == AF_INET) {
  4215. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  4216. char buf[INET_ADDRSTRLEN];
  4217. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  4218. return std::string(buf, INET_ADDRSTRLEN);
  4219. }
  4220. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  4221. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  4222. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  4223. char buf[INET6_ADDRSTRLEN] = {};
  4224. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  4225. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  4226. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  4227. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  4228. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  4229. } else {
  4230. return std::string(buf, INET6_ADDRSTRLEN);
  4231. }
  4232. }
  4233. }
  4234. }
  4235. }
  4236. }
  4237. return addr_candidate;
  4238. }
  4239. #endif
  4240. inline socket_t create_client_socket(
  4241. const std::string &host, const std::string &ip, int port,
  4242. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  4243. SocketOptions socket_options, time_t connection_timeout_sec,
  4244. time_t connection_timeout_usec, time_t read_timeout_sec,
  4245. time_t read_timeout_usec, time_t write_timeout_sec,
  4246. time_t write_timeout_usec, const std::string &intf, Error &error) {
  4247. auto sock = create_socket(
  4248. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  4249. std::move(socket_options),
  4250. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  4251. if (!intf.empty()) {
  4252. #ifdef USE_IF2IP
  4253. auto ip_from_if = if2ip(address_family, intf);
  4254. if (ip_from_if.empty()) { ip_from_if = intf; }
  4255. if (!bind_ip_address(sock2, ip_from_if)) {
  4256. error = Error::BindIPAddress;
  4257. return false;
  4258. }
  4259. #endif
  4260. }
  4261. set_nonblocking(sock2, true);
  4262. auto ret =
  4263. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  4264. if (ret < 0) {
  4265. if (is_connection_error()) {
  4266. error = Error::Connection;
  4267. return false;
  4268. }
  4269. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  4270. connection_timeout_usec);
  4271. if (error != Error::Success) {
  4272. if (error == Error::ConnectionTimeout) { quit = true; }
  4273. return false;
  4274. }
  4275. }
  4276. set_nonblocking(sock2, false);
  4277. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  4278. read_timeout_usec);
  4279. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  4280. write_timeout_usec);
  4281. error = Error::Success;
  4282. return true;
  4283. },
  4284. connection_timeout_sec); // Pass DNS timeout
  4285. if (sock != INVALID_SOCKET) {
  4286. error = Error::Success;
  4287. } else {
  4288. if (error == Error::Success) { error = Error::Connection; }
  4289. }
  4290. return sock;
  4291. }
  4292. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  4293. socklen_t addr_len, std::string &ip, int &port) {
  4294. if (addr.ss_family == AF_INET) {
  4295. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  4296. } else if (addr.ss_family == AF_INET6) {
  4297. port =
  4298. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  4299. } else {
  4300. return false;
  4301. }
  4302. std::array<char, NI_MAXHOST> ipstr{};
  4303. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  4304. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  4305. 0, NI_NUMERICHOST)) {
  4306. return false;
  4307. }
  4308. ip = ipstr.data();
  4309. return true;
  4310. }
  4311. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4312. struct sockaddr_storage addr;
  4313. socklen_t addr_len = sizeof(addr);
  4314. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4315. &addr_len)) {
  4316. get_ip_and_port(addr, addr_len, ip, port);
  4317. }
  4318. }
  4319. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4320. struct sockaddr_storage addr;
  4321. socklen_t addr_len = sizeof(addr);
  4322. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4323. &addr_len)) {
  4324. #ifndef _WIN32
  4325. if (addr.ss_family == AF_UNIX) {
  4326. #if defined(__linux__)
  4327. struct ucred ucred;
  4328. socklen_t len = sizeof(ucred);
  4329. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  4330. port = ucred.pid;
  4331. }
  4332. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  4333. pid_t pid;
  4334. socklen_t len = sizeof(pid);
  4335. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  4336. port = pid;
  4337. }
  4338. #endif
  4339. return;
  4340. }
  4341. #endif
  4342. get_ip_and_port(addr, addr_len, ip, port);
  4343. }
  4344. }
  4345. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  4346. unsigned int h) {
  4347. return (l == 0)
  4348. ? h
  4349. : str2tag_core(
  4350. s + 1, l - 1,
  4351. // Unsets the 6 high bits of h, therefore no overflow happens
  4352. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  4353. h * 33) ^
  4354. static_cast<unsigned char>(*s));
  4355. }
  4356. inline unsigned int str2tag(const std::string &s) {
  4357. return str2tag_core(s.data(), s.size(), 0);
  4358. }
  4359. namespace udl {
  4360. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  4361. return str2tag_core(s, l, 0);
  4362. }
  4363. } // namespace udl
  4364. inline std::string
  4365. find_content_type(const std::string &path,
  4366. const std::map<std::string, std::string> &user_data,
  4367. const std::string &default_content_type) {
  4368. auto ext = file_extension(path);
  4369. auto it = user_data.find(ext);
  4370. if (it != user_data.end()) { return it->second; }
  4371. using udl::operator""_t;
  4372. switch (str2tag(ext)) {
  4373. default: return default_content_type;
  4374. case "css"_t: return "text/css";
  4375. case "csv"_t: return "text/csv";
  4376. case "htm"_t:
  4377. case "html"_t: return "text/html";
  4378. case "js"_t:
  4379. case "mjs"_t: return "text/javascript";
  4380. case "txt"_t: return "text/plain";
  4381. case "vtt"_t: return "text/vtt";
  4382. case "apng"_t: return "image/apng";
  4383. case "avif"_t: return "image/avif";
  4384. case "bmp"_t: return "image/bmp";
  4385. case "gif"_t: return "image/gif";
  4386. case "png"_t: return "image/png";
  4387. case "svg"_t: return "image/svg+xml";
  4388. case "webp"_t: return "image/webp";
  4389. case "ico"_t: return "image/x-icon";
  4390. case "tif"_t: return "image/tiff";
  4391. case "tiff"_t: return "image/tiff";
  4392. case "jpg"_t:
  4393. case "jpeg"_t: return "image/jpeg";
  4394. case "mp4"_t: return "video/mp4";
  4395. case "mpeg"_t: return "video/mpeg";
  4396. case "webm"_t: return "video/webm";
  4397. case "mp3"_t: return "audio/mp3";
  4398. case "mpga"_t: return "audio/mpeg";
  4399. case "weba"_t: return "audio/webm";
  4400. case "wav"_t: return "audio/wave";
  4401. case "otf"_t: return "font/otf";
  4402. case "ttf"_t: return "font/ttf";
  4403. case "woff"_t: return "font/woff";
  4404. case "woff2"_t: return "font/woff2";
  4405. case "7z"_t: return "application/x-7z-compressed";
  4406. case "atom"_t: return "application/atom+xml";
  4407. case "pdf"_t: return "application/pdf";
  4408. case "json"_t: return "application/json";
  4409. case "rss"_t: return "application/rss+xml";
  4410. case "tar"_t: return "application/x-tar";
  4411. case "xht"_t:
  4412. case "xhtml"_t: return "application/xhtml+xml";
  4413. case "xslt"_t: return "application/xslt+xml";
  4414. case "xml"_t: return "application/xml";
  4415. case "gz"_t: return "application/gzip";
  4416. case "zip"_t: return "application/zip";
  4417. case "wasm"_t: return "application/wasm";
  4418. }
  4419. }
  4420. inline bool can_compress_content_type(const std::string &content_type) {
  4421. using udl::operator""_t;
  4422. auto tag = str2tag(content_type);
  4423. switch (tag) {
  4424. case "image/svg+xml"_t:
  4425. case "application/javascript"_t:
  4426. case "application/json"_t:
  4427. case "application/xml"_t:
  4428. case "application/protobuf"_t:
  4429. case "application/xhtml+xml"_t: return true;
  4430. case "text/event-stream"_t: return false;
  4431. default: return !content_type.rfind("text/", 0);
  4432. }
  4433. }
  4434. inline EncodingType encoding_type(const Request &req, const Response &res) {
  4435. auto ret =
  4436. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  4437. if (!ret) { return EncodingType::None; }
  4438. const auto &s = req.get_header_value("Accept-Encoding");
  4439. (void)(s);
  4440. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4441. // TODO: 'Accept-Encoding' has br, not br;q=0
  4442. ret = s.find("br") != std::string::npos;
  4443. if (ret) { return EncodingType::Brotli; }
  4444. #endif
  4445. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4446. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  4447. ret = s.find("gzip") != std::string::npos;
  4448. if (ret) { return EncodingType::Gzip; }
  4449. #endif
  4450. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4451. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  4452. ret = s.find("zstd") != std::string::npos;
  4453. if (ret) { return EncodingType::Zstd; }
  4454. #endif
  4455. return EncodingType::None;
  4456. }
  4457. inline bool nocompressor::compress(const char *data, size_t data_length,
  4458. bool /*last*/, Callback callback) {
  4459. if (!data_length) { return true; }
  4460. return callback(data, data_length);
  4461. }
  4462. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4463. inline gzip_compressor::gzip_compressor() {
  4464. std::memset(&strm_, 0, sizeof(strm_));
  4465. strm_.zalloc = Z_NULL;
  4466. strm_.zfree = Z_NULL;
  4467. strm_.opaque = Z_NULL;
  4468. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  4469. Z_DEFAULT_STRATEGY) == Z_OK;
  4470. }
  4471. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  4472. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  4473. bool last, Callback callback) {
  4474. assert(is_valid_);
  4475. do {
  4476. constexpr size_t max_avail_in =
  4477. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4478. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4479. (std::min)(data_length, max_avail_in));
  4480. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4481. data_length -= strm_.avail_in;
  4482. data += strm_.avail_in;
  4483. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  4484. auto ret = Z_OK;
  4485. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4486. do {
  4487. strm_.avail_out = static_cast<uInt>(buff.size());
  4488. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4489. ret = deflate(&strm_, flush);
  4490. if (ret == Z_STREAM_ERROR) { return false; }
  4491. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4492. return false;
  4493. }
  4494. } while (strm_.avail_out == 0);
  4495. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  4496. (flush == Z_NO_FLUSH && ret == Z_OK));
  4497. assert(strm_.avail_in == 0);
  4498. } while (data_length > 0);
  4499. return true;
  4500. }
  4501. inline gzip_decompressor::gzip_decompressor() {
  4502. std::memset(&strm_, 0, sizeof(strm_));
  4503. strm_.zalloc = Z_NULL;
  4504. strm_.zfree = Z_NULL;
  4505. strm_.opaque = Z_NULL;
  4506. // 15 is the value of wbits, which should be at the maximum possible value
  4507. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  4508. // that the stream type should be automatically detected either gzip or
  4509. // deflate.
  4510. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  4511. }
  4512. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  4513. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  4514. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  4515. Callback callback) {
  4516. assert(is_valid_);
  4517. auto ret = Z_OK;
  4518. do {
  4519. constexpr size_t max_avail_in =
  4520. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4521. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4522. (std::min)(data_length, max_avail_in));
  4523. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4524. data_length -= strm_.avail_in;
  4525. data += strm_.avail_in;
  4526. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4527. while (strm_.avail_in > 0 && ret == Z_OK) {
  4528. strm_.avail_out = static_cast<uInt>(buff.size());
  4529. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4530. ret = inflate(&strm_, Z_NO_FLUSH);
  4531. assert(ret != Z_STREAM_ERROR);
  4532. switch (ret) {
  4533. case Z_NEED_DICT:
  4534. case Z_DATA_ERROR:
  4535. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  4536. }
  4537. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4538. return false;
  4539. }
  4540. }
  4541. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  4542. } while (data_length > 0);
  4543. return true;
  4544. }
  4545. #endif
  4546. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4547. inline brotli_compressor::brotli_compressor() {
  4548. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  4549. }
  4550. inline brotli_compressor::~brotli_compressor() {
  4551. BrotliEncoderDestroyInstance(state_);
  4552. }
  4553. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  4554. bool last, Callback callback) {
  4555. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4556. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  4557. auto available_in = data_length;
  4558. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4559. for (;;) {
  4560. if (last) {
  4561. if (BrotliEncoderIsFinished(state_)) { break; }
  4562. } else {
  4563. if (!available_in) { break; }
  4564. }
  4565. auto available_out = buff.size();
  4566. auto next_out = buff.data();
  4567. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  4568. &available_out, &next_out, nullptr)) {
  4569. return false;
  4570. }
  4571. auto output_bytes = buff.size() - available_out;
  4572. if (output_bytes) {
  4573. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  4574. }
  4575. }
  4576. return true;
  4577. }
  4578. inline brotli_decompressor::brotli_decompressor() {
  4579. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  4580. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  4581. : BROTLI_DECODER_RESULT_ERROR;
  4582. }
  4583. inline brotli_decompressor::~brotli_decompressor() {
  4584. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  4585. }
  4586. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  4587. inline bool brotli_decompressor::decompress(const char *data,
  4588. size_t data_length,
  4589. Callback callback) {
  4590. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4591. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  4592. return 0;
  4593. }
  4594. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4595. size_t avail_in = data_length;
  4596. size_t total_out;
  4597. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  4598. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4599. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  4600. char *next_out = buff.data();
  4601. size_t avail_out = buff.size();
  4602. decoder_r = BrotliDecoderDecompressStream(
  4603. decoder_s, &avail_in, &next_in, &avail_out,
  4604. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  4605. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  4606. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  4607. }
  4608. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4609. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  4610. }
  4611. #endif
  4612. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4613. inline zstd_compressor::zstd_compressor() {
  4614. ctx_ = ZSTD_createCCtx();
  4615. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  4616. }
  4617. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  4618. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  4619. bool last, Callback callback) {
  4620. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4621. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  4622. ZSTD_inBuffer input = {data, data_length, 0};
  4623. bool finished;
  4624. do {
  4625. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4626. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  4627. if (ZSTD_isError(remaining)) { return false; }
  4628. if (!callback(buff.data(), output.pos)) { return false; }
  4629. finished = last ? (remaining == 0) : (input.pos == input.size);
  4630. } while (!finished);
  4631. return true;
  4632. }
  4633. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  4634. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  4635. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  4636. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  4637. Callback callback) {
  4638. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4639. ZSTD_inBuffer input = {data, data_length, 0};
  4640. while (input.pos < input.size) {
  4641. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4642. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  4643. if (ZSTD_isError(remaining)) { return false; }
  4644. if (!callback(buff.data(), output.pos)) { return false; }
  4645. }
  4646. return true;
  4647. }
  4648. #endif
  4649. inline std::unique_ptr<decompressor>
  4650. create_decompressor(const std::string &encoding) {
  4651. std::unique_ptr<decompressor> decompressor;
  4652. if (encoding == "gzip" || encoding == "deflate") {
  4653. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4654. decompressor = detail::make_unique<gzip_decompressor>();
  4655. #endif
  4656. } else if (encoding.find("br") != std::string::npos) {
  4657. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4658. decompressor = detail::make_unique<brotli_decompressor>();
  4659. #endif
  4660. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  4661. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4662. decompressor = detail::make_unique<zstd_decompressor>();
  4663. #endif
  4664. }
  4665. return decompressor;
  4666. }
  4667. inline bool is_prohibited_header_name(const std::string &name) {
  4668. using udl::operator""_t;
  4669. switch (str2tag(name)) {
  4670. case "REMOTE_ADDR"_t:
  4671. case "REMOTE_PORT"_t:
  4672. case "LOCAL_ADDR"_t:
  4673. case "LOCAL_PORT"_t: return true;
  4674. default: return false;
  4675. }
  4676. }
  4677. inline bool has_header(const Headers &headers, const std::string &key) {
  4678. if (is_prohibited_header_name(key)) { return false; }
  4679. return headers.find(key) != headers.end();
  4680. }
  4681. inline const char *get_header_value(const Headers &headers,
  4682. const std::string &key, const char *def,
  4683. size_t id) {
  4684. if (is_prohibited_header_name(key)) {
  4685. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4686. std::string msg = "Prohibited header name '" + key + "' is specified.";
  4687. throw std::invalid_argument(msg);
  4688. #else
  4689. return "";
  4690. #endif
  4691. }
  4692. auto rng = headers.equal_range(key);
  4693. auto it = rng.first;
  4694. std::advance(it, static_cast<ssize_t>(id));
  4695. if (it != rng.second) { return it->second.c_str(); }
  4696. return def;
  4697. }
  4698. inline bool read_headers(Stream &strm, Headers &headers) {
  4699. const auto bufsiz = 2048;
  4700. char buf[bufsiz];
  4701. stream_line_reader line_reader(strm, buf, bufsiz);
  4702. size_t header_count = 0;
  4703. for (;;) {
  4704. if (!line_reader.getline()) { return false; }
  4705. // Check if the line ends with CRLF.
  4706. auto line_terminator_len = 2;
  4707. if (line_reader.end_with_crlf()) {
  4708. // Blank line indicates end of headers.
  4709. if (line_reader.size() == 2) { break; }
  4710. } else {
  4711. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4712. // Blank line indicates end of headers.
  4713. if (line_reader.size() == 1) { break; }
  4714. line_terminator_len = 1;
  4715. #else
  4716. continue; // Skip invalid line.
  4717. #endif
  4718. }
  4719. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4720. // Check header count limit
  4721. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4722. // Exclude line terminator
  4723. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  4724. if (!parse_header(line_reader.ptr(), end,
  4725. [&](const std::string &key, const std::string &val) {
  4726. headers.emplace(key, val);
  4727. })) {
  4728. return false;
  4729. }
  4730. header_count++;
  4731. }
  4732. return true;
  4733. }
  4734. inline bool read_content_with_length(Stream &strm, size_t len,
  4735. DownloadProgress progress,
  4736. ContentReceiverWithProgress out) {
  4737. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4738. detail::BodyReader br;
  4739. br.stream = &strm;
  4740. br.content_length = len;
  4741. br.chunked = false;
  4742. br.bytes_read = 0;
  4743. br.last_error = Error::Success;
  4744. size_t r = 0;
  4745. while (r < len) {
  4746. auto read_len = static_cast<size_t>(len - r);
  4747. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  4748. auto n = detail::read_body_content(&strm, br, buf, to_read);
  4749. if (n <= 0) { return false; }
  4750. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  4751. r += static_cast<size_t>(n);
  4752. if (progress) {
  4753. if (!progress(r, len)) { return false; }
  4754. }
  4755. }
  4756. return true;
  4757. }
  4758. inline void skip_content_with_length(Stream &strm, size_t len) {
  4759. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4760. size_t r = 0;
  4761. while (r < len) {
  4762. auto read_len = static_cast<size_t>(len - r);
  4763. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  4764. if (n <= 0) { return; }
  4765. r += static_cast<size_t>(n);
  4766. }
  4767. }
  4768. enum class ReadContentResult {
  4769. Success, // Successfully read the content
  4770. PayloadTooLarge, // The content exceeds the specified payload limit
  4771. Error // An error occurred while reading the content
  4772. };
  4773. inline ReadContentResult
  4774. read_content_without_length(Stream &strm, size_t payload_max_length,
  4775. ContentReceiverWithProgress out) {
  4776. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4777. size_t r = 0;
  4778. for (;;) {
  4779. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  4780. if (n == 0) { return ReadContentResult::Success; }
  4781. if (n < 0) { return ReadContentResult::Error; }
  4782. // Check if adding this data would exceed the payload limit
  4783. if (r > payload_max_length ||
  4784. payload_max_length - r < static_cast<size_t>(n)) {
  4785. return ReadContentResult::PayloadTooLarge;
  4786. }
  4787. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  4788. return ReadContentResult::Error;
  4789. }
  4790. r += static_cast<size_t>(n);
  4791. }
  4792. return ReadContentResult::Success;
  4793. }
  4794. template <typename T>
  4795. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  4796. size_t payload_max_length,
  4797. ContentReceiverWithProgress out) {
  4798. detail::ChunkedDecoder dec(strm);
  4799. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4800. size_t total_len = 0;
  4801. for (;;) {
  4802. size_t chunk_offset = 0;
  4803. size_t chunk_total = 0;
  4804. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  4805. if (n < 0) { return ReadContentResult::Error; }
  4806. if (n == 0) {
  4807. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  4808. return ReadContentResult::Error;
  4809. }
  4810. return ReadContentResult::Success;
  4811. }
  4812. if (total_len > payload_max_length ||
  4813. payload_max_length - total_len < static_cast<size_t>(n)) {
  4814. return ReadContentResult::PayloadTooLarge;
  4815. }
  4816. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  4817. return ReadContentResult::Error;
  4818. }
  4819. total_len += static_cast<size_t>(n);
  4820. }
  4821. }
  4822. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  4823. return case_ignore::equal(
  4824. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  4825. }
  4826. template <typename T, typename U>
  4827. bool prepare_content_receiver(T &x, int &status,
  4828. ContentReceiverWithProgress receiver,
  4829. bool decompress, U callback) {
  4830. if (decompress) {
  4831. std::string encoding = x.get_header_value("Content-Encoding");
  4832. std::unique_ptr<decompressor> decompressor;
  4833. if (!encoding.empty()) {
  4834. decompressor = detail::create_decompressor(encoding);
  4835. if (!decompressor) {
  4836. // Unsupported encoding or no support compiled in
  4837. status = StatusCode::UnsupportedMediaType_415;
  4838. return false;
  4839. }
  4840. }
  4841. if (decompressor) {
  4842. if (decompressor->is_valid()) {
  4843. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  4844. size_t off, size_t len) {
  4845. return decompressor->decompress(buf, n,
  4846. [&](const char *buf2, size_t n2) {
  4847. return receiver(buf2, n2, off, len);
  4848. });
  4849. };
  4850. return callback(std::move(out));
  4851. } else {
  4852. status = StatusCode::InternalServerError_500;
  4853. return false;
  4854. }
  4855. }
  4856. }
  4857. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  4858. size_t len) {
  4859. return receiver(buf, n, off, len);
  4860. };
  4861. return callback(std::move(out));
  4862. }
  4863. template <typename T>
  4864. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  4865. DownloadProgress progress,
  4866. ContentReceiverWithProgress receiver, bool decompress) {
  4867. return prepare_content_receiver(
  4868. x, status, std::move(receiver), decompress,
  4869. [&](const ContentReceiverWithProgress &out) {
  4870. auto ret = true;
  4871. auto exceed_payload_max_length = false;
  4872. if (is_chunked_transfer_encoding(x.headers)) {
  4873. auto result = read_content_chunked(strm, x, payload_max_length, out);
  4874. if (result == ReadContentResult::Success) {
  4875. ret = true;
  4876. } else if (result == ReadContentResult::PayloadTooLarge) {
  4877. exceed_payload_max_length = true;
  4878. ret = false;
  4879. } else {
  4880. ret = false;
  4881. }
  4882. } else if (!has_header(x.headers, "Content-Length")) {
  4883. auto result =
  4884. read_content_without_length(strm, payload_max_length, out);
  4885. if (result == ReadContentResult::Success) {
  4886. ret = true;
  4887. } else if (result == ReadContentResult::PayloadTooLarge) {
  4888. exceed_payload_max_length = true;
  4889. ret = false;
  4890. } else {
  4891. ret = false;
  4892. }
  4893. } else {
  4894. auto is_invalid_value = false;
  4895. auto len = get_header_value_u64(x.headers, "Content-Length",
  4896. (std::numeric_limits<size_t>::max)(),
  4897. 0, is_invalid_value);
  4898. if (is_invalid_value) {
  4899. ret = false;
  4900. } else if (len > payload_max_length) {
  4901. exceed_payload_max_length = true;
  4902. skip_content_with_length(strm, len);
  4903. ret = false;
  4904. } else if (len > 0) {
  4905. ret = read_content_with_length(strm, len, std::move(progress), out);
  4906. }
  4907. }
  4908. if (!ret) {
  4909. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  4910. : StatusCode::BadRequest_400;
  4911. }
  4912. return ret;
  4913. });
  4914. }
  4915. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  4916. const std::string &path) {
  4917. std::string s = method;
  4918. s += ' ';
  4919. s += path;
  4920. s += " HTTP/1.1\r\n";
  4921. return strm.write(s.data(), s.size());
  4922. }
  4923. inline ssize_t write_response_line(Stream &strm, int status) {
  4924. std::string s = "HTTP/1.1 ";
  4925. s += std::to_string(status);
  4926. s += ' ';
  4927. s += httplib::status_message(status);
  4928. s += "\r\n";
  4929. return strm.write(s.data(), s.size());
  4930. }
  4931. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  4932. ssize_t write_len = 0;
  4933. for (const auto &x : headers) {
  4934. std::string s;
  4935. s = x.first;
  4936. s += ": ";
  4937. s += x.second;
  4938. s += "\r\n";
  4939. auto len = strm.write(s.data(), s.size());
  4940. if (len < 0) { return len; }
  4941. write_len += len;
  4942. }
  4943. auto len = strm.write("\r\n");
  4944. if (len < 0) { return len; }
  4945. write_len += len;
  4946. return write_len;
  4947. }
  4948. inline bool write_data(Stream &strm, const char *d, size_t l) {
  4949. size_t offset = 0;
  4950. while (offset < l) {
  4951. auto length = strm.write(d + offset, l - offset);
  4952. if (length < 0) { return false; }
  4953. offset += static_cast<size_t>(length);
  4954. }
  4955. return true;
  4956. }
  4957. template <typename T>
  4958. inline bool write_content_with_progress(Stream &strm,
  4959. const ContentProvider &content_provider,
  4960. size_t offset, size_t length,
  4961. T is_shutting_down,
  4962. const UploadProgress &upload_progress,
  4963. Error &error) {
  4964. size_t end_offset = offset + length;
  4965. size_t start_offset = offset;
  4966. auto ok = true;
  4967. DataSink data_sink;
  4968. data_sink.write = [&](const char *d, size_t l) -> bool {
  4969. if (ok) {
  4970. if (write_data(strm, d, l)) {
  4971. offset += l;
  4972. if (upload_progress && length > 0) {
  4973. size_t current_written = offset - start_offset;
  4974. if (!upload_progress(current_written, length)) {
  4975. ok = false;
  4976. return false;
  4977. }
  4978. }
  4979. } else {
  4980. ok = false;
  4981. }
  4982. }
  4983. return ok;
  4984. };
  4985. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4986. while (offset < end_offset && !is_shutting_down()) {
  4987. if (!strm.wait_writable()) {
  4988. error = Error::Write;
  4989. return false;
  4990. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  4991. error = Error::Canceled;
  4992. return false;
  4993. } else if (!ok) {
  4994. error = Error::Write;
  4995. return false;
  4996. }
  4997. }
  4998. error = Error::Success;
  4999. return true;
  5000. }
  5001. template <typename T>
  5002. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5003. size_t offset, size_t length, T is_shutting_down,
  5004. Error &error) {
  5005. return write_content_with_progress<T>(strm, content_provider, offset, length,
  5006. is_shutting_down, nullptr, error);
  5007. }
  5008. template <typename T>
  5009. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  5010. size_t offset, size_t length,
  5011. const T &is_shutting_down) {
  5012. auto error = Error::Success;
  5013. return write_content(strm, content_provider, offset, length, is_shutting_down,
  5014. error);
  5015. }
  5016. template <typename T>
  5017. inline bool
  5018. write_content_without_length(Stream &strm,
  5019. const ContentProvider &content_provider,
  5020. const T &is_shutting_down) {
  5021. size_t offset = 0;
  5022. auto data_available = true;
  5023. auto ok = true;
  5024. DataSink data_sink;
  5025. data_sink.write = [&](const char *d, size_t l) -> bool {
  5026. if (ok) {
  5027. offset += l;
  5028. if (!write_data(strm, d, l)) { ok = false; }
  5029. }
  5030. return ok;
  5031. };
  5032. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5033. data_sink.done = [&](void) { data_available = false; };
  5034. while (data_available && !is_shutting_down()) {
  5035. if (!strm.wait_writable()) {
  5036. return false;
  5037. } else if (!content_provider(offset, 0, data_sink)) {
  5038. return false;
  5039. } else if (!ok) {
  5040. return false;
  5041. }
  5042. }
  5043. return true;
  5044. }
  5045. template <typename T, typename U>
  5046. inline bool
  5047. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  5048. const T &is_shutting_down, U &compressor, Error &error) {
  5049. size_t offset = 0;
  5050. auto data_available = true;
  5051. auto ok = true;
  5052. DataSink data_sink;
  5053. data_sink.write = [&](const char *d, size_t l) -> bool {
  5054. if (ok) {
  5055. data_available = l > 0;
  5056. offset += l;
  5057. std::string payload;
  5058. if (compressor.compress(d, l, false,
  5059. [&](const char *data, size_t data_len) {
  5060. payload.append(data, data_len);
  5061. return true;
  5062. })) {
  5063. if (!payload.empty()) {
  5064. // Emit chunked response header and footer for each chunk
  5065. auto chunk =
  5066. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5067. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  5068. }
  5069. } else {
  5070. ok = false;
  5071. }
  5072. }
  5073. return ok;
  5074. };
  5075. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5076. auto done_with_trailer = [&](const Headers *trailer) {
  5077. if (!ok) { return; }
  5078. data_available = false;
  5079. std::string payload;
  5080. if (!compressor.compress(nullptr, 0, true,
  5081. [&](const char *data, size_t data_len) {
  5082. payload.append(data, data_len);
  5083. return true;
  5084. })) {
  5085. ok = false;
  5086. return;
  5087. }
  5088. if (!payload.empty()) {
  5089. // Emit chunked response header and footer for each chunk
  5090. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5091. if (!write_data(strm, chunk.data(), chunk.size())) {
  5092. ok = false;
  5093. return;
  5094. }
  5095. }
  5096. constexpr const char done_marker[] = "0\r\n";
  5097. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  5098. // Trailer
  5099. if (trailer) {
  5100. for (const auto &kv : *trailer) {
  5101. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  5102. if (!write_data(strm, field_line.data(), field_line.size())) {
  5103. ok = false;
  5104. }
  5105. }
  5106. }
  5107. constexpr const char crlf[] = "\r\n";
  5108. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  5109. };
  5110. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  5111. data_sink.done_with_trailer = [&](const Headers &trailer) {
  5112. done_with_trailer(&trailer);
  5113. };
  5114. while (data_available && !is_shutting_down()) {
  5115. if (!strm.wait_writable()) {
  5116. error = Error::Write;
  5117. return false;
  5118. } else if (!content_provider(offset, 0, data_sink)) {
  5119. error = Error::Canceled;
  5120. return false;
  5121. } else if (!ok) {
  5122. error = Error::Write;
  5123. return false;
  5124. }
  5125. }
  5126. error = Error::Success;
  5127. return true;
  5128. }
  5129. template <typename T, typename U>
  5130. inline bool write_content_chunked(Stream &strm,
  5131. const ContentProvider &content_provider,
  5132. const T &is_shutting_down, U &compressor) {
  5133. auto error = Error::Success;
  5134. return write_content_chunked(strm, content_provider, is_shutting_down,
  5135. compressor, error);
  5136. }
  5137. template <typename T>
  5138. inline bool redirect(T &cli, Request &req, Response &res,
  5139. const std::string &path, const std::string &location,
  5140. Error &error) {
  5141. Request new_req = req;
  5142. new_req.path = path;
  5143. new_req.redirect_count_ -= 1;
  5144. if (res.status == StatusCode::SeeOther_303 &&
  5145. (req.method != "GET" && req.method != "HEAD")) {
  5146. new_req.method = "GET";
  5147. new_req.body.clear();
  5148. new_req.headers.clear();
  5149. }
  5150. Response new_res;
  5151. auto ret = cli.send(new_req, new_res, error);
  5152. if (ret) {
  5153. req = std::move(new_req);
  5154. res = std::move(new_res);
  5155. if (res.location.empty()) { res.location = location; }
  5156. }
  5157. return ret;
  5158. }
  5159. inline std::string params_to_query_str(const Params &params) {
  5160. std::string query;
  5161. for (auto it = params.begin(); it != params.end(); ++it) {
  5162. if (it != params.begin()) { query += '&'; }
  5163. query += encode_query_component(it->first);
  5164. query += '=';
  5165. query += encode_query_component(it->second);
  5166. }
  5167. return query;
  5168. }
  5169. inline void parse_query_text(const char *data, std::size_t size,
  5170. Params &params) {
  5171. std::set<std::string> cache;
  5172. split(data, data + size, '&', [&](const char *b, const char *e) {
  5173. std::string kv(b, e);
  5174. if (cache.find(kv) != cache.end()) { return; }
  5175. cache.insert(std::move(kv));
  5176. std::string key;
  5177. std::string val;
  5178. divide(b, static_cast<std::size_t>(e - b), '=',
  5179. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  5180. std::size_t rhs_size) {
  5181. key.assign(lhs_data, lhs_size);
  5182. val.assign(rhs_data, rhs_size);
  5183. });
  5184. if (!key.empty()) {
  5185. params.emplace(decode_query_component(key), decode_query_component(val));
  5186. }
  5187. });
  5188. }
  5189. inline void parse_query_text(const std::string &s, Params &params) {
  5190. parse_query_text(s.data(), s.size(), params);
  5191. }
  5192. // Normalize a query string by decoding and re-encoding each key/value pair
  5193. // while preserving the original parameter order. This avoids double-encoding
  5194. // and ensures consistent encoding without reordering (unlike Params which
  5195. // uses std::multimap and sorts keys).
  5196. inline std::string normalize_query_string(const std::string &query) {
  5197. std::string result;
  5198. split(query.data(), query.data() + query.size(), '&',
  5199. [&](const char *b, const char *e) {
  5200. std::string key;
  5201. std::string val;
  5202. divide(b, static_cast<std::size_t>(e - b), '=',
  5203. [&](const char *lhs_data, std::size_t lhs_size,
  5204. const char *rhs_data, std::size_t rhs_size) {
  5205. key.assign(lhs_data, lhs_size);
  5206. val.assign(rhs_data, rhs_size);
  5207. });
  5208. if (!key.empty()) {
  5209. auto dec_key = decode_query_component(key);
  5210. auto dec_val = decode_query_component(val);
  5211. if (!result.empty()) { result += '&'; }
  5212. result += encode_query_component(dec_key);
  5213. if (!val.empty() || std::find(b, e, '=') != e) {
  5214. result += '=';
  5215. result += encode_query_component(dec_val);
  5216. }
  5217. }
  5218. });
  5219. return result;
  5220. }
  5221. inline bool parse_multipart_boundary(const std::string &content_type,
  5222. std::string &boundary) {
  5223. auto boundary_keyword = "boundary=";
  5224. auto pos = content_type.find(boundary_keyword);
  5225. if (pos == std::string::npos) { return false; }
  5226. auto end = content_type.find(';', pos);
  5227. auto beg = pos + strlen(boundary_keyword);
  5228. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  5229. return !boundary.empty();
  5230. }
  5231. inline void parse_disposition_params(const std::string &s, Params &params) {
  5232. std::set<std::string> cache;
  5233. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  5234. std::string kv(b, e);
  5235. if (cache.find(kv) != cache.end()) { return; }
  5236. cache.insert(kv);
  5237. std::string key;
  5238. std::string val;
  5239. split(b, e, '=', [&](const char *b2, const char *e2) {
  5240. if (key.empty()) {
  5241. key.assign(b2, e2);
  5242. } else {
  5243. val.assign(b2, e2);
  5244. }
  5245. });
  5246. if (!key.empty()) {
  5247. params.emplace(trim_double_quotes_copy((key)),
  5248. trim_double_quotes_copy((val)));
  5249. }
  5250. });
  5251. }
  5252. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5253. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  5254. #else
  5255. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  5256. #endif
  5257. auto is_valid = [](const std::string &str) {
  5258. return std::all_of(str.cbegin(), str.cend(),
  5259. [](unsigned char c) { return std::isdigit(c); });
  5260. };
  5261. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  5262. const auto pos = static_cast<size_t>(6);
  5263. const auto len = static_cast<size_t>(s.size() - 6);
  5264. auto all_valid_ranges = true;
  5265. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  5266. if (!all_valid_ranges) { return; }
  5267. const auto it = std::find(b, e, '-');
  5268. if (it == e) {
  5269. all_valid_ranges = false;
  5270. return;
  5271. }
  5272. const auto lhs = std::string(b, it);
  5273. const auto rhs = std::string(it + 1, e);
  5274. if (!is_valid(lhs) || !is_valid(rhs)) {
  5275. all_valid_ranges = false;
  5276. return;
  5277. }
  5278. ssize_t first = -1;
  5279. if (!lhs.empty()) {
  5280. ssize_t v;
  5281. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  5282. if (res.ec == std::errc{}) { first = v; }
  5283. }
  5284. ssize_t last = -1;
  5285. if (!rhs.empty()) {
  5286. ssize_t v;
  5287. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  5288. if (res.ec == std::errc{}) { last = v; }
  5289. }
  5290. if ((first == -1 && last == -1) ||
  5291. (first != -1 && last != -1 && first > last)) {
  5292. all_valid_ranges = false;
  5293. return;
  5294. }
  5295. ranges.emplace_back(first, last);
  5296. });
  5297. return all_valid_ranges && !ranges.empty();
  5298. }
  5299. return false;
  5300. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5301. }
  5302. #else
  5303. } catch (...) { return false; }
  5304. #endif
  5305. inline bool parse_accept_header(const std::string &s,
  5306. std::vector<std::string> &content_types) {
  5307. content_types.clear();
  5308. // Empty string is considered valid (no preference)
  5309. if (s.empty()) { return true; }
  5310. // Check for invalid patterns: leading/trailing commas or consecutive commas
  5311. if (s.front() == ',' || s.back() == ',' ||
  5312. s.find(",,") != std::string::npos) {
  5313. return false;
  5314. }
  5315. struct AcceptEntry {
  5316. std::string media_type;
  5317. double quality;
  5318. int order; // Original order in header
  5319. };
  5320. std::vector<AcceptEntry> entries;
  5321. int order = 0;
  5322. bool has_invalid_entry = false;
  5323. // Split by comma and parse each entry
  5324. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5325. std::string entry(b, e);
  5326. entry = trim_copy(entry);
  5327. if (entry.empty()) {
  5328. has_invalid_entry = true;
  5329. return;
  5330. }
  5331. AcceptEntry accept_entry;
  5332. accept_entry.quality = 1.0; // Default quality
  5333. accept_entry.order = order++;
  5334. // Find q= parameter
  5335. auto q_pos = entry.find(";q=");
  5336. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  5337. if (q_pos != std::string::npos) {
  5338. // Extract media type (before q parameter)
  5339. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  5340. // Extract quality value
  5341. auto q_start = entry.find('=', q_pos) + 1;
  5342. auto q_end = entry.find(';', q_start);
  5343. if (q_end == std::string::npos) { q_end = entry.length(); }
  5344. std::string quality_str =
  5345. trim_copy(entry.substr(q_start, q_end - q_start));
  5346. if (quality_str.empty()) {
  5347. has_invalid_entry = true;
  5348. return;
  5349. }
  5350. {
  5351. double v = 0.0;
  5352. auto res = detail::from_chars(
  5353. quality_str.data(), quality_str.data() + quality_str.size(), v);
  5354. if (res.ec == std::errc{}) {
  5355. accept_entry.quality = v;
  5356. } else {
  5357. has_invalid_entry = true;
  5358. return;
  5359. }
  5360. }
  5361. // Check if quality is in valid range [0.0, 1.0]
  5362. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  5363. has_invalid_entry = true;
  5364. return;
  5365. }
  5366. } else {
  5367. // No quality parameter, use entire entry as media type
  5368. accept_entry.media_type = entry;
  5369. }
  5370. // Remove additional parameters from media type
  5371. auto param_pos = accept_entry.media_type.find(';');
  5372. if (param_pos != std::string::npos) {
  5373. accept_entry.media_type =
  5374. trim_copy(accept_entry.media_type.substr(0, param_pos));
  5375. }
  5376. // Basic validation of media type format
  5377. if (accept_entry.media_type.empty()) {
  5378. has_invalid_entry = true;
  5379. return;
  5380. }
  5381. // Check for basic media type format (should contain '/' or be '*')
  5382. if (accept_entry.media_type != "*" &&
  5383. accept_entry.media_type.find('/') == std::string::npos) {
  5384. has_invalid_entry = true;
  5385. return;
  5386. }
  5387. entries.push_back(std::move(accept_entry));
  5388. });
  5389. // Return false if any invalid entry was found
  5390. if (has_invalid_entry) { return false; }
  5391. // Sort by quality (descending), then by original order (ascending)
  5392. std::sort(entries.begin(), entries.end(),
  5393. [](const AcceptEntry &a, const AcceptEntry &b) {
  5394. if (a.quality != b.quality) {
  5395. return a.quality > b.quality; // Higher quality first
  5396. }
  5397. return a.order < b.order; // Earlier order first for same quality
  5398. });
  5399. // Extract sorted media types
  5400. content_types.reserve(entries.size());
  5401. for (auto &entry : entries) {
  5402. content_types.push_back(std::move(entry.media_type));
  5403. }
  5404. return true;
  5405. }
  5406. class FormDataParser {
  5407. public:
  5408. FormDataParser() = default;
  5409. void set_boundary(std::string &&boundary) {
  5410. boundary_ = std::move(boundary);
  5411. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  5412. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  5413. }
  5414. bool is_valid() const { return is_valid_; }
  5415. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  5416. const ContentReceiver &content_callback) {
  5417. buf_append(buf, n);
  5418. while (buf_size() > 0) {
  5419. switch (state_) {
  5420. case 0: { // Initial boundary
  5421. auto pos = buf_find(dash_boundary_crlf_);
  5422. if (pos == buf_size()) { return true; }
  5423. buf_erase(pos + dash_boundary_crlf_.size());
  5424. state_ = 1;
  5425. break;
  5426. }
  5427. case 1: { // New entry
  5428. clear_file_info();
  5429. state_ = 2;
  5430. break;
  5431. }
  5432. case 2: { // Headers
  5433. auto pos = buf_find(crlf_);
  5434. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5435. while (pos < buf_size()) {
  5436. // Empty line
  5437. if (pos == 0) {
  5438. if (!header_callback(file_)) {
  5439. is_valid_ = false;
  5440. return false;
  5441. }
  5442. buf_erase(crlf_.size());
  5443. state_ = 3;
  5444. break;
  5445. }
  5446. const auto header = buf_head(pos);
  5447. if (!parse_header(header.data(), header.data() + header.size(),
  5448. [&](const std::string &, const std::string &) {})) {
  5449. is_valid_ = false;
  5450. return false;
  5451. }
  5452. // Parse and emplace space trimmed headers into a map
  5453. if (!parse_header(
  5454. header.data(), header.data() + header.size(),
  5455. [&](const std::string &key, const std::string &val) {
  5456. file_.headers.emplace(key, val);
  5457. })) {
  5458. is_valid_ = false;
  5459. return false;
  5460. }
  5461. constexpr const char header_content_type[] = "Content-Type:";
  5462. if (start_with_case_ignore(header, header_content_type)) {
  5463. file_.content_type =
  5464. trim_copy(header.substr(str_len(header_content_type)));
  5465. } else {
  5466. thread_local const std::regex re_content_disposition(
  5467. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  5468. std::regex_constants::icase);
  5469. std::smatch m;
  5470. if (std::regex_match(header, m, re_content_disposition)) {
  5471. Params params;
  5472. parse_disposition_params(m[1], params);
  5473. auto it = params.find("name");
  5474. if (it != params.end()) {
  5475. file_.name = it->second;
  5476. } else {
  5477. is_valid_ = false;
  5478. return false;
  5479. }
  5480. it = params.find("filename");
  5481. if (it != params.end()) { file_.filename = it->second; }
  5482. it = params.find("filename*");
  5483. if (it != params.end()) {
  5484. // Only allow UTF-8 encoding...
  5485. thread_local const std::regex re_rfc5987_encoding(
  5486. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  5487. std::smatch m2;
  5488. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  5489. file_.filename = decode_path_component(m2[1]); // override...
  5490. } else {
  5491. is_valid_ = false;
  5492. return false;
  5493. }
  5494. }
  5495. }
  5496. }
  5497. buf_erase(pos + crlf_.size());
  5498. pos = buf_find(crlf_);
  5499. }
  5500. if (state_ != 3) { return true; }
  5501. break;
  5502. }
  5503. case 3: { // Body
  5504. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  5505. auto pos = buf_find(crlf_dash_boundary_);
  5506. if (pos < buf_size()) {
  5507. if (!content_callback(buf_data(), pos)) {
  5508. is_valid_ = false;
  5509. return false;
  5510. }
  5511. buf_erase(pos + crlf_dash_boundary_.size());
  5512. state_ = 4;
  5513. } else {
  5514. auto len = buf_size() - crlf_dash_boundary_.size();
  5515. if (len > 0) {
  5516. if (!content_callback(buf_data(), len)) {
  5517. is_valid_ = false;
  5518. return false;
  5519. }
  5520. buf_erase(len);
  5521. }
  5522. return true;
  5523. }
  5524. break;
  5525. }
  5526. case 4: { // Boundary
  5527. if (crlf_.size() > buf_size()) { return true; }
  5528. if (buf_start_with(crlf_)) {
  5529. buf_erase(crlf_.size());
  5530. state_ = 1;
  5531. } else {
  5532. if (dash_.size() > buf_size()) { return true; }
  5533. if (buf_start_with(dash_)) {
  5534. buf_erase(dash_.size());
  5535. is_valid_ = true;
  5536. buf_erase(buf_size()); // Remove epilogue
  5537. } else {
  5538. return true;
  5539. }
  5540. }
  5541. break;
  5542. }
  5543. }
  5544. }
  5545. return true;
  5546. }
  5547. private:
  5548. void clear_file_info() {
  5549. file_.name.clear();
  5550. file_.filename.clear();
  5551. file_.content_type.clear();
  5552. file_.headers.clear();
  5553. }
  5554. bool start_with_case_ignore(const std::string &a, const char *b) const {
  5555. const auto b_len = strlen(b);
  5556. if (a.size() < b_len) { return false; }
  5557. for (size_t i = 0; i < b_len; i++) {
  5558. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  5559. return false;
  5560. }
  5561. }
  5562. return true;
  5563. }
  5564. const std::string dash_ = "--";
  5565. const std::string crlf_ = "\r\n";
  5566. std::string boundary_;
  5567. std::string dash_boundary_crlf_;
  5568. std::string crlf_dash_boundary_;
  5569. size_t state_ = 0;
  5570. bool is_valid_ = false;
  5571. FormData file_;
  5572. // Buffer
  5573. bool start_with(const std::string &a, size_t spos, size_t epos,
  5574. const std::string &b) const {
  5575. if (epos - spos < b.size()) { return false; }
  5576. for (size_t i = 0; i < b.size(); i++) {
  5577. if (a[i + spos] != b[i]) { return false; }
  5578. }
  5579. return true;
  5580. }
  5581. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  5582. const char *buf_data() const { return &buf_[buf_spos_]; }
  5583. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  5584. bool buf_start_with(const std::string &s) const {
  5585. return start_with(buf_, buf_spos_, buf_epos_, s);
  5586. }
  5587. size_t buf_find(const std::string &s) const {
  5588. auto c = s.front();
  5589. size_t off = buf_spos_;
  5590. while (off < buf_epos_) {
  5591. auto pos = off;
  5592. while (true) {
  5593. if (pos == buf_epos_) { return buf_size(); }
  5594. if (buf_[pos] == c) { break; }
  5595. pos++;
  5596. }
  5597. auto remaining_size = buf_epos_ - pos;
  5598. if (s.size() > remaining_size) { return buf_size(); }
  5599. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  5600. off = pos + 1;
  5601. }
  5602. return buf_size();
  5603. }
  5604. void buf_append(const char *data, size_t n) {
  5605. auto remaining_size = buf_size();
  5606. if (remaining_size > 0 && buf_spos_ > 0) {
  5607. for (size_t i = 0; i < remaining_size; i++) {
  5608. buf_[i] = buf_[buf_spos_ + i];
  5609. }
  5610. }
  5611. buf_spos_ = 0;
  5612. buf_epos_ = remaining_size;
  5613. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  5614. for (size_t i = 0; i < n; i++) {
  5615. buf_[buf_epos_ + i] = data[i];
  5616. }
  5617. buf_epos_ += n;
  5618. }
  5619. void buf_erase(size_t size) { buf_spos_ += size; }
  5620. std::string buf_;
  5621. size_t buf_spos_ = 0;
  5622. size_t buf_epos_ = 0;
  5623. };
  5624. inline std::string random_string(size_t length) {
  5625. constexpr const char data[] =
  5626. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  5627. thread_local auto engine([]() {
  5628. // std::random_device might actually be deterministic on some
  5629. // platforms, but due to lack of support in the c++ standard library,
  5630. // doing better requires either some ugly hacks or breaking portability.
  5631. std::random_device seed_gen;
  5632. // Request 128 bits of entropy for initialization
  5633. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  5634. return std::mt19937(seed_sequence);
  5635. }());
  5636. std::string result;
  5637. for (size_t i = 0; i < length; i++) {
  5638. result += data[engine() % (sizeof(data) - 1)];
  5639. }
  5640. return result;
  5641. }
  5642. inline std::string make_multipart_data_boundary() {
  5643. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  5644. }
  5645. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  5646. auto valid = true;
  5647. for (size_t i = 0; i < boundary.size(); i++) {
  5648. auto c = boundary[i];
  5649. if (!std::isalnum(c) && c != '-' && c != '_') {
  5650. valid = false;
  5651. break;
  5652. }
  5653. }
  5654. return valid;
  5655. }
  5656. template <typename T>
  5657. inline std::string
  5658. serialize_multipart_formdata_item_begin(const T &item,
  5659. const std::string &boundary) {
  5660. std::string body = "--" + boundary + "\r\n";
  5661. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5662. if (!item.filename.empty()) {
  5663. body += "; filename=\"" + item.filename + "\"";
  5664. }
  5665. body += "\r\n";
  5666. if (!item.content_type.empty()) {
  5667. body += "Content-Type: " + item.content_type + "\r\n";
  5668. }
  5669. body += "\r\n";
  5670. return body;
  5671. }
  5672. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  5673. inline std::string
  5674. serialize_multipart_formdata_finish(const std::string &boundary) {
  5675. return "--" + boundary + "--\r\n";
  5676. }
  5677. inline std::string
  5678. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  5679. return "multipart/form-data; boundary=" + boundary;
  5680. }
  5681. inline std::string
  5682. serialize_multipart_formdata(const UploadFormDataItems &items,
  5683. const std::string &boundary, bool finish = true) {
  5684. std::string body;
  5685. for (const auto &item : items) {
  5686. body += serialize_multipart_formdata_item_begin(item, boundary);
  5687. body += item.content + serialize_multipart_formdata_item_end();
  5688. }
  5689. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  5690. return body;
  5691. }
  5692. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  5693. if (ranges.size() <= 1) return;
  5694. // Sort ranges by start position
  5695. std::sort(ranges.begin(), ranges.end(),
  5696. [](const Range &a, const Range &b) { return a.first < b.first; });
  5697. Ranges coalesced;
  5698. coalesced.reserve(ranges.size());
  5699. for (auto &r : ranges) {
  5700. auto first_pos = r.first;
  5701. auto last_pos = r.second;
  5702. // Handle special cases like in range_error
  5703. if (first_pos == -1 && last_pos == -1) {
  5704. first_pos = 0;
  5705. last_pos = static_cast<ssize_t>(content_length);
  5706. }
  5707. if (first_pos == -1) {
  5708. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  5709. last_pos = static_cast<ssize_t>(content_length) - 1;
  5710. }
  5711. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  5712. last_pos = static_cast<ssize_t>(content_length) - 1;
  5713. }
  5714. // Skip invalid ranges
  5715. if (!(0 <= first_pos && first_pos <= last_pos &&
  5716. last_pos < static_cast<ssize_t>(content_length))) {
  5717. continue;
  5718. }
  5719. // Coalesce with previous range if overlapping or adjacent (but not
  5720. // identical)
  5721. if (!coalesced.empty()) {
  5722. auto &prev = coalesced.back();
  5723. // Check if current range overlaps or is adjacent to previous range
  5724. // but don't coalesce identical ranges (allow duplicates)
  5725. if (first_pos <= prev.second + 1 &&
  5726. !(first_pos == prev.first && last_pos == prev.second)) {
  5727. // Extend the previous range
  5728. prev.second = (std::max)(prev.second, last_pos);
  5729. continue;
  5730. }
  5731. }
  5732. // Add new range
  5733. coalesced.emplace_back(first_pos, last_pos);
  5734. }
  5735. ranges = std::move(coalesced);
  5736. }
  5737. inline bool range_error(Request &req, Response &res) {
  5738. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  5739. ssize_t content_len = static_cast<ssize_t>(
  5740. res.content_length_ ? res.content_length_ : res.body.size());
  5741. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  5742. size_t overwrapping_count = 0;
  5743. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  5744. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  5745. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  5746. // Too many ranges
  5747. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  5748. for (auto &r : req.ranges) {
  5749. auto &first_pos = r.first;
  5750. auto &last_pos = r.second;
  5751. if (first_pos == -1 && last_pos == -1) {
  5752. first_pos = 0;
  5753. last_pos = content_len;
  5754. }
  5755. if (first_pos == -1) {
  5756. first_pos = content_len - last_pos;
  5757. last_pos = content_len - 1;
  5758. }
  5759. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  5760. // A client can limit the number of bytes requested without knowing the
  5761. // size of the selected representation. If the last-pos value is absent,
  5762. // or if the value is greater than or equal to the current length of the
  5763. // representation data, the byte range is interpreted as the remainder of
  5764. // the representation (i.e., the server replaces the value of last-pos
  5765. // with a value that is one less than the current length of the selected
  5766. // representation).
  5767. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  5768. if (last_pos == -1 || last_pos >= content_len) {
  5769. last_pos = content_len - 1;
  5770. }
  5771. // Range must be within content length
  5772. if (!(0 <= first_pos && first_pos <= last_pos &&
  5773. last_pos <= content_len - 1)) {
  5774. return true;
  5775. }
  5776. // Request must not have more than two overlapping ranges
  5777. for (const auto &processed_range : processed_ranges) {
  5778. if (!(last_pos < processed_range.first ||
  5779. first_pos > processed_range.second)) {
  5780. overwrapping_count++;
  5781. if (overwrapping_count > 2) { return true; }
  5782. break; // Only count once per range
  5783. }
  5784. }
  5785. processed_ranges.emplace_back(first_pos, last_pos);
  5786. }
  5787. // After validation, coalesce overlapping ranges as per RFC 9110
  5788. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  5789. }
  5790. return false;
  5791. }
  5792. inline std::pair<size_t, size_t>
  5793. get_range_offset_and_length(Range r, size_t content_length) {
  5794. assert(r.first != -1 && r.second != -1);
  5795. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  5796. assert(r.first <= r.second &&
  5797. r.second < static_cast<ssize_t>(content_length));
  5798. (void)(content_length);
  5799. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  5800. }
  5801. inline std::string make_content_range_header_field(
  5802. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  5803. auto st = offset_and_length.first;
  5804. auto ed = st + offset_and_length.second - 1;
  5805. std::string field = "bytes ";
  5806. field += std::to_string(st);
  5807. field += '-';
  5808. field += std::to_string(ed);
  5809. field += '/';
  5810. field += std::to_string(content_length);
  5811. return field;
  5812. }
  5813. template <typename SToken, typename CToken, typename Content>
  5814. bool process_multipart_ranges_data(const Request &req,
  5815. const std::string &boundary,
  5816. const std::string &content_type,
  5817. size_t content_length, SToken stoken,
  5818. CToken ctoken, Content content) {
  5819. for (size_t i = 0; i < req.ranges.size(); i++) {
  5820. ctoken("--");
  5821. stoken(boundary);
  5822. ctoken("\r\n");
  5823. if (!content_type.empty()) {
  5824. ctoken("Content-Type: ");
  5825. stoken(content_type);
  5826. ctoken("\r\n");
  5827. }
  5828. auto offset_and_length =
  5829. get_range_offset_and_length(req.ranges[i], content_length);
  5830. ctoken("Content-Range: ");
  5831. stoken(make_content_range_header_field(offset_and_length, content_length));
  5832. ctoken("\r\n");
  5833. ctoken("\r\n");
  5834. if (!content(offset_and_length.first, offset_and_length.second)) {
  5835. return false;
  5836. }
  5837. ctoken("\r\n");
  5838. }
  5839. ctoken("--");
  5840. stoken(boundary);
  5841. ctoken("--");
  5842. return true;
  5843. }
  5844. inline void make_multipart_ranges_data(const Request &req, Response &res,
  5845. const std::string &boundary,
  5846. const std::string &content_type,
  5847. size_t content_length,
  5848. std::string &data) {
  5849. process_multipart_ranges_data(
  5850. req, boundary, content_type, content_length,
  5851. [&](const std::string &token) { data += token; },
  5852. [&](const std::string &token) { data += token; },
  5853. [&](size_t offset, size_t length) {
  5854. assert(offset + length <= content_length);
  5855. data += res.body.substr(offset, length);
  5856. return true;
  5857. });
  5858. }
  5859. inline size_t get_multipart_ranges_data_length(const Request &req,
  5860. const std::string &boundary,
  5861. const std::string &content_type,
  5862. size_t content_length) {
  5863. size_t data_length = 0;
  5864. process_multipart_ranges_data(
  5865. req, boundary, content_type, content_length,
  5866. [&](const std::string &token) { data_length += token.size(); },
  5867. [&](const std::string &token) { data_length += token.size(); },
  5868. [&](size_t /*offset*/, size_t length) {
  5869. data_length += length;
  5870. return true;
  5871. });
  5872. return data_length;
  5873. }
  5874. template <typename T>
  5875. inline bool
  5876. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  5877. const std::string &boundary,
  5878. const std::string &content_type,
  5879. size_t content_length, const T &is_shutting_down) {
  5880. return process_multipart_ranges_data(
  5881. req, boundary, content_type, content_length,
  5882. [&](const std::string &token) { strm.write(token); },
  5883. [&](const std::string &token) { strm.write(token); },
  5884. [&](size_t offset, size_t length) {
  5885. return write_content(strm, res.content_provider_, offset, length,
  5886. is_shutting_down);
  5887. });
  5888. }
  5889. inline bool expect_content(const Request &req) {
  5890. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  5891. req.method == "DELETE") {
  5892. return true;
  5893. }
  5894. if (req.has_header("Content-Length") &&
  5895. req.get_header_value_u64("Content-Length") > 0) {
  5896. return true;
  5897. }
  5898. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  5899. return false;
  5900. }
  5901. inline bool has_crlf(const std::string &s) {
  5902. auto p = s.c_str();
  5903. while (*p) {
  5904. if (*p == '\r' || *p == '\n') { return true; }
  5905. p++;
  5906. }
  5907. return false;
  5908. }
  5909. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5910. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  5911. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  5912. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  5913. unsigned int hash_length = 0;
  5914. unsigned char hash[EVP_MAX_MD_SIZE];
  5915. EVP_DigestInit_ex(context.get(), algo, nullptr);
  5916. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  5917. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  5918. std::stringstream ss;
  5919. for (auto i = 0u; i < hash_length; ++i) {
  5920. ss << std::hex << std::setw(2) << std::setfill('0')
  5921. << static_cast<unsigned int>(hash[i]);
  5922. }
  5923. return ss.str();
  5924. }
  5925. inline std::string MD5(const std::string &s) {
  5926. return message_digest(s, EVP_md5());
  5927. }
  5928. inline std::string SHA_256(const std::string &s) {
  5929. return message_digest(s, EVP_sha256());
  5930. }
  5931. inline std::string SHA_512(const std::string &s) {
  5932. return message_digest(s, EVP_sha512());
  5933. }
  5934. inline std::pair<std::string, std::string> make_digest_authentication_header(
  5935. const Request &req, const std::map<std::string, std::string> &auth,
  5936. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  5937. const std::string &password, bool is_proxy = false) {
  5938. std::string nc;
  5939. {
  5940. std::stringstream ss;
  5941. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  5942. nc = ss.str();
  5943. }
  5944. std::string qop;
  5945. if (auth.find("qop") != auth.end()) {
  5946. qop = auth.at("qop");
  5947. if (qop.find("auth-int") != std::string::npos) {
  5948. qop = "auth-int";
  5949. } else if (qop.find("auth") != std::string::npos) {
  5950. qop = "auth";
  5951. } else {
  5952. qop.clear();
  5953. }
  5954. }
  5955. std::string algo = "MD5";
  5956. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  5957. std::string response;
  5958. {
  5959. auto H = algo == "SHA-256" ? detail::SHA_256
  5960. : algo == "SHA-512" ? detail::SHA_512
  5961. : detail::MD5;
  5962. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  5963. auto A2 = req.method + ":" + req.path;
  5964. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  5965. if (qop.empty()) {
  5966. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  5967. } else {
  5968. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  5969. ":" + qop + ":" + H(A2));
  5970. }
  5971. }
  5972. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  5973. auto field = "Digest username=\"" + username + "\", realm=\"" +
  5974. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  5975. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  5976. (qop.empty() ? ", response=\""
  5977. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  5978. cnonce + "\", response=\"") +
  5979. response + "\"" +
  5980. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  5981. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5982. return std::make_pair(key, field);
  5983. }
  5984. inline bool is_ssl_peer_could_be_closed(SSL *ssl, socket_t sock) {
  5985. detail::set_nonblocking(sock, true);
  5986. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  5987. char buf[1];
  5988. return !SSL_peek(ssl, buf, 1) &&
  5989. SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
  5990. }
  5991. #ifdef _WIN32
  5992. // NOTE: This code came up with the following stackoverflow post:
  5993. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  5994. inline bool load_system_certs_on_windows(X509_STORE *store) {
  5995. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  5996. if (!hStore) { return false; }
  5997. auto result = false;
  5998. PCCERT_CONTEXT pContext = NULL;
  5999. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  6000. nullptr) {
  6001. auto encoded_cert =
  6002. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  6003. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  6004. if (x509) {
  6005. X509_STORE_add_cert(store, x509);
  6006. X509_free(x509);
  6007. result = true;
  6008. }
  6009. }
  6010. CertFreeCertificateContext(pContext);
  6011. CertCloseStore(hStore, 0);
  6012. return result;
  6013. }
  6014. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  6015. template <typename T>
  6016. using CFObjectPtr =
  6017. std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
  6018. inline void cf_object_ptr_deleter(CFTypeRef obj) {
  6019. if (obj) { CFRelease(obj); }
  6020. }
  6021. inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  6022. CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
  6023. CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,
  6024. kCFBooleanTrue};
  6025. CFObjectPtr<CFDictionaryRef> query(
  6026. CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,
  6027. sizeof(keys) / sizeof(keys[0]),
  6028. &kCFTypeDictionaryKeyCallBacks,
  6029. &kCFTypeDictionaryValueCallBacks),
  6030. cf_object_ptr_deleter);
  6031. if (!query) { return false; }
  6032. CFTypeRef security_items = nullptr;
  6033. if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
  6034. CFArrayGetTypeID() != CFGetTypeID(security_items)) {
  6035. return false;
  6036. }
  6037. certs.reset(reinterpret_cast<CFArrayRef>(security_items));
  6038. return true;
  6039. }
  6040. inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  6041. CFArrayRef root_security_items = nullptr;
  6042. if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
  6043. return false;
  6044. }
  6045. certs.reset(root_security_items);
  6046. return true;
  6047. }
  6048. inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
  6049. auto result = false;
  6050. for (auto i = 0; i < CFArrayGetCount(certs); ++i) {
  6051. const auto cert = reinterpret_cast<const __SecCertificate *>(
  6052. CFArrayGetValueAtIndex(certs, i));
  6053. if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }
  6054. CFDataRef cert_data = nullptr;
  6055. if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=
  6056. errSecSuccess) {
  6057. continue;
  6058. }
  6059. CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
  6060. auto encoded_cert = static_cast<const unsigned char *>(
  6061. CFDataGetBytePtr(cert_data_ptr.get()));
  6062. auto x509 =
  6063. d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
  6064. if (x509) {
  6065. X509_STORE_add_cert(store, x509);
  6066. X509_free(x509);
  6067. result = true;
  6068. }
  6069. }
  6070. return result;
  6071. }
  6072. inline bool load_system_certs_on_macos(X509_STORE *store) {
  6073. auto result = false;
  6074. CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);
  6075. if (retrieve_certs_from_keychain(certs) && certs) {
  6076. result = add_certs_to_x509_store(certs.get(), store);
  6077. }
  6078. if (retrieve_root_certs_from_keychain(certs) && certs) {
  6079. result = add_certs_to_x509_store(certs.get(), store) || result;
  6080. }
  6081. return result;
  6082. }
  6083. #endif // _WIN32
  6084. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  6085. #ifdef _WIN32
  6086. class WSInit {
  6087. public:
  6088. WSInit() {
  6089. WSADATA wsaData;
  6090. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  6091. }
  6092. ~WSInit() {
  6093. if (is_valid_) WSACleanup();
  6094. }
  6095. bool is_valid_ = false;
  6096. };
  6097. static WSInit wsinit_;
  6098. #endif
  6099. inline bool parse_www_authenticate(const Response &res,
  6100. std::map<std::string, std::string> &auth,
  6101. bool is_proxy) {
  6102. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  6103. if (res.has_header(auth_key)) {
  6104. thread_local auto re =
  6105. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  6106. auto s = res.get_header_value(auth_key);
  6107. auto pos = s.find(' ');
  6108. if (pos != std::string::npos) {
  6109. auto type = s.substr(0, pos);
  6110. if (type == "Basic") {
  6111. return false;
  6112. } else if (type == "Digest") {
  6113. s = s.substr(pos + 1);
  6114. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  6115. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  6116. const auto &m = *i;
  6117. auto key = s.substr(static_cast<size_t>(m.position(1)),
  6118. static_cast<size_t>(m.length(1)));
  6119. auto val = m.length(2) > 0
  6120. ? s.substr(static_cast<size_t>(m.position(2)),
  6121. static_cast<size_t>(m.length(2)))
  6122. : s.substr(static_cast<size_t>(m.position(3)),
  6123. static_cast<size_t>(m.length(3)));
  6124. auth[std::move(key)] = std::move(val);
  6125. }
  6126. return true;
  6127. }
  6128. }
  6129. }
  6130. return false;
  6131. }
  6132. class ContentProviderAdapter {
  6133. public:
  6134. explicit ContentProviderAdapter(
  6135. ContentProviderWithoutLength &&content_provider)
  6136. : content_provider_(std::move(content_provider)) {}
  6137. bool operator()(size_t offset, size_t, DataSink &sink) {
  6138. return content_provider_(offset, sink);
  6139. }
  6140. private:
  6141. ContentProviderWithoutLength content_provider_;
  6142. };
  6143. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  6144. namespace fields {
  6145. inline bool is_token_char(char c) {
  6146. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  6147. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  6148. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  6149. }
  6150. inline bool is_token(const std::string &s) {
  6151. if (s.empty()) { return false; }
  6152. for (auto c : s) {
  6153. if (!is_token_char(c)) { return false; }
  6154. }
  6155. return true;
  6156. }
  6157. inline bool is_field_name(const std::string &s) { return is_token(s); }
  6158. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  6159. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  6160. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  6161. inline bool is_field_content(const std::string &s) {
  6162. if (s.empty()) { return true; }
  6163. if (s.size() == 1) {
  6164. return is_field_vchar(s[0]);
  6165. } else if (s.size() == 2) {
  6166. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  6167. } else {
  6168. size_t i = 0;
  6169. if (!is_field_vchar(s[i])) { return false; }
  6170. i++;
  6171. while (i < s.size() - 1) {
  6172. auto c = s[i++];
  6173. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  6174. } else {
  6175. return false;
  6176. }
  6177. }
  6178. return is_field_vchar(s[i]);
  6179. }
  6180. }
  6181. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  6182. } // namespace fields
  6183. } // namespace detail
  6184. inline const char *status_message(int status) {
  6185. switch (status) {
  6186. case StatusCode::Continue_100: return "Continue";
  6187. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  6188. case StatusCode::Processing_102: return "Processing";
  6189. case StatusCode::EarlyHints_103: return "Early Hints";
  6190. case StatusCode::OK_200: return "OK";
  6191. case StatusCode::Created_201: return "Created";
  6192. case StatusCode::Accepted_202: return "Accepted";
  6193. case StatusCode::NonAuthoritativeInformation_203:
  6194. return "Non-Authoritative Information";
  6195. case StatusCode::NoContent_204: return "No Content";
  6196. case StatusCode::ResetContent_205: return "Reset Content";
  6197. case StatusCode::PartialContent_206: return "Partial Content";
  6198. case StatusCode::MultiStatus_207: return "Multi-Status";
  6199. case StatusCode::AlreadyReported_208: return "Already Reported";
  6200. case StatusCode::IMUsed_226: return "IM Used";
  6201. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  6202. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  6203. case StatusCode::Found_302: return "Found";
  6204. case StatusCode::SeeOther_303: return "See Other";
  6205. case StatusCode::NotModified_304: return "Not Modified";
  6206. case StatusCode::UseProxy_305: return "Use Proxy";
  6207. case StatusCode::unused_306: return "unused";
  6208. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  6209. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  6210. case StatusCode::BadRequest_400: return "Bad Request";
  6211. case StatusCode::Unauthorized_401: return "Unauthorized";
  6212. case StatusCode::PaymentRequired_402: return "Payment Required";
  6213. case StatusCode::Forbidden_403: return "Forbidden";
  6214. case StatusCode::NotFound_404: return "Not Found";
  6215. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  6216. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  6217. case StatusCode::ProxyAuthenticationRequired_407:
  6218. return "Proxy Authentication Required";
  6219. case StatusCode::RequestTimeout_408: return "Request Timeout";
  6220. case StatusCode::Conflict_409: return "Conflict";
  6221. case StatusCode::Gone_410: return "Gone";
  6222. case StatusCode::LengthRequired_411: return "Length Required";
  6223. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  6224. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  6225. case StatusCode::UriTooLong_414: return "URI Too Long";
  6226. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  6227. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  6228. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  6229. case StatusCode::ImATeapot_418: return "I'm a teapot";
  6230. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  6231. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  6232. case StatusCode::Locked_423: return "Locked";
  6233. case StatusCode::FailedDependency_424: return "Failed Dependency";
  6234. case StatusCode::TooEarly_425: return "Too Early";
  6235. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  6236. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  6237. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  6238. case StatusCode::RequestHeaderFieldsTooLarge_431:
  6239. return "Request Header Fields Too Large";
  6240. case StatusCode::UnavailableForLegalReasons_451:
  6241. return "Unavailable For Legal Reasons";
  6242. case StatusCode::NotImplemented_501: return "Not Implemented";
  6243. case StatusCode::BadGateway_502: return "Bad Gateway";
  6244. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  6245. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  6246. case StatusCode::HttpVersionNotSupported_505:
  6247. return "HTTP Version Not Supported";
  6248. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  6249. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  6250. case StatusCode::LoopDetected_508: return "Loop Detected";
  6251. case StatusCode::NotExtended_510: return "Not Extended";
  6252. case StatusCode::NetworkAuthenticationRequired_511:
  6253. return "Network Authentication Required";
  6254. default:
  6255. case StatusCode::InternalServerError_500: return "Internal Server Error";
  6256. }
  6257. }
  6258. inline std::string to_string(const Error error) {
  6259. switch (error) {
  6260. case Error::Success: return "Success (no error)";
  6261. case Error::Unknown: return "Unknown";
  6262. case Error::Connection: return "Could not establish connection";
  6263. case Error::BindIPAddress: return "Failed to bind IP address";
  6264. case Error::Read: return "Failed to read connection";
  6265. case Error::Write: return "Failed to write connection";
  6266. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  6267. case Error::Canceled: return "Connection handling canceled";
  6268. case Error::SSLConnection: return "SSL connection failed";
  6269. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  6270. case Error::SSLServerVerification: return "SSL server verification failed";
  6271. case Error::SSLServerHostnameVerification:
  6272. return "SSL server hostname verification failed";
  6273. case Error::UnsupportedMultipartBoundaryChars:
  6274. return "Unsupported HTTP multipart boundary characters";
  6275. case Error::Compression: return "Compression failed";
  6276. case Error::ConnectionTimeout: return "Connection timed out";
  6277. case Error::ProxyConnection: return "Proxy connection failed";
  6278. case Error::ConnectionClosed: return "Connection closed by server";
  6279. case Error::Timeout: return "Read timeout";
  6280. case Error::ResourceExhaustion: return "Resource exhaustion";
  6281. case Error::TooManyFormDataFiles: return "Too many form data files";
  6282. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  6283. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  6284. case Error::ExceedMaxSocketDescriptorCount:
  6285. return "Exceeded maximum socket descriptor count";
  6286. case Error::InvalidRequestLine: return "Invalid request line";
  6287. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  6288. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  6289. case Error::InvalidHeaders: return "Invalid headers";
  6290. case Error::MultipartParsing: return "Multipart parsing failed";
  6291. case Error::OpenFile: return "Failed to open file";
  6292. case Error::Listen: return "Failed to listen on socket";
  6293. case Error::GetSockName: return "Failed to get socket name";
  6294. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  6295. case Error::HTTPParsing: return "HTTP parsing failed";
  6296. case Error::InvalidRangeHeader: return "Invalid Range header";
  6297. default: break;
  6298. }
  6299. return "Invalid";
  6300. }
  6301. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  6302. os << to_string(obj);
  6303. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  6304. return os;
  6305. }
  6306. inline std::string hosted_at(const std::string &hostname) {
  6307. std::vector<std::string> addrs;
  6308. hosted_at(hostname, addrs);
  6309. if (addrs.empty()) { return std::string(); }
  6310. return addrs[0];
  6311. }
  6312. inline void hosted_at(const std::string &hostname,
  6313. std::vector<std::string> &addrs) {
  6314. struct addrinfo hints;
  6315. struct addrinfo *result;
  6316. memset(&hints, 0, sizeof(struct addrinfo));
  6317. hints.ai_family = AF_UNSPEC;
  6318. hints.ai_socktype = SOCK_STREAM;
  6319. hints.ai_protocol = 0;
  6320. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  6321. &result, 0)) {
  6322. #if defined __linux__ && !defined __ANDROID__
  6323. res_init();
  6324. #endif
  6325. return;
  6326. }
  6327. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6328. for (auto rp = result; rp; rp = rp->ai_next) {
  6329. const auto &addr =
  6330. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  6331. std::string ip;
  6332. auto dummy = -1;
  6333. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  6334. dummy)) {
  6335. addrs.emplace_back(std::move(ip));
  6336. }
  6337. }
  6338. }
  6339. inline std::string encode_uri_component(const std::string &value) {
  6340. std::ostringstream escaped;
  6341. escaped.fill('0');
  6342. escaped << std::hex;
  6343. for (auto c : value) {
  6344. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6345. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6346. c == ')') {
  6347. escaped << c;
  6348. } else {
  6349. escaped << std::uppercase;
  6350. escaped << '%' << std::setw(2)
  6351. << static_cast<int>(static_cast<unsigned char>(c));
  6352. escaped << std::nouppercase;
  6353. }
  6354. }
  6355. return escaped.str();
  6356. }
  6357. inline std::string encode_uri(const std::string &value) {
  6358. std::ostringstream escaped;
  6359. escaped.fill('0');
  6360. escaped << std::hex;
  6361. for (auto c : value) {
  6362. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6363. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6364. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  6365. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  6366. escaped << c;
  6367. } else {
  6368. escaped << std::uppercase;
  6369. escaped << '%' << std::setw(2)
  6370. << static_cast<int>(static_cast<unsigned char>(c));
  6371. escaped << std::nouppercase;
  6372. }
  6373. }
  6374. return escaped.str();
  6375. }
  6376. inline std::string decode_uri_component(const std::string &value) {
  6377. std::string result;
  6378. for (size_t i = 0; i < value.size(); i++) {
  6379. if (value[i] == '%' && i + 2 < value.size()) {
  6380. auto val = 0;
  6381. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6382. result += static_cast<char>(val);
  6383. i += 2;
  6384. } else {
  6385. result += value[i];
  6386. }
  6387. } else {
  6388. result += value[i];
  6389. }
  6390. }
  6391. return result;
  6392. }
  6393. inline std::string decode_uri(const std::string &value) {
  6394. std::string result;
  6395. for (size_t i = 0; i < value.size(); i++) {
  6396. if (value[i] == '%' && i + 2 < value.size()) {
  6397. auto val = 0;
  6398. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6399. result += static_cast<char>(val);
  6400. i += 2;
  6401. } else {
  6402. result += value[i];
  6403. }
  6404. } else {
  6405. result += value[i];
  6406. }
  6407. }
  6408. return result;
  6409. }
  6410. inline std::string encode_path_component(const std::string &component) {
  6411. std::string result;
  6412. result.reserve(component.size() * 3);
  6413. for (size_t i = 0; i < component.size(); i++) {
  6414. auto c = static_cast<unsigned char>(component[i]);
  6415. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  6416. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6417. result += static_cast<char>(c);
  6418. }
  6419. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  6420. // "," / ";" / "="
  6421. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  6422. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  6423. c == '=') {
  6424. result += static_cast<char>(c);
  6425. }
  6426. // Colon is allowed in path segments except first segment
  6427. else if (c == ':') {
  6428. result += static_cast<char>(c);
  6429. }
  6430. // @ is allowed in path
  6431. else if (c == '@') {
  6432. result += static_cast<char>(c);
  6433. } else {
  6434. result += '%';
  6435. char hex[3];
  6436. snprintf(hex, sizeof(hex), "%02X", c);
  6437. result.append(hex, 2);
  6438. }
  6439. }
  6440. return result;
  6441. }
  6442. inline std::string decode_path_component(const std::string &component) {
  6443. std::string result;
  6444. result.reserve(component.size());
  6445. for (size_t i = 0; i < component.size(); i++) {
  6446. if (component[i] == '%' && i + 1 < component.size()) {
  6447. if (component[i + 1] == 'u') {
  6448. // Unicode %uXXXX encoding
  6449. auto val = 0;
  6450. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  6451. // 4 digits Unicode codes
  6452. char buff[4];
  6453. size_t len = detail::to_utf8(val, buff);
  6454. if (len > 0) { result.append(buff, len); }
  6455. i += 5; // 'u0000'
  6456. } else {
  6457. result += component[i];
  6458. }
  6459. } else {
  6460. // Standard %XX encoding
  6461. auto val = 0;
  6462. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  6463. // 2 digits hex codes
  6464. result += static_cast<char>(val);
  6465. i += 2; // 'XX'
  6466. } else {
  6467. result += component[i];
  6468. }
  6469. }
  6470. } else {
  6471. result += component[i];
  6472. }
  6473. }
  6474. return result;
  6475. }
  6476. inline std::string encode_query_component(const std::string &component,
  6477. bool space_as_plus) {
  6478. std::string result;
  6479. result.reserve(component.size() * 3);
  6480. for (size_t i = 0; i < component.size(); i++) {
  6481. auto c = static_cast<unsigned char>(component[i]);
  6482. // Unreserved characters per RFC 3986
  6483. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6484. result += static_cast<char>(c);
  6485. }
  6486. // Space handling
  6487. else if (c == ' ') {
  6488. if (space_as_plus) {
  6489. result += '+';
  6490. } else {
  6491. result += "%20";
  6492. }
  6493. }
  6494. // Plus sign handling
  6495. else if (c == '+') {
  6496. if (space_as_plus) {
  6497. result += "%2B";
  6498. } else {
  6499. result += static_cast<char>(c);
  6500. }
  6501. }
  6502. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  6503. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  6504. c == '*' || c == ',' || c == ';') {
  6505. result += static_cast<char>(c);
  6506. }
  6507. // Colon and @ are allowed in query
  6508. else if (c == ':' || c == '@') {
  6509. result += static_cast<char>(c);
  6510. }
  6511. // Forward slash is allowed in query values
  6512. else if (c == '/') {
  6513. result += static_cast<char>(c);
  6514. }
  6515. // Question mark is allowed in query values (after first ?)
  6516. else if (c == '?') {
  6517. result += static_cast<char>(c);
  6518. } else {
  6519. result += '%';
  6520. char hex[3];
  6521. snprintf(hex, sizeof(hex), "%02X", c);
  6522. result.append(hex, 2);
  6523. }
  6524. }
  6525. return result;
  6526. }
  6527. inline std::string decode_query_component(const std::string &component,
  6528. bool plus_as_space) {
  6529. std::string result;
  6530. result.reserve(component.size());
  6531. for (size_t i = 0; i < component.size(); i++) {
  6532. if (component[i] == '%' && i + 2 < component.size()) {
  6533. std::string hex = component.substr(i + 1, 2);
  6534. char *end;
  6535. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  6536. if (end == hex.c_str() + 2) {
  6537. result += static_cast<char>(value);
  6538. i += 2;
  6539. } else {
  6540. result += component[i];
  6541. }
  6542. } else if (component[i] == '+' && plus_as_space) {
  6543. result += ' '; // + becomes space in form-urlencoded
  6544. } else {
  6545. result += component[i];
  6546. }
  6547. }
  6548. return result;
  6549. }
  6550. inline std::string append_query_params(const std::string &path,
  6551. const Params &params) {
  6552. std::string path_with_query = path;
  6553. thread_local const std::regex re("[^?]+\\?.*");
  6554. auto delm = std::regex_match(path, re) ? '&' : '?';
  6555. path_with_query += delm + detail::params_to_query_str(params);
  6556. return path_with_query;
  6557. }
  6558. // Header utilities
  6559. inline std::pair<std::string, std::string>
  6560. make_range_header(const Ranges &ranges) {
  6561. std::string field = "bytes=";
  6562. auto i = 0;
  6563. for (const auto &r : ranges) {
  6564. if (i != 0) { field += ", "; }
  6565. if (r.first != -1) { field += std::to_string(r.first); }
  6566. field += '-';
  6567. if (r.second != -1) { field += std::to_string(r.second); }
  6568. i++;
  6569. }
  6570. return std::make_pair("Range", std::move(field));
  6571. }
  6572. inline std::pair<std::string, std::string>
  6573. make_basic_authentication_header(const std::string &username,
  6574. const std::string &password, bool is_proxy) {
  6575. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  6576. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6577. return std::make_pair(key, std::move(field));
  6578. }
  6579. inline std::pair<std::string, std::string>
  6580. make_bearer_token_authentication_header(const std::string &token,
  6581. bool is_proxy = false) {
  6582. auto field = "Bearer " + token;
  6583. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6584. return std::make_pair(key, std::move(field));
  6585. }
  6586. // Request implementation
  6587. inline bool Request::has_header(const std::string &key) const {
  6588. return detail::has_header(headers, key);
  6589. }
  6590. inline std::string Request::get_header_value(const std::string &key,
  6591. const char *def, size_t id) const {
  6592. return detail::get_header_value(headers, key, def, id);
  6593. }
  6594. inline size_t Request::get_header_value_count(const std::string &key) const {
  6595. auto r = headers.equal_range(key);
  6596. return static_cast<size_t>(std::distance(r.first, r.second));
  6597. }
  6598. inline void Request::set_header(const std::string &key,
  6599. const std::string &val) {
  6600. if (detail::fields::is_field_name(key) &&
  6601. detail::fields::is_field_value(val)) {
  6602. headers.emplace(key, val);
  6603. }
  6604. }
  6605. inline bool Request::has_trailer(const std::string &key) const {
  6606. return trailers.find(key) != trailers.end();
  6607. }
  6608. inline std::string Request::get_trailer_value(const std::string &key,
  6609. size_t id) const {
  6610. auto rng = trailers.equal_range(key);
  6611. auto it = rng.first;
  6612. std::advance(it, static_cast<ssize_t>(id));
  6613. if (it != rng.second) { return it->second; }
  6614. return std::string();
  6615. }
  6616. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  6617. auto r = trailers.equal_range(key);
  6618. return static_cast<size_t>(std::distance(r.first, r.second));
  6619. }
  6620. inline bool Request::has_param(const std::string &key) const {
  6621. return params.find(key) != params.end();
  6622. }
  6623. inline std::string Request::get_param_value(const std::string &key,
  6624. size_t id) const {
  6625. auto rng = params.equal_range(key);
  6626. auto it = rng.first;
  6627. std::advance(it, static_cast<ssize_t>(id));
  6628. if (it != rng.second) { return it->second; }
  6629. return std::string();
  6630. }
  6631. inline size_t Request::get_param_value_count(const std::string &key) const {
  6632. auto r = params.equal_range(key);
  6633. return static_cast<size_t>(std::distance(r.first, r.second));
  6634. }
  6635. inline bool Request::is_multipart_form_data() const {
  6636. const auto &content_type = get_header_value("Content-Type");
  6637. return !content_type.rfind("multipart/form-data", 0);
  6638. }
  6639. // Multipart FormData implementation
  6640. inline std::string MultipartFormData::get_field(const std::string &key,
  6641. size_t id) const {
  6642. auto rng = fields.equal_range(key);
  6643. auto it = rng.first;
  6644. std::advance(it, static_cast<ssize_t>(id));
  6645. if (it != rng.second) { return it->second.content; }
  6646. return std::string();
  6647. }
  6648. inline std::vector<std::string>
  6649. MultipartFormData::get_fields(const std::string &key) const {
  6650. std::vector<std::string> values;
  6651. auto rng = fields.equal_range(key);
  6652. for (auto it = rng.first; it != rng.second; it++) {
  6653. values.push_back(it->second.content);
  6654. }
  6655. return values;
  6656. }
  6657. inline bool MultipartFormData::has_field(const std::string &key) const {
  6658. return fields.find(key) != fields.end();
  6659. }
  6660. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  6661. auto r = fields.equal_range(key);
  6662. return static_cast<size_t>(std::distance(r.first, r.second));
  6663. }
  6664. inline FormData MultipartFormData::get_file(const std::string &key,
  6665. size_t id) const {
  6666. auto rng = files.equal_range(key);
  6667. auto it = rng.first;
  6668. std::advance(it, static_cast<ssize_t>(id));
  6669. if (it != rng.second) { return it->second; }
  6670. return FormData();
  6671. }
  6672. inline std::vector<FormData>
  6673. MultipartFormData::get_files(const std::string &key) const {
  6674. std::vector<FormData> values;
  6675. auto rng = files.equal_range(key);
  6676. for (auto it = rng.first; it != rng.second; it++) {
  6677. values.push_back(it->second);
  6678. }
  6679. return values;
  6680. }
  6681. inline bool MultipartFormData::has_file(const std::string &key) const {
  6682. return files.find(key) != files.end();
  6683. }
  6684. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  6685. auto r = files.equal_range(key);
  6686. return static_cast<size_t>(std::distance(r.first, r.second));
  6687. }
  6688. // Response implementation
  6689. inline bool Response::has_header(const std::string &key) const {
  6690. return headers.find(key) != headers.end();
  6691. }
  6692. inline std::string Response::get_header_value(const std::string &key,
  6693. const char *def,
  6694. size_t id) const {
  6695. return detail::get_header_value(headers, key, def, id);
  6696. }
  6697. inline size_t Response::get_header_value_count(const std::string &key) const {
  6698. auto r = headers.equal_range(key);
  6699. return static_cast<size_t>(std::distance(r.first, r.second));
  6700. }
  6701. inline void Response::set_header(const std::string &key,
  6702. const std::string &val) {
  6703. if (detail::fields::is_field_name(key) &&
  6704. detail::fields::is_field_value(val)) {
  6705. headers.emplace(key, val);
  6706. }
  6707. }
  6708. inline bool Response::has_trailer(const std::string &key) const {
  6709. return trailers.find(key) != trailers.end();
  6710. }
  6711. inline std::string Response::get_trailer_value(const std::string &key,
  6712. size_t id) const {
  6713. auto rng = trailers.equal_range(key);
  6714. auto it = rng.first;
  6715. std::advance(it, static_cast<ssize_t>(id));
  6716. if (it != rng.second) { return it->second; }
  6717. return std::string();
  6718. }
  6719. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  6720. auto r = trailers.equal_range(key);
  6721. return static_cast<size_t>(std::distance(r.first, r.second));
  6722. }
  6723. inline void Response::set_redirect(const std::string &url, int stat) {
  6724. if (detail::fields::is_field_value(url)) {
  6725. set_header("Location", url);
  6726. if (300 <= stat && stat < 400) {
  6727. this->status = stat;
  6728. } else {
  6729. this->status = StatusCode::Found_302;
  6730. }
  6731. }
  6732. }
  6733. inline void Response::set_content(const char *s, size_t n,
  6734. const std::string &content_type) {
  6735. body.assign(s, n);
  6736. auto rng = headers.equal_range("Content-Type");
  6737. headers.erase(rng.first, rng.second);
  6738. set_header("Content-Type", content_type);
  6739. }
  6740. inline void Response::set_content(const std::string &s,
  6741. const std::string &content_type) {
  6742. set_content(s.data(), s.size(), content_type);
  6743. }
  6744. inline void Response::set_content(std::string &&s,
  6745. const std::string &content_type) {
  6746. body = std::move(s);
  6747. auto rng = headers.equal_range("Content-Type");
  6748. headers.erase(rng.first, rng.second);
  6749. set_header("Content-Type", content_type);
  6750. }
  6751. inline void Response::set_content_provider(
  6752. size_t in_length, const std::string &content_type, ContentProvider provider,
  6753. ContentProviderResourceReleaser resource_releaser) {
  6754. set_header("Content-Type", content_type);
  6755. content_length_ = in_length;
  6756. if (in_length > 0) { content_provider_ = std::move(provider); }
  6757. content_provider_resource_releaser_ = std::move(resource_releaser);
  6758. is_chunked_content_provider_ = false;
  6759. }
  6760. inline void Response::set_content_provider(
  6761. const std::string &content_type, ContentProviderWithoutLength provider,
  6762. ContentProviderResourceReleaser resource_releaser) {
  6763. set_header("Content-Type", content_type);
  6764. content_length_ = 0;
  6765. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6766. content_provider_resource_releaser_ = std::move(resource_releaser);
  6767. is_chunked_content_provider_ = false;
  6768. }
  6769. inline void Response::set_chunked_content_provider(
  6770. const std::string &content_type, ContentProviderWithoutLength provider,
  6771. ContentProviderResourceReleaser resource_releaser) {
  6772. set_header("Content-Type", content_type);
  6773. content_length_ = 0;
  6774. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6775. content_provider_resource_releaser_ = std::move(resource_releaser);
  6776. is_chunked_content_provider_ = true;
  6777. }
  6778. inline void Response::set_file_content(const std::string &path,
  6779. const std::string &content_type) {
  6780. file_content_path_ = path;
  6781. file_content_content_type_ = content_type;
  6782. }
  6783. inline void Response::set_file_content(const std::string &path) {
  6784. file_content_path_ = path;
  6785. }
  6786. // Result implementation
  6787. inline bool Result::has_request_header(const std::string &key) const {
  6788. return request_headers_.find(key) != request_headers_.end();
  6789. }
  6790. inline std::string Result::get_request_header_value(const std::string &key,
  6791. const char *def,
  6792. size_t id) const {
  6793. return detail::get_header_value(request_headers_, key, def, id);
  6794. }
  6795. inline size_t
  6796. Result::get_request_header_value_count(const std::string &key) const {
  6797. auto r = request_headers_.equal_range(key);
  6798. return static_cast<size_t>(std::distance(r.first, r.second));
  6799. }
  6800. // Stream implementation
  6801. inline ssize_t Stream::write(const char *ptr) {
  6802. return write(ptr, strlen(ptr));
  6803. }
  6804. inline ssize_t Stream::write(const std::string &s) {
  6805. return write(s.data(), s.size());
  6806. }
  6807. // BodyReader implementation
  6808. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  6809. if (!stream) {
  6810. last_error = Error::Connection;
  6811. return -1;
  6812. }
  6813. if (eof) { return 0; }
  6814. if (!chunked) {
  6815. // Content-Length based reading
  6816. if (bytes_read >= content_length) {
  6817. eof = true;
  6818. return 0;
  6819. }
  6820. auto remaining = content_length - bytes_read;
  6821. auto to_read = (std::min)(len, remaining);
  6822. auto n = stream->read(buf, to_read);
  6823. if (n < 0) {
  6824. last_error = stream->get_error();
  6825. if (last_error == Error::Success) { last_error = Error::Read; }
  6826. eof = true;
  6827. return n;
  6828. }
  6829. if (n == 0) {
  6830. // Unexpected EOF before content_length
  6831. last_error = stream->get_error();
  6832. if (last_error == Error::Success) { last_error = Error::Read; }
  6833. eof = true;
  6834. return 0;
  6835. }
  6836. bytes_read += static_cast<size_t>(n);
  6837. if (bytes_read >= content_length) { eof = true; }
  6838. return n;
  6839. }
  6840. // Chunked transfer encoding: delegate to shared decoder instance.
  6841. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  6842. size_t chunk_offset = 0;
  6843. size_t chunk_total = 0;
  6844. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  6845. if (n < 0) {
  6846. last_error = stream->get_error();
  6847. if (last_error == Error::Success) { last_error = Error::Read; }
  6848. eof = true;
  6849. return n;
  6850. }
  6851. if (n == 0) {
  6852. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  6853. eof = true;
  6854. return 0;
  6855. }
  6856. bytes_read += static_cast<size_t>(n);
  6857. return n;
  6858. }
  6859. namespace detail {
  6860. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  6861. time_t timeout_sec, time_t timeout_usec,
  6862. time_t &actual_timeout_sec,
  6863. time_t &actual_timeout_usec) {
  6864. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  6865. auto actual_timeout_msec =
  6866. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  6867. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  6868. actual_timeout_sec = actual_timeout_msec / 1000;
  6869. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  6870. }
  6871. // Socket stream implementation
  6872. inline SocketStream::SocketStream(
  6873. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  6874. time_t write_timeout_sec, time_t write_timeout_usec,
  6875. time_t max_timeout_msec,
  6876. std::chrono::time_point<std::chrono::steady_clock> start_time)
  6877. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  6878. read_timeout_usec_(read_timeout_usec),
  6879. write_timeout_sec_(write_timeout_sec),
  6880. write_timeout_usec_(write_timeout_usec),
  6881. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  6882. read_buff_(read_buff_size_, 0) {}
  6883. inline SocketStream::~SocketStream() = default;
  6884. inline bool SocketStream::is_readable() const {
  6885. return read_buff_off_ < read_buff_content_size_;
  6886. }
  6887. inline bool SocketStream::wait_readable() const {
  6888. if (max_timeout_msec_ <= 0) {
  6889. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  6890. }
  6891. time_t read_timeout_sec;
  6892. time_t read_timeout_usec;
  6893. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  6894. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  6895. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  6896. }
  6897. inline bool SocketStream::wait_writable() const {
  6898. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  6899. is_socket_alive(sock_);
  6900. }
  6901. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  6902. #ifdef _WIN32
  6903. size =
  6904. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  6905. #else
  6906. size = (std::min)(size,
  6907. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  6908. #endif
  6909. if (read_buff_off_ < read_buff_content_size_) {
  6910. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  6911. if (size <= remaining_size) {
  6912. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  6913. read_buff_off_ += size;
  6914. return static_cast<ssize_t>(size);
  6915. } else {
  6916. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  6917. read_buff_off_ += remaining_size;
  6918. return static_cast<ssize_t>(remaining_size);
  6919. }
  6920. }
  6921. if (!wait_readable()) {
  6922. error_ = Error::Timeout;
  6923. return -1;
  6924. }
  6925. read_buff_off_ = 0;
  6926. read_buff_content_size_ = 0;
  6927. if (size < read_buff_size_) {
  6928. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  6929. CPPHTTPLIB_RECV_FLAGS);
  6930. if (n <= 0) {
  6931. if (n == 0) {
  6932. error_ = Error::ConnectionClosed;
  6933. } else {
  6934. error_ = Error::Read;
  6935. }
  6936. return n;
  6937. } else if (n <= static_cast<ssize_t>(size)) {
  6938. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  6939. return n;
  6940. } else {
  6941. memcpy(ptr, read_buff_.data(), size);
  6942. read_buff_off_ = size;
  6943. read_buff_content_size_ = static_cast<size_t>(n);
  6944. return static_cast<ssize_t>(size);
  6945. }
  6946. } else {
  6947. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  6948. if (n <= 0) {
  6949. if (n == 0) {
  6950. error_ = Error::ConnectionClosed;
  6951. } else {
  6952. error_ = Error::Read;
  6953. }
  6954. }
  6955. return n;
  6956. }
  6957. }
  6958. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  6959. if (!wait_writable()) { return -1; }
  6960. #if defined(_WIN32) && !defined(_WIN64)
  6961. size =
  6962. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  6963. #endif
  6964. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  6965. }
  6966. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  6967. int &port) const {
  6968. return detail::get_remote_ip_and_port(sock_, ip, port);
  6969. }
  6970. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  6971. int &port) const {
  6972. return detail::get_local_ip_and_port(sock_, ip, port);
  6973. }
  6974. inline socket_t SocketStream::socket() const { return sock_; }
  6975. inline time_t SocketStream::duration() const {
  6976. return std::chrono::duration_cast<std::chrono::milliseconds>(
  6977. std::chrono::steady_clock::now() - start_time_)
  6978. .count();
  6979. }
  6980. // Buffer stream implementation
  6981. inline bool BufferStream::is_readable() const { return true; }
  6982. inline bool BufferStream::wait_readable() const { return true; }
  6983. inline bool BufferStream::wait_writable() const { return true; }
  6984. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  6985. #if defined(_MSC_VER) && _MSC_VER < 1910
  6986. auto len_read = buffer._Copy_s(ptr, size, size, position);
  6987. #else
  6988. auto len_read = buffer.copy(ptr, size, position);
  6989. #endif
  6990. position += static_cast<size_t>(len_read);
  6991. return static_cast<ssize_t>(len_read);
  6992. }
  6993. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  6994. buffer.append(ptr, size);
  6995. return static_cast<ssize_t>(size);
  6996. }
  6997. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  6998. int & /*port*/) const {}
  6999. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  7000. int & /*port*/) const {}
  7001. inline socket_t BufferStream::socket() const { return 0; }
  7002. inline time_t BufferStream::duration() const { return 0; }
  7003. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  7004. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  7005. : MatcherBase(pattern) {
  7006. constexpr const char marker[] = "/:";
  7007. // One past the last ending position of a path param substring
  7008. std::size_t last_param_end = 0;
  7009. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7010. // Needed to ensure that parameter names are unique during matcher
  7011. // construction
  7012. // If exceptions are disabled, only last duplicate path
  7013. // parameter will be set
  7014. std::unordered_set<std::string> param_name_set;
  7015. #endif
  7016. while (true) {
  7017. const auto marker_pos = pattern.find(
  7018. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  7019. if (marker_pos == std::string::npos) { break; }
  7020. static_fragments_.push_back(
  7021. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  7022. const auto param_name_start = marker_pos + str_len(marker);
  7023. auto sep_pos = pattern.find(separator, param_name_start);
  7024. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  7025. auto param_name =
  7026. pattern.substr(param_name_start, sep_pos - param_name_start);
  7027. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7028. if (param_name_set.find(param_name) != param_name_set.cend()) {
  7029. std::string msg = "Encountered path parameter '" + param_name +
  7030. "' multiple times in route pattern '" + pattern + "'.";
  7031. throw std::invalid_argument(msg);
  7032. }
  7033. #endif
  7034. param_names_.push_back(std::move(param_name));
  7035. last_param_end = sep_pos + 1;
  7036. }
  7037. if (last_param_end < pattern.length()) {
  7038. static_fragments_.push_back(pattern.substr(last_param_end));
  7039. }
  7040. }
  7041. inline bool PathParamsMatcher::match(Request &request) const {
  7042. request.matches = std::smatch();
  7043. request.path_params.clear();
  7044. request.path_params.reserve(param_names_.size());
  7045. // One past the position at which the path matched the pattern last time
  7046. std::size_t starting_pos = 0;
  7047. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  7048. const auto &fragment = static_fragments_[i];
  7049. if (starting_pos + fragment.length() > request.path.length()) {
  7050. return false;
  7051. }
  7052. // Avoid unnecessary allocation by using strncmp instead of substr +
  7053. // comparison
  7054. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  7055. fragment.length()) != 0) {
  7056. return false;
  7057. }
  7058. starting_pos += fragment.length();
  7059. // Should only happen when we have a static fragment after a param
  7060. // Example: '/users/:id/subscriptions'
  7061. // The 'subscriptions' fragment here does not have a corresponding param
  7062. if (i >= param_names_.size()) { continue; }
  7063. auto sep_pos = request.path.find(separator, starting_pos);
  7064. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  7065. const auto &param_name = param_names_[i];
  7066. request.path_params.emplace(
  7067. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  7068. // Mark everything up to '/' as matched
  7069. starting_pos = sep_pos + 1;
  7070. }
  7071. // Returns false if the path is longer than the pattern
  7072. return starting_pos >= request.path.length();
  7073. }
  7074. inline bool RegexMatcher::match(Request &request) const {
  7075. request.path_params.clear();
  7076. return std::regex_match(request.path, request.matches, regex_);
  7077. }
  7078. // Enclose IPv6 address in brackets if needed
  7079. inline std::string prepare_host_string(const std::string &host) {
  7080. // Enclose IPv6 address in brackets (but not if already enclosed)
  7081. if (host.find(':') == std::string::npos ||
  7082. (!host.empty() && host[0] == '[')) {
  7083. // IPv4, hostname, or already bracketed IPv6
  7084. return host;
  7085. } else {
  7086. // IPv6 address without brackets
  7087. return "[" + host + "]";
  7088. }
  7089. }
  7090. inline std::string make_host_and_port_string(const std::string &host, int port,
  7091. bool is_ssl) {
  7092. auto result = prepare_host_string(host);
  7093. // Append port if not default
  7094. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  7095. ; // do nothing
  7096. } else {
  7097. result += ":" + std::to_string(port);
  7098. }
  7099. return result;
  7100. }
  7101. // Create "host:port" string always including port number (for CONNECT method)
  7102. inline std::string
  7103. make_host_and_port_string_always_port(const std::string &host, int port) {
  7104. return prepare_host_string(host) + ":" + std::to_string(port);
  7105. }
  7106. template <typename T>
  7107. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  7108. T header_writer, Error &error) {
  7109. for (const auto &h : headers) {
  7110. if (!detail::fields::is_field_name(h.first) ||
  7111. !detail::fields::is_field_value(h.second)) {
  7112. error = Error::InvalidHeaders;
  7113. return false;
  7114. }
  7115. }
  7116. if (header_writer(strm, headers) <= 0) {
  7117. error = Error::Write;
  7118. return false;
  7119. }
  7120. return true;
  7121. }
  7122. } // namespace detail
  7123. // HTTP server implementation
  7124. inline Server::Server()
  7125. : new_task_queue(
  7126. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  7127. #ifndef _WIN32
  7128. signal(SIGPIPE, SIG_IGN);
  7129. #endif
  7130. }
  7131. inline Server::~Server() = default;
  7132. inline std::unique_ptr<detail::MatcherBase>
  7133. Server::make_matcher(const std::string &pattern) {
  7134. if (pattern.find("/:") != std::string::npos) {
  7135. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  7136. } else {
  7137. return detail::make_unique<detail::RegexMatcher>(pattern);
  7138. }
  7139. }
  7140. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  7141. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7142. return *this;
  7143. }
  7144. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  7145. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7146. return *this;
  7147. }
  7148. inline Server &Server::Post(const std::string &pattern,
  7149. HandlerWithContentReader handler) {
  7150. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7151. std::move(handler));
  7152. return *this;
  7153. }
  7154. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  7155. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7156. return *this;
  7157. }
  7158. inline Server &Server::Put(const std::string &pattern,
  7159. HandlerWithContentReader handler) {
  7160. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7161. std::move(handler));
  7162. return *this;
  7163. }
  7164. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  7165. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7166. return *this;
  7167. }
  7168. inline Server &Server::Patch(const std::string &pattern,
  7169. HandlerWithContentReader handler) {
  7170. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7171. std::move(handler));
  7172. return *this;
  7173. }
  7174. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  7175. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7176. return *this;
  7177. }
  7178. inline Server &Server::Delete(const std::string &pattern,
  7179. HandlerWithContentReader handler) {
  7180. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7181. std::move(handler));
  7182. return *this;
  7183. }
  7184. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  7185. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7186. return *this;
  7187. }
  7188. inline bool Server::set_base_dir(const std::string &dir,
  7189. const std::string &mount_point) {
  7190. return set_mount_point(mount_point, dir);
  7191. }
  7192. inline bool Server::set_mount_point(const std::string &mount_point,
  7193. const std::string &dir, Headers headers) {
  7194. detail::FileStat stat(dir);
  7195. if (stat.is_dir()) {
  7196. std::string mnt = !mount_point.empty() ? mount_point : "/";
  7197. if (!mnt.empty() && mnt[0] == '/') {
  7198. base_dirs_.push_back({std::move(mnt), dir, std::move(headers)});
  7199. return true;
  7200. }
  7201. }
  7202. return false;
  7203. }
  7204. inline bool Server::remove_mount_point(const std::string &mount_point) {
  7205. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  7206. if (it->mount_point == mount_point) {
  7207. base_dirs_.erase(it);
  7208. return true;
  7209. }
  7210. }
  7211. return false;
  7212. }
  7213. inline Server &
  7214. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  7215. const std::string &mime) {
  7216. file_extension_and_mimetype_map_[ext] = mime;
  7217. return *this;
  7218. }
  7219. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  7220. default_file_mimetype_ = mime;
  7221. return *this;
  7222. }
  7223. inline Server &Server::set_file_request_handler(Handler handler) {
  7224. file_request_handler_ = std::move(handler);
  7225. return *this;
  7226. }
  7227. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  7228. std::true_type) {
  7229. error_handler_ = std::move(handler);
  7230. return *this;
  7231. }
  7232. inline Server &Server::set_error_handler_core(Handler handler,
  7233. std::false_type) {
  7234. error_handler_ = [handler](const Request &req, Response &res) {
  7235. handler(req, res);
  7236. return HandlerResponse::Handled;
  7237. };
  7238. return *this;
  7239. }
  7240. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  7241. exception_handler_ = std::move(handler);
  7242. return *this;
  7243. }
  7244. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  7245. pre_routing_handler_ = std::move(handler);
  7246. return *this;
  7247. }
  7248. inline Server &Server::set_post_routing_handler(Handler handler) {
  7249. post_routing_handler_ = std::move(handler);
  7250. return *this;
  7251. }
  7252. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  7253. pre_request_handler_ = std::move(handler);
  7254. return *this;
  7255. }
  7256. inline Server &Server::set_logger(Logger logger) {
  7257. logger_ = std::move(logger);
  7258. return *this;
  7259. }
  7260. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  7261. error_logger_ = std::move(error_logger);
  7262. return *this;
  7263. }
  7264. inline Server &Server::set_pre_compression_logger(Logger logger) {
  7265. pre_compression_logger_ = std::move(logger);
  7266. return *this;
  7267. }
  7268. inline Server &
  7269. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  7270. expect_100_continue_handler_ = std::move(handler);
  7271. return *this;
  7272. }
  7273. inline Server &Server::set_address_family(int family) {
  7274. address_family_ = family;
  7275. return *this;
  7276. }
  7277. inline Server &Server::set_tcp_nodelay(bool on) {
  7278. tcp_nodelay_ = on;
  7279. return *this;
  7280. }
  7281. inline Server &Server::set_ipv6_v6only(bool on) {
  7282. ipv6_v6only_ = on;
  7283. return *this;
  7284. }
  7285. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  7286. socket_options_ = std::move(socket_options);
  7287. return *this;
  7288. }
  7289. inline Server &Server::set_default_headers(Headers headers) {
  7290. default_headers_ = std::move(headers);
  7291. return *this;
  7292. }
  7293. inline Server &Server::set_header_writer(
  7294. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7295. header_writer_ = writer;
  7296. return *this;
  7297. }
  7298. inline Server &
  7299. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  7300. trusted_proxies_ = proxies;
  7301. return *this;
  7302. }
  7303. inline Server &Server::set_keep_alive_max_count(size_t count) {
  7304. keep_alive_max_count_ = count;
  7305. return *this;
  7306. }
  7307. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  7308. keep_alive_timeout_sec_ = sec;
  7309. return *this;
  7310. }
  7311. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  7312. read_timeout_sec_ = sec;
  7313. read_timeout_usec_ = usec;
  7314. return *this;
  7315. }
  7316. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  7317. write_timeout_sec_ = sec;
  7318. write_timeout_usec_ = usec;
  7319. return *this;
  7320. }
  7321. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  7322. idle_interval_sec_ = sec;
  7323. idle_interval_usec_ = usec;
  7324. return *this;
  7325. }
  7326. inline Server &Server::set_payload_max_length(size_t length) {
  7327. payload_max_length_ = length;
  7328. return *this;
  7329. }
  7330. inline bool Server::bind_to_port(const std::string &host, int port,
  7331. int socket_flags) {
  7332. auto ret = bind_internal(host, port, socket_flags);
  7333. if (ret == -1) { is_decommissioned = true; }
  7334. return ret >= 0;
  7335. }
  7336. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  7337. auto ret = bind_internal(host, 0, socket_flags);
  7338. if (ret == -1) { is_decommissioned = true; }
  7339. return ret;
  7340. }
  7341. inline bool Server::listen_after_bind() { return listen_internal(); }
  7342. inline bool Server::listen(const std::string &host, int port,
  7343. int socket_flags) {
  7344. return bind_to_port(host, port, socket_flags) && listen_internal();
  7345. }
  7346. inline bool Server::is_running() const { return is_running_; }
  7347. inline void Server::wait_until_ready() const {
  7348. while (!is_running_ && !is_decommissioned) {
  7349. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7350. }
  7351. }
  7352. inline void Server::stop() {
  7353. if (is_running_) {
  7354. assert(svr_sock_ != INVALID_SOCKET);
  7355. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  7356. detail::shutdown_socket(sock);
  7357. detail::close_socket(sock);
  7358. }
  7359. is_decommissioned = false;
  7360. }
  7361. inline void Server::decommission() { is_decommissioned = true; }
  7362. inline bool Server::parse_request_line(const char *s, Request &req) const {
  7363. auto len = strlen(s);
  7364. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  7365. len -= 2;
  7366. {
  7367. size_t count = 0;
  7368. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  7369. switch (count) {
  7370. case 0: req.method = std::string(b, e); break;
  7371. case 1: req.target = std::string(b, e); break;
  7372. case 2: req.version = std::string(b, e); break;
  7373. default: break;
  7374. }
  7375. count++;
  7376. });
  7377. if (count != 3) { return false; }
  7378. }
  7379. thread_local const std::set<std::string> methods{
  7380. "GET", "HEAD", "POST", "PUT", "DELETE",
  7381. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7382. if (methods.find(req.method) == methods.end()) {
  7383. output_error_log(Error::InvalidHTTPMethod, &req);
  7384. return false;
  7385. }
  7386. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  7387. output_error_log(Error::InvalidHTTPVersion, &req);
  7388. return false;
  7389. }
  7390. {
  7391. // Skip URL fragment
  7392. for (size_t i = 0; i < req.target.size(); i++) {
  7393. if (req.target[i] == '#') {
  7394. req.target.erase(i);
  7395. break;
  7396. }
  7397. }
  7398. detail::divide(req.target, '?',
  7399. [&](const char *lhs_data, std::size_t lhs_size,
  7400. const char *rhs_data, std::size_t rhs_size) {
  7401. req.path =
  7402. decode_path_component(std::string(lhs_data, lhs_size));
  7403. detail::parse_query_text(rhs_data, rhs_size, req.params);
  7404. });
  7405. }
  7406. return true;
  7407. }
  7408. inline bool Server::write_response(Stream &strm, bool close_connection,
  7409. Request &req, Response &res) {
  7410. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  7411. // incorrectly to the error content.
  7412. req.ranges.clear();
  7413. return write_response_core(strm, close_connection, req, res, false);
  7414. }
  7415. inline bool Server::write_response_with_content(Stream &strm,
  7416. bool close_connection,
  7417. const Request &req,
  7418. Response &res) {
  7419. return write_response_core(strm, close_connection, req, res, true);
  7420. }
  7421. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  7422. const Request &req, Response &res,
  7423. bool need_apply_ranges) {
  7424. assert(res.status != -1);
  7425. if (400 <= res.status && error_handler_ &&
  7426. error_handler_(req, res) == HandlerResponse::Handled) {
  7427. need_apply_ranges = true;
  7428. }
  7429. std::string content_type;
  7430. std::string boundary;
  7431. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  7432. // Prepare additional headers
  7433. if (close_connection || req.get_header_value("Connection") == "close" ||
  7434. 400 <= res.status) { // Don't leave connections open after errors
  7435. res.set_header("Connection", "close");
  7436. } else {
  7437. std::string s = "timeout=";
  7438. s += std::to_string(keep_alive_timeout_sec_);
  7439. s += ", max=";
  7440. s += std::to_string(keep_alive_max_count_);
  7441. res.set_header("Keep-Alive", s);
  7442. }
  7443. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  7444. !res.has_header("Content-Type")) {
  7445. res.set_header("Content-Type", "text/plain");
  7446. }
  7447. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  7448. !res.has_header("Content-Length")) {
  7449. res.set_header("Content-Length", "0");
  7450. }
  7451. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  7452. res.set_header("Accept-Ranges", "bytes");
  7453. }
  7454. if (post_routing_handler_) { post_routing_handler_(req, res); }
  7455. // Response line and headers
  7456. {
  7457. detail::BufferStream bstrm;
  7458. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  7459. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  7460. // Flush buffer
  7461. auto &data = bstrm.get_buffer();
  7462. detail::write_data(strm, data.data(), data.size());
  7463. }
  7464. // Body
  7465. auto ret = true;
  7466. if (req.method != "HEAD") {
  7467. if (!res.body.empty()) {
  7468. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  7469. ret = false;
  7470. }
  7471. } else if (res.content_provider_) {
  7472. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  7473. res.content_provider_success_ = true;
  7474. } else {
  7475. ret = false;
  7476. }
  7477. }
  7478. }
  7479. // Log
  7480. output_log(req, res);
  7481. return ret;
  7482. }
  7483. inline bool
  7484. Server::write_content_with_provider(Stream &strm, const Request &req,
  7485. Response &res, const std::string &boundary,
  7486. const std::string &content_type) {
  7487. auto is_shutting_down = [this]() {
  7488. return this->svr_sock_ == INVALID_SOCKET;
  7489. };
  7490. if (res.content_length_ > 0) {
  7491. if (req.ranges.empty()) {
  7492. return detail::write_content(strm, res.content_provider_, 0,
  7493. res.content_length_, is_shutting_down);
  7494. } else if (req.ranges.size() == 1) {
  7495. auto offset_and_length = detail::get_range_offset_and_length(
  7496. req.ranges[0], res.content_length_);
  7497. return detail::write_content(strm, res.content_provider_,
  7498. offset_and_length.first,
  7499. offset_and_length.second, is_shutting_down);
  7500. } else {
  7501. return detail::write_multipart_ranges_data(
  7502. strm, req, res, boundary, content_type, res.content_length_,
  7503. is_shutting_down);
  7504. }
  7505. } else {
  7506. if (res.is_chunked_content_provider_) {
  7507. auto type = detail::encoding_type(req, res);
  7508. std::unique_ptr<detail::compressor> compressor;
  7509. if (type == detail::EncodingType::Gzip) {
  7510. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7511. compressor = detail::make_unique<detail::gzip_compressor>();
  7512. #endif
  7513. } else if (type == detail::EncodingType::Brotli) {
  7514. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7515. compressor = detail::make_unique<detail::brotli_compressor>();
  7516. #endif
  7517. } else if (type == detail::EncodingType::Zstd) {
  7518. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7519. compressor = detail::make_unique<detail::zstd_compressor>();
  7520. #endif
  7521. } else {
  7522. compressor = detail::make_unique<detail::nocompressor>();
  7523. }
  7524. assert(compressor != nullptr);
  7525. return detail::write_content_chunked(strm, res.content_provider_,
  7526. is_shutting_down, *compressor);
  7527. } else {
  7528. return detail::write_content_without_length(strm, res.content_provider_,
  7529. is_shutting_down);
  7530. }
  7531. }
  7532. }
  7533. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  7534. FormFields::iterator cur_field;
  7535. FormFiles::iterator cur_file;
  7536. auto is_text_field = false;
  7537. size_t count = 0;
  7538. if (read_content_core(
  7539. strm, req, res,
  7540. // Regular
  7541. [&](const char *buf, size_t n) {
  7542. // Prevent arithmetic overflow when checking sizes.
  7543. // Avoid computing (req.body.size() + n) directly because
  7544. // adding two unsigned `size_t` values can wrap around and
  7545. // produce a small result instead of indicating overflow.
  7546. // Instead, check using subtraction: ensure `n` does not
  7547. // exceed the remaining capacity `max_size() - size()`.
  7548. if (req.body.size() >= req.body.max_size() ||
  7549. n > req.body.max_size() - req.body.size()) {
  7550. return false;
  7551. }
  7552. // Limit decompressed body size to payload_max_length_ to protect
  7553. // against "zip bomb" attacks where a small compressed payload
  7554. // decompresses to a massive size.
  7555. if (payload_max_length_ > 0 &&
  7556. (req.body.size() >= payload_max_length_ ||
  7557. n > payload_max_length_ - req.body.size())) {
  7558. return false;
  7559. }
  7560. req.body.append(buf, n);
  7561. return true;
  7562. },
  7563. // Multipart FormData
  7564. [&](const FormData &file) {
  7565. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  7566. output_error_log(Error::TooManyFormDataFiles, &req);
  7567. return false;
  7568. }
  7569. if (file.filename.empty()) {
  7570. cur_field = req.form.fields.emplace(
  7571. file.name, FormField{file.name, file.content, file.headers});
  7572. is_text_field = true;
  7573. } else {
  7574. cur_file = req.form.files.emplace(file.name, file);
  7575. is_text_field = false;
  7576. }
  7577. return true;
  7578. },
  7579. [&](const char *buf, size_t n) {
  7580. if (is_text_field) {
  7581. auto &content = cur_field->second.content;
  7582. if (content.size() + n > content.max_size()) { return false; }
  7583. content.append(buf, n);
  7584. } else {
  7585. auto &content = cur_file->second.content;
  7586. if (content.size() + n > content.max_size()) { return false; }
  7587. content.append(buf, n);
  7588. }
  7589. return true;
  7590. })) {
  7591. const auto &content_type = req.get_header_value("Content-Type");
  7592. if (!content_type.find("application/x-www-form-urlencoded")) {
  7593. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  7594. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  7595. output_error_log(Error::ExceedMaxPayloadSize, &req);
  7596. return false;
  7597. }
  7598. detail::parse_query_text(req.body, req.params);
  7599. }
  7600. return true;
  7601. }
  7602. return false;
  7603. }
  7604. inline bool Server::read_content_with_content_receiver(
  7605. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7606. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  7607. return read_content_core(strm, req, res, std::move(receiver),
  7608. std::move(multipart_header),
  7609. std::move(multipart_receiver));
  7610. }
  7611. inline bool Server::read_content_core(
  7612. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7613. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  7614. detail::FormDataParser multipart_form_data_parser;
  7615. ContentReceiverWithProgress out;
  7616. if (req.is_multipart_form_data()) {
  7617. const auto &content_type = req.get_header_value("Content-Type");
  7618. std::string boundary;
  7619. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  7620. res.status = StatusCode::BadRequest_400;
  7621. output_error_log(Error::MultipartParsing, &req);
  7622. return false;
  7623. }
  7624. multipart_form_data_parser.set_boundary(std::move(boundary));
  7625. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  7626. return multipart_form_data_parser.parse(buf, n, multipart_header,
  7627. multipart_receiver);
  7628. };
  7629. } else {
  7630. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  7631. size_t /*len*/) { return receiver(buf, n); };
  7632. }
  7633. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  7634. // are true (no Transfer-Encoding and no Content-Length), then the message
  7635. // body length is zero (no message body is present).
  7636. //
  7637. // For non-SSL builds, peek into the socket to detect clients that send a
  7638. // body without a Content-Length header (raw HTTP over TCP). If there is
  7639. // pending data that exceeds the configured payload limit, treat this as an
  7640. // oversized request and fail early (causing connection close). For SSL
  7641. // builds we cannot reliably peek the decrypted application bytes, so keep
  7642. // the original behaviour.
  7643. #if !defined(CPPHTTPLIB_OPENSSL_SUPPORT)
  7644. if (!req.has_header("Content-Length") &&
  7645. !detail::is_chunked_transfer_encoding(req.headers)) {
  7646. // Only peek if payload_max_length is set to a finite value
  7647. if (payload_max_length_ > 0 &&
  7648. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  7649. socket_t s = strm.socket();
  7650. if (s != INVALID_SOCKET) {
  7651. // Peek to check if there is any pending data
  7652. char peekbuf[1];
  7653. ssize_t n = ::recv(s, peekbuf, 1, MSG_PEEK);
  7654. if (n > 0) {
  7655. // There is data, so read it with payload limit enforcement
  7656. auto result = detail::read_content_without_length(
  7657. strm, payload_max_length_, out);
  7658. if (result == detail::ReadContentResult::PayloadTooLarge) {
  7659. res.status = StatusCode::PayloadTooLarge_413;
  7660. return false;
  7661. } else if (result != detail::ReadContentResult::Success) {
  7662. return false;
  7663. }
  7664. return true;
  7665. }
  7666. }
  7667. }
  7668. return true;
  7669. }
  7670. #else
  7671. if (!req.has_header("Content-Length") &&
  7672. !detail::is_chunked_transfer_encoding(req.headers)) {
  7673. return true;
  7674. }
  7675. #endif
  7676. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  7677. out, true)) {
  7678. return false;
  7679. }
  7680. if (req.is_multipart_form_data()) {
  7681. if (!multipart_form_data_parser.is_valid()) {
  7682. res.status = StatusCode::BadRequest_400;
  7683. output_error_log(Error::MultipartParsing, &req);
  7684. return false;
  7685. }
  7686. }
  7687. return true;
  7688. }
  7689. inline bool Server::handle_file_request(Request &req, Response &res) {
  7690. for (const auto &entry : base_dirs_) {
  7691. // Prefix match
  7692. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  7693. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  7694. if (detail::is_valid_path(sub_path)) {
  7695. auto path = entry.base_dir + sub_path;
  7696. if (path.back() == '/') { path += "index.html"; }
  7697. detail::FileStat stat(path);
  7698. if (stat.is_dir()) {
  7699. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  7700. return true;
  7701. }
  7702. if (stat.is_file()) {
  7703. for (const auto &kv : entry.headers) {
  7704. res.set_header(kv.first, kv.second);
  7705. }
  7706. auto etag = detail::compute_etag(stat);
  7707. if (!etag.empty()) { res.set_header("ETag", etag); }
  7708. auto mtime = stat.mtime();
  7709. auto last_modified = detail::file_mtime_to_http_date(mtime);
  7710. if (!last_modified.empty()) {
  7711. res.set_header("Last-Modified", last_modified);
  7712. }
  7713. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  7714. check_if_range(req, etag, mtime);
  7715. auto mm = std::make_shared<detail::mmap>(path.c_str());
  7716. if (!mm->is_open()) {
  7717. output_error_log(Error::OpenFile, &req);
  7718. return false;
  7719. }
  7720. res.set_content_provider(
  7721. mm->size(),
  7722. detail::find_content_type(path, file_extension_and_mimetype_map_,
  7723. default_file_mimetype_),
  7724. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  7725. sink.write(mm->data() + offset, length);
  7726. return true;
  7727. });
  7728. if (req.method != "HEAD" && file_request_handler_) {
  7729. file_request_handler_(req, res);
  7730. }
  7731. return true;
  7732. } else {
  7733. output_error_log(Error::OpenFile, &req);
  7734. }
  7735. }
  7736. }
  7737. }
  7738. return false;
  7739. }
  7740. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  7741. const std::string &etag,
  7742. time_t mtime) const {
  7743. // Handle conditional GET:
  7744. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  7745. // 2. If-Modified-Since is checked only when If-None-Match is absent
  7746. if (req.has_header("If-None-Match")) {
  7747. if (!etag.empty()) {
  7748. auto val = req.get_header_value("If-None-Match");
  7749. // NOTE: We use exact string matching here. This works correctly
  7750. // because our server always generates weak ETags (W/"..."), and
  7751. // clients typically send back the same ETag they received.
  7752. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  7753. // If-None-Match, where W/"x" and "x" would match, but this
  7754. // simplified implementation requires exact matches.
  7755. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  7756. [&](const char *b, const char *e) {
  7757. return std::equal(b, e, "*") ||
  7758. std::equal(b, e, etag.begin());
  7759. });
  7760. if (ret) {
  7761. res.status = StatusCode::NotModified_304;
  7762. return true;
  7763. }
  7764. }
  7765. } else if (req.has_header("If-Modified-Since")) {
  7766. auto val = req.get_header_value("If-Modified-Since");
  7767. auto t = detail::parse_http_date(val);
  7768. if (t != static_cast<time_t>(-1) && mtime <= t) {
  7769. res.status = StatusCode::NotModified_304;
  7770. return true;
  7771. }
  7772. }
  7773. return false;
  7774. }
  7775. inline bool Server::check_if_range(Request &req, const std::string &etag,
  7776. time_t mtime) const {
  7777. // Handle If-Range for partial content requests (RFC 9110
  7778. // Section 13.1.5). If-Range is only evaluated when Range header is
  7779. // present. If the validator matches, serve partial content; otherwise
  7780. // serve full content.
  7781. if (!req.ranges.empty() && req.has_header("If-Range")) {
  7782. auto val = req.get_header_value("If-Range");
  7783. auto is_valid_range = [&]() {
  7784. if (detail::is_strong_etag(val)) {
  7785. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  7786. // comparison.
  7787. return (!etag.empty() && val == etag);
  7788. } else if (detail::is_weak_etag(val)) {
  7789. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  7790. return false;
  7791. } else {
  7792. // HTTP-date comparison
  7793. auto t = detail::parse_http_date(val);
  7794. return (t != static_cast<time_t>(-1) && mtime <= t);
  7795. }
  7796. };
  7797. if (!is_valid_range()) {
  7798. // Validator doesn't match: ignore Range and serve full content
  7799. req.ranges.clear();
  7800. return false;
  7801. }
  7802. }
  7803. return true;
  7804. }
  7805. inline socket_t
  7806. Server::create_server_socket(const std::string &host, int port,
  7807. int socket_flags,
  7808. SocketOptions socket_options) const {
  7809. return detail::create_socket(
  7810. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  7811. ipv6_v6only_, std::move(socket_options),
  7812. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  7813. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  7814. output_error_log(Error::BindIPAddress, nullptr);
  7815. return false;
  7816. }
  7817. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  7818. output_error_log(Error::Listen, nullptr);
  7819. return false;
  7820. }
  7821. return true;
  7822. });
  7823. }
  7824. inline int Server::bind_internal(const std::string &host, int port,
  7825. int socket_flags) {
  7826. if (is_decommissioned) { return -1; }
  7827. if (!is_valid()) { return -1; }
  7828. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  7829. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  7830. if (port == 0) {
  7831. struct sockaddr_storage addr;
  7832. socklen_t addr_len = sizeof(addr);
  7833. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  7834. &addr_len) == -1) {
  7835. output_error_log(Error::GetSockName, nullptr);
  7836. return -1;
  7837. }
  7838. if (addr.ss_family == AF_INET) {
  7839. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  7840. } else if (addr.ss_family == AF_INET6) {
  7841. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  7842. } else {
  7843. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  7844. return -1;
  7845. }
  7846. } else {
  7847. return port;
  7848. }
  7849. }
  7850. inline bool Server::listen_internal() {
  7851. if (is_decommissioned) { return false; }
  7852. auto ret = true;
  7853. is_running_ = true;
  7854. auto se = detail::scope_exit([&]() { is_running_ = false; });
  7855. {
  7856. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  7857. while (svr_sock_ != INVALID_SOCKET) {
  7858. #ifndef _WIN32
  7859. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  7860. #endif
  7861. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  7862. idle_interval_usec_);
  7863. if (val == 0) { // Timeout
  7864. task_queue->on_idle();
  7865. continue;
  7866. }
  7867. #ifndef _WIN32
  7868. }
  7869. #endif
  7870. #if defined _WIN32
  7871. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  7872. // OVERLAPPED
  7873. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  7874. #elif defined SOCK_CLOEXEC
  7875. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  7876. #else
  7877. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  7878. #endif
  7879. if (sock == INVALID_SOCKET) {
  7880. if (errno == EMFILE) {
  7881. // The per-process limit of open file descriptors has been reached.
  7882. // Try to accept new connections after a short sleep.
  7883. std::this_thread::sleep_for(std::chrono::microseconds{1});
  7884. continue;
  7885. } else if (errno == EINTR || errno == EAGAIN) {
  7886. continue;
  7887. }
  7888. if (svr_sock_ != INVALID_SOCKET) {
  7889. detail::close_socket(svr_sock_);
  7890. ret = false;
  7891. output_error_log(Error::Connection, nullptr);
  7892. } else {
  7893. ; // The server socket was closed by user.
  7894. }
  7895. break;
  7896. }
  7897. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  7898. read_timeout_sec_, read_timeout_usec_);
  7899. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  7900. write_timeout_sec_, write_timeout_usec_);
  7901. if (!task_queue->enqueue(
  7902. [this, sock]() { process_and_close_socket(sock); })) {
  7903. output_error_log(Error::ResourceExhaustion, nullptr);
  7904. detail::shutdown_socket(sock);
  7905. detail::close_socket(sock);
  7906. }
  7907. }
  7908. task_queue->shutdown();
  7909. }
  7910. is_decommissioned = !ret;
  7911. return ret;
  7912. }
  7913. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  7914. if (pre_routing_handler_ &&
  7915. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  7916. return true;
  7917. }
  7918. // File handler
  7919. if ((req.method == "GET" || req.method == "HEAD") &&
  7920. handle_file_request(req, res)) {
  7921. return true;
  7922. }
  7923. if (detail::expect_content(req)) {
  7924. // Content reader handler
  7925. {
  7926. ContentReader reader(
  7927. [&](ContentReceiver receiver) {
  7928. auto result = read_content_with_content_receiver(
  7929. strm, req, res, std::move(receiver), nullptr, nullptr);
  7930. if (!result) { output_error_log(Error::Read, &req); }
  7931. return result;
  7932. },
  7933. [&](FormDataHeader header, ContentReceiver receiver) {
  7934. auto result = read_content_with_content_receiver(
  7935. strm, req, res, nullptr, std::move(header),
  7936. std::move(receiver));
  7937. if (!result) { output_error_log(Error::Read, &req); }
  7938. return result;
  7939. });
  7940. if (req.method == "POST") {
  7941. if (dispatch_request_for_content_reader(
  7942. req, res, std::move(reader),
  7943. post_handlers_for_content_reader_)) {
  7944. return true;
  7945. }
  7946. } else if (req.method == "PUT") {
  7947. if (dispatch_request_for_content_reader(
  7948. req, res, std::move(reader),
  7949. put_handlers_for_content_reader_)) {
  7950. return true;
  7951. }
  7952. } else if (req.method == "PATCH") {
  7953. if (dispatch_request_for_content_reader(
  7954. req, res, std::move(reader),
  7955. patch_handlers_for_content_reader_)) {
  7956. return true;
  7957. }
  7958. } else if (req.method == "DELETE") {
  7959. if (dispatch_request_for_content_reader(
  7960. req, res, std::move(reader),
  7961. delete_handlers_for_content_reader_)) {
  7962. return true;
  7963. }
  7964. }
  7965. }
  7966. // Read content into `req.body`
  7967. if (!read_content(strm, req, res)) {
  7968. output_error_log(Error::Read, &req);
  7969. return false;
  7970. }
  7971. }
  7972. // Regular handler
  7973. if (req.method == "GET" || req.method == "HEAD") {
  7974. return dispatch_request(req, res, get_handlers_);
  7975. } else if (req.method == "POST") {
  7976. return dispatch_request(req, res, post_handlers_);
  7977. } else if (req.method == "PUT") {
  7978. return dispatch_request(req, res, put_handlers_);
  7979. } else if (req.method == "DELETE") {
  7980. return dispatch_request(req, res, delete_handlers_);
  7981. } else if (req.method == "OPTIONS") {
  7982. return dispatch_request(req, res, options_handlers_);
  7983. } else if (req.method == "PATCH") {
  7984. return dispatch_request(req, res, patch_handlers_);
  7985. }
  7986. res.status = StatusCode::BadRequest_400;
  7987. return false;
  7988. }
  7989. inline bool Server::dispatch_request(Request &req, Response &res,
  7990. const Handlers &handlers) const {
  7991. for (const auto &x : handlers) {
  7992. const auto &matcher = x.first;
  7993. const auto &handler = x.second;
  7994. if (matcher->match(req)) {
  7995. req.matched_route = matcher->pattern();
  7996. if (!pre_request_handler_ ||
  7997. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  7998. handler(req, res);
  7999. }
  8000. return true;
  8001. }
  8002. }
  8003. return false;
  8004. }
  8005. inline void Server::apply_ranges(const Request &req, Response &res,
  8006. std::string &content_type,
  8007. std::string &boundary) const {
  8008. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  8009. auto it = res.headers.find("Content-Type");
  8010. if (it != res.headers.end()) {
  8011. content_type = it->second;
  8012. res.headers.erase(it);
  8013. }
  8014. boundary = detail::make_multipart_data_boundary();
  8015. res.set_header("Content-Type",
  8016. "multipart/byteranges; boundary=" + boundary);
  8017. }
  8018. auto type = detail::encoding_type(req, res);
  8019. if (res.body.empty()) {
  8020. if (res.content_length_ > 0) {
  8021. size_t length = 0;
  8022. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8023. length = res.content_length_;
  8024. } else if (req.ranges.size() == 1) {
  8025. auto offset_and_length = detail::get_range_offset_and_length(
  8026. req.ranges[0], res.content_length_);
  8027. length = offset_and_length.second;
  8028. auto content_range = detail::make_content_range_header_field(
  8029. offset_and_length, res.content_length_);
  8030. res.set_header("Content-Range", content_range);
  8031. } else {
  8032. length = detail::get_multipart_ranges_data_length(
  8033. req, boundary, content_type, res.content_length_);
  8034. }
  8035. res.set_header("Content-Length", std::to_string(length));
  8036. } else {
  8037. if (res.content_provider_) {
  8038. if (res.is_chunked_content_provider_) {
  8039. res.set_header("Transfer-Encoding", "chunked");
  8040. if (type == detail::EncodingType::Gzip) {
  8041. res.set_header("Content-Encoding", "gzip");
  8042. res.set_header("Vary", "Accept-Encoding");
  8043. } else if (type == detail::EncodingType::Brotli) {
  8044. res.set_header("Content-Encoding", "br");
  8045. res.set_header("Vary", "Accept-Encoding");
  8046. } else if (type == detail::EncodingType::Zstd) {
  8047. res.set_header("Content-Encoding", "zstd");
  8048. res.set_header("Vary", "Accept-Encoding");
  8049. }
  8050. }
  8051. }
  8052. }
  8053. } else {
  8054. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8055. ;
  8056. } else if (req.ranges.size() == 1) {
  8057. auto offset_and_length =
  8058. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  8059. auto offset = offset_and_length.first;
  8060. auto length = offset_and_length.second;
  8061. auto content_range = detail::make_content_range_header_field(
  8062. offset_and_length, res.body.size());
  8063. res.set_header("Content-Range", content_range);
  8064. assert(offset + length <= res.body.size());
  8065. res.body = res.body.substr(offset, length);
  8066. } else {
  8067. std::string data;
  8068. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  8069. res.body.size(), data);
  8070. res.body.swap(data);
  8071. }
  8072. if (type != detail::EncodingType::None) {
  8073. output_pre_compression_log(req, res);
  8074. std::unique_ptr<detail::compressor> compressor;
  8075. std::string content_encoding;
  8076. if (type == detail::EncodingType::Gzip) {
  8077. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8078. compressor = detail::make_unique<detail::gzip_compressor>();
  8079. content_encoding = "gzip";
  8080. #endif
  8081. } else if (type == detail::EncodingType::Brotli) {
  8082. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8083. compressor = detail::make_unique<detail::brotli_compressor>();
  8084. content_encoding = "br";
  8085. #endif
  8086. } else if (type == detail::EncodingType::Zstd) {
  8087. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8088. compressor = detail::make_unique<detail::zstd_compressor>();
  8089. content_encoding = "zstd";
  8090. #endif
  8091. }
  8092. if (compressor) {
  8093. std::string compressed;
  8094. if (compressor->compress(res.body.data(), res.body.size(), true,
  8095. [&](const char *data, size_t data_len) {
  8096. compressed.append(data, data_len);
  8097. return true;
  8098. })) {
  8099. res.body.swap(compressed);
  8100. res.set_header("Content-Encoding", content_encoding);
  8101. res.set_header("Vary", "Accept-Encoding");
  8102. }
  8103. }
  8104. }
  8105. auto length = std::to_string(res.body.size());
  8106. res.set_header("Content-Length", length);
  8107. }
  8108. }
  8109. inline bool Server::dispatch_request_for_content_reader(
  8110. Request &req, Response &res, ContentReader content_reader,
  8111. const HandlersForContentReader &handlers) const {
  8112. for (const auto &x : handlers) {
  8113. const auto &matcher = x.first;
  8114. const auto &handler = x.second;
  8115. if (matcher->match(req)) {
  8116. req.matched_route = matcher->pattern();
  8117. if (!pre_request_handler_ ||
  8118. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8119. handler(req, res, content_reader);
  8120. }
  8121. return true;
  8122. }
  8123. }
  8124. return false;
  8125. }
  8126. inline std::string
  8127. get_client_ip(const std::string &x_forwarded_for,
  8128. const std::vector<std::string> &trusted_proxies) {
  8129. // X-Forwarded-For is a comma-separated list per RFC 7239
  8130. std::vector<std::string> ip_list;
  8131. detail::split(x_forwarded_for.data(),
  8132. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  8133. [&](const char *b, const char *e) {
  8134. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  8135. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  8136. });
  8137. for (size_t i = 0; i < ip_list.size(); ++i) {
  8138. auto ip = ip_list[i];
  8139. auto is_trusted_proxy =
  8140. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  8141. [&](const std::string &proxy) { return ip == proxy; });
  8142. if (is_trusted_proxy) {
  8143. if (i == 0) {
  8144. // If the trusted proxy is the first IP, there's no preceding client IP
  8145. return ip;
  8146. } else {
  8147. // Return the IP immediately before the trusted proxy
  8148. return ip_list[i - 1];
  8149. }
  8150. }
  8151. }
  8152. // If no trusted proxy is found, return the first IP in the list
  8153. return ip_list.front();
  8154. }
  8155. inline bool
  8156. Server::process_request(Stream &strm, const std::string &remote_addr,
  8157. int remote_port, const std::string &local_addr,
  8158. int local_port, bool close_connection,
  8159. bool &connection_closed,
  8160. const std::function<void(Request &)> &setup_request) {
  8161. std::array<char, 2048> buf{};
  8162. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8163. // Connection has been closed on client
  8164. if (!line_reader.getline()) { return false; }
  8165. Request req;
  8166. req.start_time_ = std::chrono::steady_clock::now();
  8167. req.remote_addr = remote_addr;
  8168. req.remote_port = remote_port;
  8169. req.local_addr = local_addr;
  8170. req.local_port = local_port;
  8171. Response res;
  8172. res.version = "HTTP/1.1";
  8173. res.headers = default_headers_;
  8174. #ifdef __APPLE__
  8175. // Socket file descriptor exceeded FD_SETSIZE...
  8176. if (strm.socket() >= FD_SETSIZE) {
  8177. Headers dummy;
  8178. detail::read_headers(strm, dummy);
  8179. res.status = StatusCode::InternalServerError_500;
  8180. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  8181. return write_response(strm, close_connection, req, res);
  8182. }
  8183. #endif
  8184. // Request line and headers
  8185. if (!parse_request_line(line_reader.ptr(), req)) {
  8186. res.status = StatusCode::BadRequest_400;
  8187. output_error_log(Error::InvalidRequestLine, &req);
  8188. return write_response(strm, close_connection, req, res);
  8189. }
  8190. // Request headers
  8191. if (!detail::read_headers(strm, req.headers)) {
  8192. res.status = StatusCode::BadRequest_400;
  8193. output_error_log(Error::InvalidHeaders, &req);
  8194. return write_response(strm, close_connection, req, res);
  8195. }
  8196. // Check if the request URI doesn't exceed the limit
  8197. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  8198. res.status = StatusCode::UriTooLong_414;
  8199. output_error_log(Error::ExceedUriMaxLength, &req);
  8200. return write_response(strm, close_connection, req, res);
  8201. }
  8202. if (req.get_header_value("Connection") == "close") {
  8203. connection_closed = true;
  8204. }
  8205. if (req.version == "HTTP/1.0" &&
  8206. req.get_header_value("Connection") != "Keep-Alive") {
  8207. connection_closed = true;
  8208. }
  8209. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  8210. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  8211. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  8212. } else {
  8213. req.remote_addr = remote_addr;
  8214. }
  8215. req.remote_port = remote_port;
  8216. req.local_addr = local_addr;
  8217. req.local_port = local_port;
  8218. if (req.has_header("Accept")) {
  8219. const auto &accept_header = req.get_header_value("Accept");
  8220. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  8221. res.status = StatusCode::BadRequest_400;
  8222. output_error_log(Error::HTTPParsing, &req);
  8223. return write_response(strm, close_connection, req, res);
  8224. }
  8225. }
  8226. if (req.has_header("Range")) {
  8227. const auto &range_header_value = req.get_header_value("Range");
  8228. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  8229. res.status = StatusCode::RangeNotSatisfiable_416;
  8230. output_error_log(Error::InvalidRangeHeader, &req);
  8231. return write_response(strm, close_connection, req, res);
  8232. }
  8233. }
  8234. if (setup_request) { setup_request(req); }
  8235. if (req.get_header_value("Expect") == "100-continue") {
  8236. int status = StatusCode::Continue_100;
  8237. if (expect_100_continue_handler_) {
  8238. status = expect_100_continue_handler_(req, res);
  8239. }
  8240. switch (status) {
  8241. case StatusCode::Continue_100:
  8242. case StatusCode::ExpectationFailed_417:
  8243. detail::write_response_line(strm, status);
  8244. strm.write("\r\n");
  8245. break;
  8246. default:
  8247. connection_closed = true;
  8248. return write_response(strm, true, req, res);
  8249. }
  8250. }
  8251. // Setup `is_connection_closed` method
  8252. auto sock = strm.socket();
  8253. req.is_connection_closed = [sock]() {
  8254. return !detail::is_socket_alive(sock);
  8255. };
  8256. // Routing
  8257. auto routed = false;
  8258. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8259. routed = routing(req, res, strm);
  8260. #else
  8261. try {
  8262. routed = routing(req, res, strm);
  8263. } catch (std::exception &e) {
  8264. if (exception_handler_) {
  8265. auto ep = std::current_exception();
  8266. exception_handler_(req, res, ep);
  8267. routed = true;
  8268. } else {
  8269. res.status = StatusCode::InternalServerError_500;
  8270. std::string val;
  8271. auto s = e.what();
  8272. for (size_t i = 0; s[i]; i++) {
  8273. switch (s[i]) {
  8274. case '\r': val += "\\r"; break;
  8275. case '\n': val += "\\n"; break;
  8276. default: val += s[i]; break;
  8277. }
  8278. }
  8279. res.set_header("EXCEPTION_WHAT", val);
  8280. }
  8281. } catch (...) {
  8282. if (exception_handler_) {
  8283. auto ep = std::current_exception();
  8284. exception_handler_(req, res, ep);
  8285. routed = true;
  8286. } else {
  8287. res.status = StatusCode::InternalServerError_500;
  8288. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  8289. }
  8290. }
  8291. #endif
  8292. if (routed) {
  8293. if (res.status == -1) {
  8294. res.status = req.ranges.empty() ? StatusCode::OK_200
  8295. : StatusCode::PartialContent_206;
  8296. }
  8297. // Serve file content by using a content provider
  8298. if (!res.file_content_path_.empty()) {
  8299. const auto &path = res.file_content_path_;
  8300. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8301. if (!mm->is_open()) {
  8302. res.body.clear();
  8303. res.content_length_ = 0;
  8304. res.content_provider_ = nullptr;
  8305. res.status = StatusCode::NotFound_404;
  8306. output_error_log(Error::OpenFile, &req);
  8307. return write_response(strm, close_connection, req, res);
  8308. }
  8309. auto content_type = res.file_content_content_type_;
  8310. if (content_type.empty()) {
  8311. content_type = detail::find_content_type(
  8312. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  8313. }
  8314. res.set_content_provider(
  8315. mm->size(), content_type,
  8316. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8317. sink.write(mm->data() + offset, length);
  8318. return true;
  8319. });
  8320. }
  8321. if (detail::range_error(req, res)) {
  8322. res.body.clear();
  8323. res.content_length_ = 0;
  8324. res.content_provider_ = nullptr;
  8325. res.status = StatusCode::RangeNotSatisfiable_416;
  8326. return write_response(strm, close_connection, req, res);
  8327. }
  8328. return write_response_with_content(strm, close_connection, req, res);
  8329. } else {
  8330. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  8331. return write_response(strm, close_connection, req, res);
  8332. }
  8333. }
  8334. inline bool Server::is_valid() const { return true; }
  8335. inline bool Server::process_and_close_socket(socket_t sock) {
  8336. std::string remote_addr;
  8337. int remote_port = 0;
  8338. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8339. std::string local_addr;
  8340. int local_port = 0;
  8341. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8342. auto ret = detail::process_server_socket(
  8343. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8344. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8345. write_timeout_usec_,
  8346. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8347. return process_request(strm, remote_addr, remote_port, local_addr,
  8348. local_port, close_connection, connection_closed,
  8349. nullptr);
  8350. });
  8351. detail::shutdown_socket(sock);
  8352. detail::close_socket(sock);
  8353. return ret;
  8354. }
  8355. inline void Server::output_log(const Request &req, const Response &res) const {
  8356. if (logger_) {
  8357. std::lock_guard<std::mutex> guard(logger_mutex_);
  8358. logger_(req, res);
  8359. }
  8360. }
  8361. inline void Server::output_pre_compression_log(const Request &req,
  8362. const Response &res) const {
  8363. if (pre_compression_logger_) {
  8364. std::lock_guard<std::mutex> guard(logger_mutex_);
  8365. pre_compression_logger_(req, res);
  8366. }
  8367. }
  8368. inline void Server::output_error_log(const Error &err,
  8369. const Request *req) const {
  8370. if (error_logger_) {
  8371. std::lock_guard<std::mutex> guard(logger_mutex_);
  8372. error_logger_(err, req);
  8373. }
  8374. }
  8375. // HTTP client implementation
  8376. inline ClientImpl::ClientImpl(const std::string &host)
  8377. : ClientImpl(host, 80, std::string(), std::string()) {}
  8378. inline ClientImpl::ClientImpl(const std::string &host, int port)
  8379. : ClientImpl(host, port, std::string(), std::string()) {}
  8380. inline ClientImpl::ClientImpl(const std::string &host, int port,
  8381. const std::string &client_cert_path,
  8382. const std::string &client_key_path)
  8383. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  8384. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  8385. inline ClientImpl::~ClientImpl() {
  8386. // Wait until all the requests in flight are handled.
  8387. size_t retry_count = 10;
  8388. while (retry_count-- > 0) {
  8389. {
  8390. std::lock_guard<std::mutex> guard(socket_mutex_);
  8391. if (socket_requests_in_flight_ == 0) { break; }
  8392. }
  8393. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  8394. }
  8395. std::lock_guard<std::mutex> guard(socket_mutex_);
  8396. shutdown_socket(socket_);
  8397. close_socket(socket_);
  8398. }
  8399. inline bool ClientImpl::is_valid() const { return true; }
  8400. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  8401. client_cert_path_ = rhs.client_cert_path_;
  8402. client_key_path_ = rhs.client_key_path_;
  8403. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  8404. read_timeout_sec_ = rhs.read_timeout_sec_;
  8405. read_timeout_usec_ = rhs.read_timeout_usec_;
  8406. write_timeout_sec_ = rhs.write_timeout_sec_;
  8407. write_timeout_usec_ = rhs.write_timeout_usec_;
  8408. max_timeout_msec_ = rhs.max_timeout_msec_;
  8409. basic_auth_username_ = rhs.basic_auth_username_;
  8410. basic_auth_password_ = rhs.basic_auth_password_;
  8411. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  8412. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8413. digest_auth_username_ = rhs.digest_auth_username_;
  8414. digest_auth_password_ = rhs.digest_auth_password_;
  8415. #endif
  8416. keep_alive_ = rhs.keep_alive_;
  8417. follow_location_ = rhs.follow_location_;
  8418. path_encode_ = rhs.path_encode_;
  8419. address_family_ = rhs.address_family_;
  8420. tcp_nodelay_ = rhs.tcp_nodelay_;
  8421. ipv6_v6only_ = rhs.ipv6_v6only_;
  8422. socket_options_ = rhs.socket_options_;
  8423. compress_ = rhs.compress_;
  8424. decompress_ = rhs.decompress_;
  8425. interface_ = rhs.interface_;
  8426. proxy_host_ = rhs.proxy_host_;
  8427. proxy_port_ = rhs.proxy_port_;
  8428. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  8429. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  8430. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  8431. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8432. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  8433. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  8434. #endif
  8435. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8436. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  8437. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  8438. ca_cert_store_ = rhs.ca_cert_store_;
  8439. #endif
  8440. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8441. server_certificate_verification_ = rhs.server_certificate_verification_;
  8442. server_hostname_verification_ = rhs.server_hostname_verification_;
  8443. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  8444. #endif
  8445. logger_ = rhs.logger_;
  8446. error_logger_ = rhs.error_logger_;
  8447. }
  8448. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  8449. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8450. return detail::create_client_socket(
  8451. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  8452. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  8453. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  8454. write_timeout_sec_, write_timeout_usec_, interface_, error);
  8455. }
  8456. // Check is custom IP specified for host_
  8457. std::string ip;
  8458. auto it = addr_map_.find(host_);
  8459. if (it != addr_map_.end()) { ip = it->second; }
  8460. return detail::create_client_socket(
  8461. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  8462. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  8463. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8464. write_timeout_usec_, interface_, error);
  8465. }
  8466. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  8467. Error &error) {
  8468. auto sock = create_client_socket(error);
  8469. if (sock == INVALID_SOCKET) { return false; }
  8470. socket.sock = sock;
  8471. return true;
  8472. }
  8473. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  8474. return create_and_connect_socket(socket, error);
  8475. }
  8476. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8477. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  8478. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  8479. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  8480. if (!initialize_ssl(socket, error)) {
  8481. shutdown_socket(socket);
  8482. close_socket(socket);
  8483. return false;
  8484. }
  8485. return true;
  8486. }
  8487. #endif
  8488. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  8489. bool /*shutdown_gracefully*/) {
  8490. // If there are any requests in flight from threads other than us, then it's
  8491. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  8492. assert(socket_requests_in_flight_ == 0 ||
  8493. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8494. }
  8495. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  8496. if (socket.sock == INVALID_SOCKET) { return; }
  8497. detail::shutdown_socket(socket.sock);
  8498. }
  8499. inline void ClientImpl::close_socket(Socket &socket) {
  8500. // If there are requests in flight in another thread, usually closing
  8501. // the socket will be fine and they will simply receive an error when
  8502. // using the closed socket, but it is still a bug since rarely the OS
  8503. // may reassign the socket id to be used for a new socket, and then
  8504. // suddenly they will be operating on a live socket that is different
  8505. // than the one they intended!
  8506. assert(socket_requests_in_flight_ == 0 ||
  8507. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8508. // It is also a bug if this happens while SSL is still active
  8509. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8510. assert(socket.ssl == nullptr);
  8511. #endif
  8512. if (socket.sock == INVALID_SOCKET) { return; }
  8513. detail::close_socket(socket.sock);
  8514. socket.sock = INVALID_SOCKET;
  8515. }
  8516. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  8517. Response &res,
  8518. bool skip_100_continue) const {
  8519. std::array<char, 2048> buf{};
  8520. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8521. if (!line_reader.getline()) { return false; }
  8522. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  8523. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  8524. #else
  8525. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  8526. #endif
  8527. std::cmatch m;
  8528. if (!std::regex_match(line_reader.ptr(), m, re)) {
  8529. return req.method == "CONNECT";
  8530. }
  8531. res.version = std::string(m[1]);
  8532. res.status = std::stoi(std::string(m[2]));
  8533. res.reason = std::string(m[3]);
  8534. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  8535. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  8536. if (!line_reader.getline()) { return false; } // CRLF
  8537. if (!line_reader.getline()) { return false; } // next response line
  8538. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  8539. res.version = std::string(m[1]);
  8540. res.status = std::stoi(std::string(m[2]));
  8541. res.reason = std::string(m[3]);
  8542. }
  8543. return true;
  8544. }
  8545. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  8546. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  8547. auto ret = send_(req, res, error);
  8548. if (error == Error::SSLPeerCouldBeClosed_) {
  8549. assert(!ret);
  8550. ret = send_(req, res, error);
  8551. }
  8552. return ret;
  8553. }
  8554. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  8555. {
  8556. std::lock_guard<std::mutex> guard(socket_mutex_);
  8557. // Set this to false immediately - if it ever gets set to true by the end
  8558. // of the request, we know another thread instructed us to close the
  8559. // socket.
  8560. socket_should_be_closed_when_request_is_done_ = false;
  8561. auto is_alive = false;
  8562. if (socket_.is_open()) {
  8563. is_alive = detail::is_socket_alive(socket_.sock);
  8564. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8565. if (is_alive && is_ssl()) {
  8566. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  8567. is_alive = false;
  8568. }
  8569. }
  8570. #endif
  8571. if (!is_alive) {
  8572. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  8573. // seems like the other side has already closed the connection Also,
  8574. // there cannot be any requests in flight from other threads since we
  8575. // locked request_mutex_, so safe to close everything immediately
  8576. const bool shutdown_gracefully = false;
  8577. shutdown_ssl(socket_, shutdown_gracefully);
  8578. shutdown_socket(socket_);
  8579. close_socket(socket_);
  8580. }
  8581. }
  8582. if (!is_alive) {
  8583. if (!ensure_socket_connection(socket_, error)) {
  8584. output_error_log(error, &req);
  8585. return false;
  8586. }
  8587. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8588. // TODO: refactoring
  8589. if (is_ssl()) {
  8590. auto &scli = static_cast<SSLClient &>(*this);
  8591. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8592. auto success = false;
  8593. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  8594. error)) {
  8595. if (!success) { output_error_log(error, &req); }
  8596. return success;
  8597. }
  8598. }
  8599. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8600. if (!scli.initialize_ssl(socket_, error)) {
  8601. output_error_log(error, &req);
  8602. return false;
  8603. }
  8604. }
  8605. }
  8606. #endif
  8607. }
  8608. // Mark the current socket as being in use so that it cannot be closed by
  8609. // anyone else while this request is ongoing, even though we will be
  8610. // releasing the mutex.
  8611. if (socket_requests_in_flight_ > 1) {
  8612. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  8613. }
  8614. socket_requests_in_flight_ += 1;
  8615. socket_requests_are_from_thread_ = std::this_thread::get_id();
  8616. }
  8617. for (const auto &header : default_headers_) {
  8618. if (req.headers.find(header.first) == req.headers.end()) {
  8619. req.headers.insert(header);
  8620. }
  8621. }
  8622. auto ret = false;
  8623. auto close_connection = !keep_alive_;
  8624. auto se = detail::scope_exit([&]() {
  8625. // Briefly lock mutex in order to mark that a request is no longer ongoing
  8626. std::lock_guard<std::mutex> guard(socket_mutex_);
  8627. socket_requests_in_flight_ -= 1;
  8628. if (socket_requests_in_flight_ <= 0) {
  8629. assert(socket_requests_in_flight_ == 0);
  8630. socket_requests_are_from_thread_ = std::thread::id();
  8631. }
  8632. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  8633. !ret) {
  8634. shutdown_ssl(socket_, true);
  8635. shutdown_socket(socket_);
  8636. close_socket(socket_);
  8637. }
  8638. });
  8639. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  8640. return handle_request(strm, req, res, close_connection, error);
  8641. });
  8642. if (!ret) {
  8643. if (error == Error::Success) {
  8644. error = Error::Unknown;
  8645. output_error_log(error, &req);
  8646. }
  8647. }
  8648. return ret;
  8649. }
  8650. inline Result ClientImpl::send(const Request &req) {
  8651. auto req2 = req;
  8652. return send_(std::move(req2));
  8653. }
  8654. inline Result ClientImpl::send_(Request &&req) {
  8655. auto res = detail::make_unique<Response>();
  8656. auto error = Error::Success;
  8657. auto ret = send(req, *res, error);
  8658. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8659. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  8660. last_ssl_error_, last_openssl_error_};
  8661. #else
  8662. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  8663. #endif
  8664. }
  8665. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  8666. const std::string &ct) {
  8667. (void)for_stream;
  8668. for (const auto &header : default_headers_) {
  8669. if (!r.has_header(header.first)) { r.headers.insert(header); }
  8670. }
  8671. if (!r.has_header("Host")) {
  8672. if (address_family_ == AF_UNIX) {
  8673. r.headers.emplace("Host", "localhost");
  8674. } else {
  8675. r.headers.emplace(
  8676. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  8677. }
  8678. }
  8679. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  8680. if (!r.content_receiver) {
  8681. if (!r.has_header("Accept-Encoding")) {
  8682. std::string accept_encoding;
  8683. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8684. accept_encoding = "br";
  8685. #endif
  8686. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8687. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8688. accept_encoding += "gzip, deflate";
  8689. #endif
  8690. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8691. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8692. accept_encoding += "zstd";
  8693. #endif
  8694. r.set_header("Accept-Encoding", accept_encoding);
  8695. }
  8696. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  8697. if (!r.has_header("User-Agent")) {
  8698. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  8699. r.set_header("User-Agent", agent);
  8700. }
  8701. #endif
  8702. }
  8703. if (!r.body.empty()) {
  8704. if (!ct.empty() && !r.has_header("Content-Type")) {
  8705. r.headers.emplace("Content-Type", ct);
  8706. }
  8707. if (!r.has_header("Content-Length")) {
  8708. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  8709. }
  8710. }
  8711. }
  8712. inline ClientImpl::StreamHandle
  8713. ClientImpl::open_stream(const std::string &method, const std::string &path,
  8714. const Params &params, const Headers &headers,
  8715. const std::string &body,
  8716. const std::string &content_type) {
  8717. StreamHandle handle;
  8718. handle.response = detail::make_unique<Response>();
  8719. handle.error = Error::Success;
  8720. auto query_path = params.empty() ? path : append_query_params(path, params);
  8721. handle.connection_ = detail::make_unique<ClientConnection>();
  8722. {
  8723. std::lock_guard<std::mutex> guard(socket_mutex_);
  8724. auto is_alive = false;
  8725. if (socket_.is_open()) {
  8726. is_alive = detail::is_socket_alive(socket_.sock);
  8727. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8728. if (is_alive && is_ssl()) {
  8729. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  8730. is_alive = false;
  8731. }
  8732. }
  8733. #endif
  8734. if (!is_alive) {
  8735. shutdown_ssl(socket_, false);
  8736. shutdown_socket(socket_);
  8737. close_socket(socket_);
  8738. }
  8739. }
  8740. if (!is_alive) {
  8741. if (!ensure_socket_connection(socket_, handle.error)) {
  8742. handle.response.reset();
  8743. return handle;
  8744. }
  8745. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8746. if (is_ssl()) {
  8747. auto &scli = static_cast<SSLClient &>(*this);
  8748. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8749. if (!scli.initialize_ssl(socket_, handle.error)) {
  8750. handle.response.reset();
  8751. return handle;
  8752. }
  8753. }
  8754. }
  8755. #endif
  8756. }
  8757. transfer_socket_ownership_to_handle(handle);
  8758. }
  8759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8760. if (is_ssl() && handle.connection_->ssl) {
  8761. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  8762. handle.connection_->sock, handle.connection_->ssl, read_timeout_sec_,
  8763. read_timeout_usec_, write_timeout_sec_, write_timeout_usec_);
  8764. } else {
  8765. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8766. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8767. write_timeout_sec_, write_timeout_usec_);
  8768. }
  8769. #else
  8770. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8771. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8772. write_timeout_sec_, write_timeout_usec_);
  8773. #endif
  8774. handle.stream_ = handle.socket_stream_.get();
  8775. Request req;
  8776. req.method = method;
  8777. req.path = query_path;
  8778. req.headers = headers;
  8779. req.body = body;
  8780. prepare_default_headers(req, true, content_type);
  8781. auto &strm = *handle.stream_;
  8782. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  8783. handle.error = Error::Write;
  8784. handle.response.reset();
  8785. return handle;
  8786. }
  8787. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  8788. handle.error)) {
  8789. handle.response.reset();
  8790. return handle;
  8791. }
  8792. if (!body.empty()) {
  8793. if (strm.write(body.data(), body.size()) < 0) {
  8794. handle.error = Error::Write;
  8795. handle.response.reset();
  8796. return handle;
  8797. }
  8798. }
  8799. if (!read_response_line(strm, req, *handle.response) ||
  8800. !detail::read_headers(strm, handle.response->headers)) {
  8801. handle.error = Error::Read;
  8802. handle.response.reset();
  8803. return handle;
  8804. }
  8805. handle.body_reader_.stream = handle.stream_;
  8806. auto content_length_str = handle.response->get_header_value("Content-Length");
  8807. if (!content_length_str.empty()) {
  8808. handle.body_reader_.content_length =
  8809. static_cast<size_t>(std::stoull(content_length_str));
  8810. }
  8811. auto transfer_encoding =
  8812. handle.response->get_header_value("Transfer-Encoding");
  8813. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  8814. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  8815. if (!content_encoding.empty()) {
  8816. handle.decompressor_ = detail::create_decompressor(content_encoding);
  8817. }
  8818. return handle;
  8819. }
  8820. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  8821. if (!is_valid() || !response) { return -1; }
  8822. if (decompressor_) { return read_with_decompression(buf, len); }
  8823. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  8824. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  8825. trailers_parsed_ = true;
  8826. if (body_reader_.chunked_decoder) {
  8827. if (!body_reader_.chunked_decoder->parse_trailers_into(
  8828. response->trailers, response->headers)) {
  8829. return n;
  8830. }
  8831. } else {
  8832. detail::ChunkedDecoder dec(*stream_);
  8833. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  8834. return n;
  8835. }
  8836. }
  8837. }
  8838. return n;
  8839. }
  8840. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  8841. size_t len) {
  8842. if (decompress_offset_ < decompress_buffer_.size()) {
  8843. auto available = decompress_buffer_.size() - decompress_offset_;
  8844. auto to_copy = (std::min)(len, available);
  8845. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  8846. decompress_offset_ += to_copy;
  8847. return static_cast<ssize_t>(to_copy);
  8848. }
  8849. decompress_buffer_.clear();
  8850. decompress_offset_ = 0;
  8851. constexpr size_t kDecompressionBufferSize = 8192;
  8852. char compressed_buf[kDecompressionBufferSize];
  8853. while (true) {
  8854. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  8855. sizeof(compressed_buf));
  8856. if (n <= 0) { return n; }
  8857. bool decompress_ok =
  8858. decompressor_->decompress(compressed_buf, static_cast<size_t>(n),
  8859. [this](const char *data, size_t data_len) {
  8860. decompress_buffer_.append(data, data_len);
  8861. return true;
  8862. });
  8863. if (!decompress_ok) {
  8864. body_reader_.last_error = Error::Read;
  8865. return -1;
  8866. }
  8867. if (!decompress_buffer_.empty()) { break; }
  8868. }
  8869. auto to_copy = (std::min)(len, decompress_buffer_.size());
  8870. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  8871. decompress_offset_ = to_copy;
  8872. return static_cast<ssize_t>(to_copy);
  8873. }
  8874. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  8875. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  8876. return;
  8877. }
  8878. trailers_parsed_ = true;
  8879. const auto bufsiz = 128;
  8880. char line_buf[bufsiz];
  8881. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  8882. if (!line_reader.getline()) { return; }
  8883. if (!detail::parse_trailers(line_reader, response->trailers,
  8884. response->headers)) {
  8885. return;
  8886. }
  8887. }
  8888. // Inline method implementations for `ChunkedDecoder`.
  8889. namespace detail {
  8890. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  8891. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  8892. size_t &out_chunk_offset,
  8893. size_t &out_chunk_total) {
  8894. if (finished) { return 0; }
  8895. if (chunk_remaining == 0) {
  8896. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  8897. if (!lr.getline()) { return -1; }
  8898. char *endptr = nullptr;
  8899. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  8900. if (endptr == lr.ptr()) { return -1; }
  8901. if (chunk_len == ULONG_MAX) { return -1; }
  8902. if (chunk_len == 0) {
  8903. chunk_remaining = 0;
  8904. finished = true;
  8905. out_chunk_offset = 0;
  8906. out_chunk_total = 0;
  8907. return 0;
  8908. }
  8909. chunk_remaining = static_cast<size_t>(chunk_len);
  8910. last_chunk_total = chunk_remaining;
  8911. last_chunk_offset = 0;
  8912. }
  8913. auto to_read = (std::min)(chunk_remaining, len);
  8914. auto n = strm.read(buf, to_read);
  8915. if (n <= 0) { return -1; }
  8916. auto offset_before = last_chunk_offset;
  8917. last_chunk_offset += static_cast<size_t>(n);
  8918. chunk_remaining -= static_cast<size_t>(n);
  8919. out_chunk_offset = offset_before;
  8920. out_chunk_total = last_chunk_total;
  8921. if (chunk_remaining == 0) {
  8922. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  8923. if (!lr.getline()) { return -1; }
  8924. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  8925. }
  8926. return n;
  8927. }
  8928. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  8929. const Headers &src_headers) {
  8930. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  8931. if (!lr.getline()) { return false; }
  8932. return parse_trailers(lr, dest, src_headers);
  8933. }
  8934. } // namespace detail
  8935. inline void
  8936. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  8937. handle.connection_->sock = socket_.sock;
  8938. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8939. handle.connection_->ssl = socket_.ssl;
  8940. socket_.ssl = nullptr;
  8941. #endif
  8942. socket_.sock = INVALID_SOCKET;
  8943. }
  8944. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  8945. Response &res, bool close_connection,
  8946. Error &error) {
  8947. if (req.path.empty()) {
  8948. error = Error::Connection;
  8949. output_error_log(error, &req);
  8950. return false;
  8951. }
  8952. auto req_save = req;
  8953. bool ret;
  8954. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  8955. auto req2 = req;
  8956. req2.path = "http://" +
  8957. detail::make_host_and_port_string(host_, port_, false) +
  8958. req.path;
  8959. ret = process_request(strm, req2, res, close_connection, error);
  8960. req = std::move(req2);
  8961. req.path = req_save.path;
  8962. } else {
  8963. ret = process_request(strm, req, res, close_connection, error);
  8964. }
  8965. if (!ret) { return false; }
  8966. if (res.get_header_value("Connection") == "close" ||
  8967. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  8968. // TODO this requires a not-entirely-obvious chain of calls to be correct
  8969. // for this to be safe.
  8970. // This is safe to call because handle_request is only called by send_
  8971. // which locks the request mutex during the process. It would be a bug
  8972. // to call it from a different thread since it's a thread-safety issue
  8973. // to do these things to the socket if another thread is using the socket.
  8974. std::lock_guard<std::mutex> guard(socket_mutex_);
  8975. shutdown_ssl(socket_, true);
  8976. shutdown_socket(socket_);
  8977. close_socket(socket_);
  8978. }
  8979. if (300 < res.status && res.status < 400 && follow_location_) {
  8980. req = std::move(req_save);
  8981. ret = redirect(req, res, error);
  8982. }
  8983. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8984. if ((res.status == StatusCode::Unauthorized_401 ||
  8985. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  8986. req.authorization_count_ < 5) {
  8987. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  8988. const auto &username =
  8989. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  8990. const auto &password =
  8991. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  8992. if (!username.empty() && !password.empty()) {
  8993. std::map<std::string, std::string> auth;
  8994. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  8995. Request new_req = req;
  8996. new_req.authorization_count_ += 1;
  8997. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  8998. : "Authorization");
  8999. new_req.headers.insert(detail::make_digest_authentication_header(
  9000. req, auth, new_req.authorization_count_, detail::random_string(10),
  9001. username, password, is_proxy));
  9002. Response new_res;
  9003. ret = send(new_req, new_res, error);
  9004. if (ret) { res = std::move(new_res); }
  9005. }
  9006. }
  9007. }
  9008. #endif
  9009. return ret;
  9010. }
  9011. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  9012. if (req.redirect_count_ == 0) {
  9013. error = Error::ExceedRedirectCount;
  9014. output_error_log(error, &req);
  9015. return false;
  9016. }
  9017. auto location = res.get_header_value("location");
  9018. if (location.empty()) { return false; }
  9019. thread_local const std::regex re(
  9020. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  9021. std::smatch m;
  9022. if (!std::regex_match(location, m, re)) { return false; }
  9023. auto scheme = is_ssl() ? "https" : "http";
  9024. auto next_scheme = m[1].str();
  9025. auto next_host = m[2].str();
  9026. if (next_host.empty()) { next_host = m[3].str(); }
  9027. auto port_str = m[4].str();
  9028. auto next_path = m[5].str();
  9029. auto next_query = m[6].str();
  9030. auto next_port = port_;
  9031. if (!port_str.empty()) {
  9032. next_port = std::stoi(port_str);
  9033. } else if (!next_scheme.empty()) {
  9034. next_port = next_scheme == "https" ? 443 : 80;
  9035. }
  9036. if (next_scheme.empty()) { next_scheme = scheme; }
  9037. if (next_host.empty()) { next_host = host_; }
  9038. if (next_path.empty()) { next_path = "/"; }
  9039. auto path = decode_query_component(next_path, true) + next_query;
  9040. // Same host redirect - use current client
  9041. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  9042. return detail::redirect(*this, req, res, path, location, error);
  9043. }
  9044. // Cross-host/scheme redirect - create new client with robust setup
  9045. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  9046. path, location, error);
  9047. }
  9048. // New method for robust redirect client creation
  9049. inline bool ClientImpl::create_redirect_client(
  9050. const std::string &scheme, const std::string &host, int port, Request &req,
  9051. Response &res, const std::string &path, const std::string &location,
  9052. Error &error) {
  9053. // Determine if we need SSL
  9054. auto need_ssl = (scheme == "https");
  9055. // Clean up request headers that are host/client specific
  9056. // Remove headers that should not be carried over to new host
  9057. auto headers_to_remove =
  9058. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  9059. for (const auto &header_name : headers_to_remove) {
  9060. auto it = req.headers.find(header_name);
  9061. while (it != req.headers.end()) {
  9062. it = req.headers.erase(it);
  9063. it = req.headers.find(header_name);
  9064. }
  9065. }
  9066. // Create appropriate client type and handle redirect
  9067. if (need_ssl) {
  9068. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9069. // Create SSL client for HTTPS redirect
  9070. SSLClient redirect_client(host, port);
  9071. // Setup basic client configuration first
  9072. setup_redirect_client(redirect_client);
  9073. // SSL-specific configuration for proxy environments
  9074. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9075. // Critical: Disable SSL verification for proxy environments
  9076. redirect_client.enable_server_certificate_verification(false);
  9077. redirect_client.enable_server_hostname_verification(false);
  9078. } else {
  9079. // For direct SSL connections, copy SSL verification settings
  9080. redirect_client.enable_server_certificate_verification(
  9081. server_certificate_verification_);
  9082. redirect_client.enable_server_hostname_verification(
  9083. server_hostname_verification_);
  9084. }
  9085. // Handle CA certificate store and paths if available
  9086. if (ca_cert_store_ && X509_STORE_up_ref(ca_cert_store_)) {
  9087. redirect_client.set_ca_cert_store(ca_cert_store_);
  9088. }
  9089. if (!ca_cert_file_path_.empty()) {
  9090. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  9091. }
  9092. // Client certificates are set through constructor for SSLClient
  9093. // NOTE: SSLClient constructor already takes client_cert_path and
  9094. // client_key_path so we need to create it properly if client certs are
  9095. // needed
  9096. // Execute the redirect
  9097. return detail::redirect(redirect_client, req, res, path, location, error);
  9098. #else
  9099. // SSL not supported - set appropriate error
  9100. error = Error::SSLConnection;
  9101. output_error_log(error, &req);
  9102. return false;
  9103. #endif
  9104. } else {
  9105. // HTTP redirect
  9106. ClientImpl redirect_client(host, port);
  9107. // Setup client with robust configuration
  9108. setup_redirect_client(redirect_client);
  9109. // Execute the redirect
  9110. return detail::redirect(redirect_client, req, res, path, location, error);
  9111. }
  9112. }
  9113. // New method for robust client setup (based on basic_manual_redirect.cpp
  9114. // logic)
  9115. template <typename ClientType>
  9116. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  9117. // Copy basic settings first
  9118. client.set_connection_timeout(connection_timeout_sec_);
  9119. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  9120. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  9121. client.set_keep_alive(keep_alive_);
  9122. client.set_follow_location(
  9123. true); // Enable redirects to handle multi-step redirects
  9124. client.set_path_encode(path_encode_);
  9125. client.set_compress(compress_);
  9126. client.set_decompress(decompress_);
  9127. // Copy authentication settings BEFORE proxy setup
  9128. if (!basic_auth_username_.empty()) {
  9129. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  9130. }
  9131. if (!bearer_token_auth_token_.empty()) {
  9132. client.set_bearer_token_auth(bearer_token_auth_token_);
  9133. }
  9134. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9135. if (!digest_auth_username_.empty()) {
  9136. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  9137. }
  9138. #endif
  9139. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  9140. // before proxy auth)
  9141. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9142. // First set proxy host and port
  9143. client.set_proxy(proxy_host_, proxy_port_);
  9144. // Then set proxy authentication (order matters!)
  9145. if (!proxy_basic_auth_username_.empty()) {
  9146. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  9147. proxy_basic_auth_password_);
  9148. }
  9149. if (!proxy_bearer_token_auth_token_.empty()) {
  9150. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  9151. }
  9152. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9153. if (!proxy_digest_auth_username_.empty()) {
  9154. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  9155. proxy_digest_auth_password_);
  9156. }
  9157. #endif
  9158. }
  9159. // Copy network and socket settings
  9160. client.set_address_family(address_family_);
  9161. client.set_tcp_nodelay(tcp_nodelay_);
  9162. client.set_ipv6_v6only(ipv6_v6only_);
  9163. if (socket_options_) { client.set_socket_options(socket_options_); }
  9164. if (!interface_.empty()) { client.set_interface(interface_); }
  9165. // Copy logging and headers
  9166. if (logger_) { client.set_logger(logger_); }
  9167. if (error_logger_) { client.set_error_logger(error_logger_); }
  9168. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  9169. // Each new client should generate its own headers based on its target host
  9170. }
  9171. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  9172. const Request &req,
  9173. Error &error) const {
  9174. auto is_shutting_down = []() { return false; };
  9175. if (req.is_chunked_content_provider_) {
  9176. // TODO: Brotli support
  9177. std::unique_ptr<detail::compressor> compressor;
  9178. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9179. if (compress_) {
  9180. compressor = detail::make_unique<detail::gzip_compressor>();
  9181. } else
  9182. #endif
  9183. {
  9184. compressor = detail::make_unique<detail::nocompressor>();
  9185. }
  9186. return detail::write_content_chunked(strm, req.content_provider_,
  9187. is_shutting_down, *compressor, error);
  9188. } else {
  9189. return detail::write_content_with_progress(
  9190. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  9191. req.upload_progress, error);
  9192. }
  9193. }
  9194. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  9195. bool close_connection, Error &error,
  9196. bool skip_body) {
  9197. // Prepare additional headers
  9198. if (close_connection) {
  9199. if (!req.has_header("Connection")) {
  9200. req.set_header("Connection", "close");
  9201. }
  9202. }
  9203. std::string ct_for_defaults;
  9204. if (!req.has_header("Content-Type") && !req.body.empty()) {
  9205. ct_for_defaults = "text/plain";
  9206. }
  9207. prepare_default_headers(req, false, ct_for_defaults);
  9208. if (req.body.empty()) {
  9209. if (req.content_provider_) {
  9210. if (!req.is_chunked_content_provider_) {
  9211. if (!req.has_header("Content-Length")) {
  9212. auto length = std::to_string(req.content_length_);
  9213. req.set_header("Content-Length", length);
  9214. }
  9215. }
  9216. } else {
  9217. if (req.method == "POST" || req.method == "PUT" ||
  9218. req.method == "PATCH") {
  9219. req.set_header("Content-Length", "0");
  9220. }
  9221. }
  9222. }
  9223. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  9224. if (!req.has_header("Authorization")) {
  9225. req.headers.insert(make_basic_authentication_header(
  9226. basic_auth_username_, basic_auth_password_, false));
  9227. }
  9228. }
  9229. if (!proxy_basic_auth_username_.empty() &&
  9230. !proxy_basic_auth_password_.empty()) {
  9231. if (!req.has_header("Proxy-Authorization")) {
  9232. req.headers.insert(make_basic_authentication_header(
  9233. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  9234. }
  9235. }
  9236. if (!bearer_token_auth_token_.empty()) {
  9237. if (!req.has_header("Authorization")) {
  9238. req.headers.insert(make_bearer_token_authentication_header(
  9239. bearer_token_auth_token_, false));
  9240. }
  9241. }
  9242. if (!proxy_bearer_token_auth_token_.empty()) {
  9243. if (!req.has_header("Proxy-Authorization")) {
  9244. req.headers.insert(make_bearer_token_authentication_header(
  9245. proxy_bearer_token_auth_token_, true));
  9246. }
  9247. }
  9248. // Request line and headers
  9249. {
  9250. detail::BufferStream bstrm;
  9251. // Extract path and query from req.path
  9252. std::string path_part, query_part;
  9253. auto query_pos = req.path.find('?');
  9254. if (query_pos != std::string::npos) {
  9255. path_part = req.path.substr(0, query_pos);
  9256. query_part = req.path.substr(query_pos + 1);
  9257. } else {
  9258. path_part = req.path;
  9259. query_part = "";
  9260. }
  9261. // Encode path part. If the original `req.path` already contained a
  9262. // query component, preserve its raw query string (including parameter
  9263. // order) instead of reparsing and reassembling it which may reorder
  9264. // parameters due to container ordering (e.g. `Params` uses
  9265. // `std::multimap`). When there is no query in `req.path`, fall back to
  9266. // building a query from `req.params` so existing callers that pass
  9267. // `Params` continue to work.
  9268. auto path_with_query =
  9269. path_encode_ ? detail::encode_path(path_part) : path_part;
  9270. if (!query_part.empty()) {
  9271. // Normalize the query string (decode then re-encode) while preserving
  9272. // the original parameter order.
  9273. auto normalized = detail::normalize_query_string(query_part);
  9274. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  9275. // Still populate req.params for handlers/users who read them.
  9276. detail::parse_query_text(query_part, req.params);
  9277. } else {
  9278. // No query in path; parse any query_part (empty) and append params
  9279. // from `req.params` when present (preserves prior behavior for
  9280. // callers who provide Params separately).
  9281. detail::parse_query_text(query_part, req.params);
  9282. if (!req.params.empty()) {
  9283. path_with_query = append_query_params(path_with_query, req.params);
  9284. }
  9285. }
  9286. // Write request line and headers
  9287. detail::write_request_line(bstrm, req.method, path_with_query);
  9288. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  9289. error)) {
  9290. output_error_log(error, &req);
  9291. return false;
  9292. }
  9293. // Flush buffer
  9294. auto &data = bstrm.get_buffer();
  9295. if (!detail::write_data(strm, data.data(), data.size())) {
  9296. error = Error::Write;
  9297. output_error_log(error, &req);
  9298. return false;
  9299. }
  9300. }
  9301. // After sending request line and headers, wait briefly for an early server
  9302. // response (e.g. 4xx) and avoid sending a potentially large request body
  9303. // unnecessarily. This workaround is only enabled on Windows because Unix
  9304. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  9305. // buffering can accept large writes even when the peer already responded.
  9306. // Check the stream first (which covers SSL via `is_readable()`), then
  9307. // fall back to select on the socket. Only perform the wait for very large
  9308. // request bodies to avoid interfering with normal small requests and
  9309. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  9310. // response. Skip this check when using Expect: 100-continue, as the protocol
  9311. // handles early responses properly.
  9312. #if defined(_WIN32)
  9313. if (!skip_body &&
  9314. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  9315. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  9316. auto start = std::chrono::high_resolution_clock::now();
  9317. for (;;) {
  9318. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  9319. // from SSL internals. If the underlying socket is readable, assume an
  9320. // early response may be present.
  9321. auto sock = strm.socket();
  9322. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  9323. return false;
  9324. }
  9325. // Fallback to stream-level check for non-socket streams or when the
  9326. // socket isn't reporting readable. Avoid using `is_readable()` for
  9327. // SSL, since `SSL_pending()` may report buffered records that do not
  9328. // indicate a complete application-level response yet.
  9329. if (!is_ssl() && strm.is_readable()) { return false; }
  9330. auto now = std::chrono::high_resolution_clock::now();
  9331. auto elapsed =
  9332. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  9333. .count();
  9334. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  9335. break;
  9336. }
  9337. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  9338. }
  9339. }
  9340. #endif
  9341. // Body
  9342. if (skip_body) { return true; }
  9343. return write_request_body(strm, req, error);
  9344. }
  9345. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  9346. Error &error) {
  9347. if (req.body.empty()) {
  9348. return write_content_with_provider(strm, req, error);
  9349. }
  9350. if (req.upload_progress) {
  9351. auto body_size = req.body.size();
  9352. size_t written = 0;
  9353. auto data = req.body.data();
  9354. while (written < body_size) {
  9355. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  9356. if (!detail::write_data(strm, data + written, to_write)) {
  9357. error = Error::Write;
  9358. output_error_log(error, &req);
  9359. return false;
  9360. }
  9361. written += to_write;
  9362. if (!req.upload_progress(written, body_size)) {
  9363. error = Error::Canceled;
  9364. output_error_log(error, &req);
  9365. return false;
  9366. }
  9367. }
  9368. } else {
  9369. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  9370. error = Error::Write;
  9371. output_error_log(error, &req);
  9372. return false;
  9373. }
  9374. }
  9375. return true;
  9376. }
  9377. inline std::unique_ptr<Response>
  9378. ClientImpl::send_with_content_provider_and_receiver(
  9379. Request &req, const char *body, size_t content_length,
  9380. ContentProvider content_provider,
  9381. ContentProviderWithoutLength content_provider_without_length,
  9382. const std::string &content_type, ContentReceiver content_receiver,
  9383. Error &error) {
  9384. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9385. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9386. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  9387. #endif
  9388. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9389. if (compress_ && !content_provider_without_length) {
  9390. // TODO: Brotli support
  9391. detail::gzip_compressor compressor;
  9392. if (content_provider) {
  9393. auto ok = true;
  9394. size_t offset = 0;
  9395. DataSink data_sink;
  9396. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  9397. if (ok) {
  9398. auto last = offset + data_len == content_length;
  9399. auto ret = compressor.compress(
  9400. data, data_len, last,
  9401. [&](const char *compressed_data, size_t compressed_data_len) {
  9402. req.body.append(compressed_data, compressed_data_len);
  9403. return true;
  9404. });
  9405. if (ret) {
  9406. offset += data_len;
  9407. } else {
  9408. ok = false;
  9409. }
  9410. }
  9411. return ok;
  9412. };
  9413. while (ok && offset < content_length) {
  9414. if (!content_provider(offset, content_length - offset, data_sink)) {
  9415. error = Error::Canceled;
  9416. output_error_log(error, &req);
  9417. return nullptr;
  9418. }
  9419. }
  9420. } else {
  9421. if (!compressor.compress(body, content_length, true,
  9422. [&](const char *data, size_t data_len) {
  9423. req.body.append(data, data_len);
  9424. return true;
  9425. })) {
  9426. error = Error::Compression;
  9427. output_error_log(error, &req);
  9428. return nullptr;
  9429. }
  9430. }
  9431. } else
  9432. #endif
  9433. {
  9434. if (content_provider) {
  9435. req.content_length_ = content_length;
  9436. req.content_provider_ = std::move(content_provider);
  9437. req.is_chunked_content_provider_ = false;
  9438. } else if (content_provider_without_length) {
  9439. req.content_length_ = 0;
  9440. req.content_provider_ = detail::ContentProviderAdapter(
  9441. std::move(content_provider_without_length));
  9442. req.is_chunked_content_provider_ = true;
  9443. req.set_header("Transfer-Encoding", "chunked");
  9444. } else {
  9445. req.body.assign(body, content_length);
  9446. }
  9447. }
  9448. if (content_receiver) {
  9449. req.content_receiver =
  9450. [content_receiver](const char *data, size_t data_length,
  9451. size_t /*offset*/, size_t /*total_length*/) {
  9452. return content_receiver(data, data_length);
  9453. };
  9454. }
  9455. auto res = detail::make_unique<Response>();
  9456. return send(req, *res, error) ? std::move(res) : nullptr;
  9457. }
  9458. inline Result ClientImpl::send_with_content_provider_and_receiver(
  9459. const std::string &method, const std::string &path, const Headers &headers,
  9460. const char *body, size_t content_length, ContentProvider content_provider,
  9461. ContentProviderWithoutLength content_provider_without_length,
  9462. const std::string &content_type, ContentReceiver content_receiver,
  9463. UploadProgress progress) {
  9464. Request req;
  9465. req.method = method;
  9466. req.headers = headers;
  9467. req.path = path;
  9468. req.upload_progress = std::move(progress);
  9469. if (max_timeout_msec_ > 0) {
  9470. req.start_time_ = std::chrono::steady_clock::now();
  9471. }
  9472. auto error = Error::Success;
  9473. auto res = send_with_content_provider_and_receiver(
  9474. req, body, content_length, std::move(content_provider),
  9475. std::move(content_provider_without_length), content_type,
  9476. std::move(content_receiver), error);
  9477. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9478. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  9479. last_openssl_error_};
  9480. #else
  9481. return Result{std::move(res), error, std::move(req.headers)};
  9482. #endif
  9483. }
  9484. inline void ClientImpl::output_log(const Request &req,
  9485. const Response &res) const {
  9486. if (logger_) {
  9487. std::lock_guard<std::mutex> guard(logger_mutex_);
  9488. logger_(req, res);
  9489. }
  9490. }
  9491. inline void ClientImpl::output_error_log(const Error &err,
  9492. const Request *req) const {
  9493. if (error_logger_) {
  9494. std::lock_guard<std::mutex> guard(logger_mutex_);
  9495. error_logger_(err, req);
  9496. }
  9497. }
  9498. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  9499. Response &res, bool close_connection,
  9500. Error &error) {
  9501. // Auto-add Expect: 100-continue for large bodies
  9502. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  9503. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  9504. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  9505. req.set_header("Expect", "100-continue");
  9506. }
  9507. }
  9508. // Check for Expect: 100-continue
  9509. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  9510. // Send request (skip body if using Expect: 100-continue)
  9511. auto write_request_success =
  9512. write_request(strm, req, close_connection, error, expect_100_continue);
  9513. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9514. if (is_ssl()) {
  9515. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  9516. if (!is_proxy_enabled) {
  9517. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  9518. error = Error::SSLPeerCouldBeClosed_;
  9519. output_error_log(error, &req);
  9520. return false;
  9521. }
  9522. }
  9523. }
  9524. #endif
  9525. // Handle Expect: 100-continue with timeout
  9526. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  9527. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  9528. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  9529. auto ret = detail::select_read(strm.socket(), sec, usec);
  9530. if (ret <= 0) {
  9531. // Timeout or error: send body anyway (server didn't respond in time)
  9532. if (!write_request_body(strm, req, error)) { return false; }
  9533. expect_100_continue = false; // Switch to normal response handling
  9534. }
  9535. }
  9536. // Receive response and headers
  9537. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  9538. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  9539. !detail::read_headers(strm, res.headers)) {
  9540. if (write_request_success) { error = Error::Read; }
  9541. output_error_log(error, &req);
  9542. return false;
  9543. }
  9544. if (!write_request_success) { return false; }
  9545. // Handle Expect: 100-continue response
  9546. if (expect_100_continue) {
  9547. if (res.status == StatusCode::Continue_100) {
  9548. // Server accepted, send the body
  9549. if (!write_request_body(strm, req, error)) { return false; }
  9550. // Read the actual response
  9551. res.headers.clear();
  9552. res.body.clear();
  9553. if (!read_response_line(strm, req, res) ||
  9554. !detail::read_headers(strm, res.headers)) {
  9555. error = Error::Read;
  9556. output_error_log(error, &req);
  9557. return false;
  9558. }
  9559. }
  9560. // If not 100 Continue, server returned an error; proceed with that response
  9561. }
  9562. // Body
  9563. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  9564. req.method != "CONNECT") {
  9565. auto redirect = 300 < res.status && res.status < 400 &&
  9566. res.status != StatusCode::NotModified_304 &&
  9567. follow_location_;
  9568. if (req.response_handler && !redirect) {
  9569. if (!req.response_handler(res)) {
  9570. error = Error::Canceled;
  9571. output_error_log(error, &req);
  9572. return false;
  9573. }
  9574. }
  9575. auto out =
  9576. req.content_receiver
  9577. ? static_cast<ContentReceiverWithProgress>(
  9578. [&](const char *buf, size_t n, size_t off, size_t len) {
  9579. if (redirect) { return true; }
  9580. auto ret = req.content_receiver(buf, n, off, len);
  9581. if (!ret) {
  9582. error = Error::Canceled;
  9583. output_error_log(error, &req);
  9584. }
  9585. return ret;
  9586. })
  9587. : static_cast<ContentReceiverWithProgress>(
  9588. [&](const char *buf, size_t n, size_t /*off*/,
  9589. size_t /*len*/) {
  9590. assert(res.body.size() + n <= res.body.max_size());
  9591. res.body.append(buf, n);
  9592. return true;
  9593. });
  9594. auto progress = [&](size_t current, size_t total) {
  9595. if (!req.download_progress || redirect) { return true; }
  9596. auto ret = req.download_progress(current, total);
  9597. if (!ret) {
  9598. error = Error::Canceled;
  9599. output_error_log(error, &req);
  9600. }
  9601. return ret;
  9602. };
  9603. if (res.has_header("Content-Length")) {
  9604. if (!req.content_receiver) {
  9605. auto len = res.get_header_value_u64("Content-Length");
  9606. if (len > res.body.max_size()) {
  9607. error = Error::Read;
  9608. output_error_log(error, &req);
  9609. return false;
  9610. }
  9611. res.body.reserve(static_cast<size_t>(len));
  9612. }
  9613. }
  9614. if (res.status != StatusCode::NotModified_304) {
  9615. int dummy_status;
  9616. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  9617. dummy_status, std::move(progress),
  9618. std::move(out), decompress_)) {
  9619. if (error != Error::Canceled) { error = Error::Read; }
  9620. output_error_log(error, &req);
  9621. return false;
  9622. }
  9623. }
  9624. }
  9625. // Log
  9626. output_log(req, res);
  9627. return true;
  9628. }
  9629. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  9630. const std::string &boundary, const UploadFormDataItems &items,
  9631. const FormDataProviderItems &provider_items) const {
  9632. size_t cur_item = 0;
  9633. size_t cur_start = 0;
  9634. // cur_item and cur_start are copied to within the std::function and
  9635. // maintain state between successive calls
  9636. return [&, cur_item, cur_start](size_t offset,
  9637. DataSink &sink) mutable -> bool {
  9638. if (!offset && !items.empty()) {
  9639. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  9640. return true;
  9641. } else if (cur_item < provider_items.size()) {
  9642. if (!cur_start) {
  9643. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  9644. provider_items[cur_item], boundary);
  9645. offset += begin.size();
  9646. cur_start = offset;
  9647. sink.os << begin;
  9648. }
  9649. DataSink cur_sink;
  9650. auto has_data = true;
  9651. cur_sink.write = sink.write;
  9652. cur_sink.done = [&]() { has_data = false; };
  9653. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  9654. return false;
  9655. }
  9656. if (!has_data) {
  9657. sink.os << detail::serialize_multipart_formdata_item_end();
  9658. cur_item++;
  9659. cur_start = 0;
  9660. }
  9661. return true;
  9662. } else {
  9663. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  9664. sink.done();
  9665. return true;
  9666. }
  9667. };
  9668. }
  9669. inline bool ClientImpl::process_socket(
  9670. const Socket &socket,
  9671. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9672. std::function<bool(Stream &strm)> callback) {
  9673. return detail::process_client_socket(
  9674. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9675. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  9676. }
  9677. inline bool ClientImpl::is_ssl() const { return false; }
  9678. inline Result ClientImpl::Get(const std::string &path,
  9679. DownloadProgress progress) {
  9680. return Get(path, Headers(), std::move(progress));
  9681. }
  9682. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9683. const Headers &headers,
  9684. DownloadProgress progress) {
  9685. if (params.empty()) { return Get(path, headers); }
  9686. std::string path_with_query = append_query_params(path, params);
  9687. return Get(path_with_query, headers, std::move(progress));
  9688. }
  9689. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9690. DownloadProgress progress) {
  9691. Request req;
  9692. req.method = "GET";
  9693. req.path = path;
  9694. req.headers = headers;
  9695. req.download_progress = std::move(progress);
  9696. if (max_timeout_msec_ > 0) {
  9697. req.start_time_ = std::chrono::steady_clock::now();
  9698. }
  9699. return send_(std::move(req));
  9700. }
  9701. inline Result ClientImpl::Get(const std::string &path,
  9702. ContentReceiver content_receiver,
  9703. DownloadProgress progress) {
  9704. return Get(path, Headers(), nullptr, std::move(content_receiver),
  9705. std::move(progress));
  9706. }
  9707. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9708. ContentReceiver content_receiver,
  9709. DownloadProgress progress) {
  9710. return Get(path, headers, nullptr, std::move(content_receiver),
  9711. std::move(progress));
  9712. }
  9713. inline Result ClientImpl::Get(const std::string &path,
  9714. ResponseHandler response_handler,
  9715. ContentReceiver content_receiver,
  9716. DownloadProgress progress) {
  9717. return Get(path, Headers(), std::move(response_handler),
  9718. std::move(content_receiver), std::move(progress));
  9719. }
  9720. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9721. ResponseHandler response_handler,
  9722. ContentReceiver content_receiver,
  9723. DownloadProgress progress) {
  9724. Request req;
  9725. req.method = "GET";
  9726. req.path = path;
  9727. req.headers = headers;
  9728. req.response_handler = std::move(response_handler);
  9729. req.content_receiver =
  9730. [content_receiver](const char *data, size_t data_length,
  9731. size_t /*offset*/, size_t /*total_length*/) {
  9732. return content_receiver(data, data_length);
  9733. };
  9734. req.download_progress = std::move(progress);
  9735. if (max_timeout_msec_ > 0) {
  9736. req.start_time_ = std::chrono::steady_clock::now();
  9737. }
  9738. return send_(std::move(req));
  9739. }
  9740. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9741. const Headers &headers,
  9742. ContentReceiver content_receiver,
  9743. DownloadProgress progress) {
  9744. return Get(path, params, headers, nullptr, std::move(content_receiver),
  9745. std::move(progress));
  9746. }
  9747. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9748. const Headers &headers,
  9749. ResponseHandler response_handler,
  9750. ContentReceiver content_receiver,
  9751. DownloadProgress progress) {
  9752. if (params.empty()) {
  9753. return Get(path, headers, std::move(response_handler),
  9754. std::move(content_receiver), std::move(progress));
  9755. }
  9756. std::string path_with_query = append_query_params(path, params);
  9757. return Get(path_with_query, headers, std::move(response_handler),
  9758. std::move(content_receiver), std::move(progress));
  9759. }
  9760. inline Result ClientImpl::Head(const std::string &path) {
  9761. return Head(path, Headers());
  9762. }
  9763. inline Result ClientImpl::Head(const std::string &path,
  9764. const Headers &headers) {
  9765. Request req;
  9766. req.method = "HEAD";
  9767. req.headers = headers;
  9768. req.path = path;
  9769. if (max_timeout_msec_ > 0) {
  9770. req.start_time_ = std::chrono::steady_clock::now();
  9771. }
  9772. return send_(std::move(req));
  9773. }
  9774. inline Result ClientImpl::Post(const std::string &path) {
  9775. return Post(path, std::string(), std::string());
  9776. }
  9777. inline Result ClientImpl::Post(const std::string &path,
  9778. const Headers &headers) {
  9779. return Post(path, headers, nullptr, 0, std::string());
  9780. }
  9781. inline Result ClientImpl::Post(const std::string &path, const char *body,
  9782. size_t content_length,
  9783. const std::string &content_type,
  9784. UploadProgress progress) {
  9785. return Post(path, Headers(), body, content_length, content_type, progress);
  9786. }
  9787. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  9788. const std::string &content_type,
  9789. UploadProgress progress) {
  9790. return Post(path, Headers(), body, content_type, progress);
  9791. }
  9792. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  9793. return Post(path, Headers(), params);
  9794. }
  9795. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9796. ContentProvider content_provider,
  9797. const std::string &content_type,
  9798. UploadProgress progress) {
  9799. return Post(path, Headers(), content_length, std::move(content_provider),
  9800. content_type, progress);
  9801. }
  9802. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9803. ContentProvider content_provider,
  9804. const std::string &content_type,
  9805. ContentReceiver content_receiver,
  9806. UploadProgress progress) {
  9807. return Post(path, Headers(), content_length, std::move(content_provider),
  9808. content_type, std::move(content_receiver), progress);
  9809. }
  9810. inline Result ClientImpl::Post(const std::string &path,
  9811. ContentProviderWithoutLength content_provider,
  9812. const std::string &content_type,
  9813. UploadProgress progress) {
  9814. return Post(path, Headers(), std::move(content_provider), content_type,
  9815. progress);
  9816. }
  9817. inline Result ClientImpl::Post(const std::string &path,
  9818. ContentProviderWithoutLength content_provider,
  9819. const std::string &content_type,
  9820. ContentReceiver content_receiver,
  9821. UploadProgress progress) {
  9822. return Post(path, Headers(), std::move(content_provider), content_type,
  9823. std::move(content_receiver), progress);
  9824. }
  9825. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9826. const Params &params) {
  9827. auto query = detail::params_to_query_str(params);
  9828. return Post(path, headers, query, "application/x-www-form-urlencoded");
  9829. }
  9830. inline Result ClientImpl::Post(const std::string &path,
  9831. const UploadFormDataItems &items,
  9832. UploadProgress progress) {
  9833. return Post(path, Headers(), items, progress);
  9834. }
  9835. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9836. const UploadFormDataItems &items,
  9837. UploadProgress progress) {
  9838. const auto &boundary = detail::make_multipart_data_boundary();
  9839. const auto &content_type =
  9840. detail::serialize_multipart_formdata_get_content_type(boundary);
  9841. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9842. return Post(path, headers, body, content_type, progress);
  9843. }
  9844. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9845. const UploadFormDataItems &items,
  9846. const std::string &boundary,
  9847. UploadProgress progress) {
  9848. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  9849. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  9850. }
  9851. const auto &content_type =
  9852. detail::serialize_multipart_formdata_get_content_type(boundary);
  9853. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9854. return Post(path, headers, body, content_type, progress);
  9855. }
  9856. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9857. const char *body, size_t content_length,
  9858. const std::string &content_type,
  9859. UploadProgress progress) {
  9860. return send_with_content_provider_and_receiver(
  9861. "POST", path, headers, body, content_length, nullptr, nullptr,
  9862. content_type, nullptr, progress);
  9863. }
  9864. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9865. const std::string &body,
  9866. const std::string &content_type,
  9867. UploadProgress progress) {
  9868. return send_with_content_provider_and_receiver(
  9869. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  9870. content_type, nullptr, progress);
  9871. }
  9872. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9873. size_t content_length,
  9874. ContentProvider content_provider,
  9875. const std::string &content_type,
  9876. UploadProgress progress) {
  9877. return send_with_content_provider_and_receiver(
  9878. "POST", path, headers, nullptr, content_length,
  9879. std::move(content_provider), nullptr, content_type, nullptr, progress);
  9880. }
  9881. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9882. size_t content_length,
  9883. ContentProvider content_provider,
  9884. const std::string &content_type,
  9885. ContentReceiver content_receiver,
  9886. DownloadProgress progress) {
  9887. return send_with_content_provider_and_receiver(
  9888. "POST", path, headers, nullptr, content_length,
  9889. std::move(content_provider), nullptr, content_type,
  9890. std::move(content_receiver), std::move(progress));
  9891. }
  9892. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9893. ContentProviderWithoutLength content_provider,
  9894. const std::string &content_type,
  9895. UploadProgress progress) {
  9896. return send_with_content_provider_and_receiver(
  9897. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  9898. content_type, nullptr, progress);
  9899. }
  9900. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9901. ContentProviderWithoutLength content_provider,
  9902. const std::string &content_type,
  9903. ContentReceiver content_receiver,
  9904. DownloadProgress progress) {
  9905. return send_with_content_provider_and_receiver(
  9906. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  9907. content_type, std::move(content_receiver), std::move(progress));
  9908. }
  9909. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9910. const UploadFormDataItems &items,
  9911. const FormDataProviderItems &provider_items,
  9912. UploadProgress progress) {
  9913. const auto &boundary = detail::make_multipart_data_boundary();
  9914. const auto &content_type =
  9915. detail::serialize_multipart_formdata_get_content_type(boundary);
  9916. return send_with_content_provider_and_receiver(
  9917. "POST", path, headers, nullptr, 0, nullptr,
  9918. get_multipart_content_provider(boundary, items, provider_items),
  9919. content_type, nullptr, progress);
  9920. }
  9921. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9922. const std::string &body,
  9923. const std::string &content_type,
  9924. ContentReceiver content_receiver,
  9925. DownloadProgress progress) {
  9926. Request req;
  9927. req.method = "POST";
  9928. req.path = path;
  9929. req.headers = headers;
  9930. req.body = body;
  9931. req.content_receiver =
  9932. [content_receiver](const char *data, size_t data_length,
  9933. size_t /*offset*/, size_t /*total_length*/) {
  9934. return content_receiver(data, data_length);
  9935. };
  9936. req.download_progress = std::move(progress);
  9937. if (max_timeout_msec_ > 0) {
  9938. req.start_time_ = std::chrono::steady_clock::now();
  9939. }
  9940. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9941. return send_(std::move(req));
  9942. }
  9943. inline Result ClientImpl::Put(const std::string &path) {
  9944. return Put(path, std::string(), std::string());
  9945. }
  9946. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  9947. return Put(path, headers, nullptr, 0, std::string());
  9948. }
  9949. inline Result ClientImpl::Put(const std::string &path, const char *body,
  9950. size_t content_length,
  9951. const std::string &content_type,
  9952. UploadProgress progress) {
  9953. return Put(path, Headers(), body, content_length, content_type, progress);
  9954. }
  9955. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  9956. const std::string &content_type,
  9957. UploadProgress progress) {
  9958. return Put(path, Headers(), body, content_type, progress);
  9959. }
  9960. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  9961. return Put(path, Headers(), params);
  9962. }
  9963. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  9964. ContentProvider content_provider,
  9965. const std::string &content_type,
  9966. UploadProgress progress) {
  9967. return Put(path, Headers(), content_length, std::move(content_provider),
  9968. content_type, progress);
  9969. }
  9970. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  9971. ContentProvider content_provider,
  9972. const std::string &content_type,
  9973. ContentReceiver content_receiver,
  9974. UploadProgress progress) {
  9975. return Put(path, Headers(), content_length, std::move(content_provider),
  9976. content_type, std::move(content_receiver), progress);
  9977. }
  9978. inline Result ClientImpl::Put(const std::string &path,
  9979. ContentProviderWithoutLength content_provider,
  9980. const std::string &content_type,
  9981. UploadProgress progress) {
  9982. return Put(path, Headers(), std::move(content_provider), content_type,
  9983. progress);
  9984. }
  9985. inline Result ClientImpl::Put(const std::string &path,
  9986. ContentProviderWithoutLength content_provider,
  9987. const std::string &content_type,
  9988. ContentReceiver content_receiver,
  9989. UploadProgress progress) {
  9990. return Put(path, Headers(), std::move(content_provider), content_type,
  9991. std::move(content_receiver), progress);
  9992. }
  9993. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9994. const Params &params) {
  9995. auto query = detail::params_to_query_str(params);
  9996. return Put(path, headers, query, "application/x-www-form-urlencoded");
  9997. }
  9998. inline Result ClientImpl::Put(const std::string &path,
  9999. const UploadFormDataItems &items,
  10000. UploadProgress progress) {
  10001. return Put(path, Headers(), items, progress);
  10002. }
  10003. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10004. const UploadFormDataItems &items,
  10005. UploadProgress progress) {
  10006. const auto &boundary = detail::make_multipart_data_boundary();
  10007. const auto &content_type =
  10008. detail::serialize_multipart_formdata_get_content_type(boundary);
  10009. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10010. return Put(path, headers, body, content_type, progress);
  10011. }
  10012. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10013. const UploadFormDataItems &items,
  10014. const std::string &boundary,
  10015. UploadProgress progress) {
  10016. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10017. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10018. }
  10019. const auto &content_type =
  10020. detail::serialize_multipart_formdata_get_content_type(boundary);
  10021. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10022. return Put(path, headers, body, content_type, progress);
  10023. }
  10024. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10025. const char *body, size_t content_length,
  10026. const std::string &content_type,
  10027. UploadProgress progress) {
  10028. return send_with_content_provider_and_receiver(
  10029. "PUT", path, headers, body, content_length, nullptr, nullptr,
  10030. content_type, nullptr, progress);
  10031. }
  10032. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10033. const std::string &body,
  10034. const std::string &content_type,
  10035. UploadProgress progress) {
  10036. return send_with_content_provider_and_receiver(
  10037. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  10038. content_type, nullptr, progress);
  10039. }
  10040. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10041. size_t content_length,
  10042. ContentProvider content_provider,
  10043. const std::string &content_type,
  10044. UploadProgress progress) {
  10045. return send_with_content_provider_and_receiver(
  10046. "PUT", path, headers, nullptr, content_length,
  10047. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10048. }
  10049. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10050. size_t content_length,
  10051. ContentProvider content_provider,
  10052. const std::string &content_type,
  10053. ContentReceiver content_receiver,
  10054. UploadProgress progress) {
  10055. return send_with_content_provider_and_receiver(
  10056. "PUT", path, headers, nullptr, content_length,
  10057. std::move(content_provider), nullptr, content_type,
  10058. std::move(content_receiver), progress);
  10059. }
  10060. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10061. ContentProviderWithoutLength content_provider,
  10062. const std::string &content_type,
  10063. UploadProgress progress) {
  10064. return send_with_content_provider_and_receiver(
  10065. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10066. content_type, nullptr, progress);
  10067. }
  10068. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10069. ContentProviderWithoutLength content_provider,
  10070. const std::string &content_type,
  10071. ContentReceiver content_receiver,
  10072. UploadProgress progress) {
  10073. return send_with_content_provider_and_receiver(
  10074. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10075. content_type, std::move(content_receiver), progress);
  10076. }
  10077. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10078. const UploadFormDataItems &items,
  10079. const FormDataProviderItems &provider_items,
  10080. UploadProgress progress) {
  10081. const auto &boundary = detail::make_multipart_data_boundary();
  10082. const auto &content_type =
  10083. detail::serialize_multipart_formdata_get_content_type(boundary);
  10084. return send_with_content_provider_and_receiver(
  10085. "PUT", path, headers, nullptr, 0, nullptr,
  10086. get_multipart_content_provider(boundary, items, provider_items),
  10087. content_type, nullptr, progress);
  10088. }
  10089. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10090. const std::string &body,
  10091. const std::string &content_type,
  10092. ContentReceiver content_receiver,
  10093. DownloadProgress progress) {
  10094. Request req;
  10095. req.method = "PUT";
  10096. req.path = path;
  10097. req.headers = headers;
  10098. req.body = body;
  10099. req.content_receiver =
  10100. [content_receiver](const char *data, size_t data_length,
  10101. size_t /*offset*/, size_t /*total_length*/) {
  10102. return content_receiver(data, data_length);
  10103. };
  10104. req.download_progress = std::move(progress);
  10105. if (max_timeout_msec_ > 0) {
  10106. req.start_time_ = std::chrono::steady_clock::now();
  10107. }
  10108. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10109. return send_(std::move(req));
  10110. }
  10111. inline Result ClientImpl::Patch(const std::string &path) {
  10112. return Patch(path, std::string(), std::string());
  10113. }
  10114. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10115. UploadProgress progress) {
  10116. return Patch(path, headers, nullptr, 0, std::string(), progress);
  10117. }
  10118. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  10119. size_t content_length,
  10120. const std::string &content_type,
  10121. UploadProgress progress) {
  10122. return Patch(path, Headers(), body, content_length, content_type, progress);
  10123. }
  10124. inline Result ClientImpl::Patch(const std::string &path,
  10125. const std::string &body,
  10126. const std::string &content_type,
  10127. UploadProgress progress) {
  10128. return Patch(path, Headers(), body, content_type, progress);
  10129. }
  10130. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  10131. return Patch(path, Headers(), params);
  10132. }
  10133. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10134. ContentProvider content_provider,
  10135. const std::string &content_type,
  10136. UploadProgress progress) {
  10137. return Patch(path, Headers(), content_length, std::move(content_provider),
  10138. content_type, progress);
  10139. }
  10140. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10141. ContentProvider content_provider,
  10142. const std::string &content_type,
  10143. ContentReceiver content_receiver,
  10144. UploadProgress progress) {
  10145. return Patch(path, Headers(), content_length, std::move(content_provider),
  10146. content_type, std::move(content_receiver), progress);
  10147. }
  10148. inline Result ClientImpl::Patch(const std::string &path,
  10149. ContentProviderWithoutLength content_provider,
  10150. const std::string &content_type,
  10151. UploadProgress progress) {
  10152. return Patch(path, Headers(), std::move(content_provider), content_type,
  10153. progress);
  10154. }
  10155. inline Result ClientImpl::Patch(const std::string &path,
  10156. ContentProviderWithoutLength content_provider,
  10157. const std::string &content_type,
  10158. ContentReceiver content_receiver,
  10159. UploadProgress progress) {
  10160. return Patch(path, Headers(), std::move(content_provider), content_type,
  10161. std::move(content_receiver), progress);
  10162. }
  10163. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10164. const Params &params) {
  10165. auto query = detail::params_to_query_str(params);
  10166. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  10167. }
  10168. inline Result ClientImpl::Patch(const std::string &path,
  10169. const UploadFormDataItems &items,
  10170. UploadProgress progress) {
  10171. return Patch(path, Headers(), items, progress);
  10172. }
  10173. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10174. const UploadFormDataItems &items,
  10175. UploadProgress progress) {
  10176. const auto &boundary = detail::make_multipart_data_boundary();
  10177. const auto &content_type =
  10178. detail::serialize_multipart_formdata_get_content_type(boundary);
  10179. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10180. return Patch(path, headers, body, content_type, progress);
  10181. }
  10182. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10183. const UploadFormDataItems &items,
  10184. const std::string &boundary,
  10185. UploadProgress progress) {
  10186. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10187. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10188. }
  10189. const auto &content_type =
  10190. detail::serialize_multipart_formdata_get_content_type(boundary);
  10191. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10192. return Patch(path, headers, body, content_type, progress);
  10193. }
  10194. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10195. const char *body, size_t content_length,
  10196. const std::string &content_type,
  10197. UploadProgress progress) {
  10198. return send_with_content_provider_and_receiver(
  10199. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  10200. content_type, nullptr, progress);
  10201. }
  10202. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10203. const std::string &body,
  10204. const std::string &content_type,
  10205. UploadProgress progress) {
  10206. return send_with_content_provider_and_receiver(
  10207. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  10208. content_type, nullptr, progress);
  10209. }
  10210. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10211. size_t content_length,
  10212. ContentProvider content_provider,
  10213. const std::string &content_type,
  10214. UploadProgress progress) {
  10215. return send_with_content_provider_and_receiver(
  10216. "PATCH", path, headers, nullptr, content_length,
  10217. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10218. }
  10219. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10220. size_t content_length,
  10221. ContentProvider content_provider,
  10222. const std::string &content_type,
  10223. ContentReceiver content_receiver,
  10224. UploadProgress progress) {
  10225. return send_with_content_provider_and_receiver(
  10226. "PATCH", path, headers, nullptr, content_length,
  10227. std::move(content_provider), nullptr, content_type,
  10228. std::move(content_receiver), progress);
  10229. }
  10230. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10231. ContentProviderWithoutLength content_provider,
  10232. const std::string &content_type,
  10233. UploadProgress progress) {
  10234. return send_with_content_provider_and_receiver(
  10235. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10236. content_type, nullptr, progress);
  10237. }
  10238. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10239. ContentProviderWithoutLength content_provider,
  10240. const std::string &content_type,
  10241. ContentReceiver content_receiver,
  10242. UploadProgress progress) {
  10243. return send_with_content_provider_and_receiver(
  10244. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10245. content_type, std::move(content_receiver), progress);
  10246. }
  10247. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10248. const UploadFormDataItems &items,
  10249. const FormDataProviderItems &provider_items,
  10250. UploadProgress progress) {
  10251. const auto &boundary = detail::make_multipart_data_boundary();
  10252. const auto &content_type =
  10253. detail::serialize_multipart_formdata_get_content_type(boundary);
  10254. return send_with_content_provider_and_receiver(
  10255. "PATCH", path, headers, nullptr, 0, nullptr,
  10256. get_multipart_content_provider(boundary, items, provider_items),
  10257. content_type, nullptr, progress);
  10258. }
  10259. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10260. const std::string &body,
  10261. const std::string &content_type,
  10262. ContentReceiver content_receiver,
  10263. DownloadProgress progress) {
  10264. Request req;
  10265. req.method = "PATCH";
  10266. req.path = path;
  10267. req.headers = headers;
  10268. req.body = body;
  10269. req.content_receiver =
  10270. [content_receiver](const char *data, size_t data_length,
  10271. size_t /*offset*/, size_t /*total_length*/) {
  10272. return content_receiver(data, data_length);
  10273. };
  10274. req.download_progress = std::move(progress);
  10275. if (max_timeout_msec_ > 0) {
  10276. req.start_time_ = std::chrono::steady_clock::now();
  10277. }
  10278. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10279. return send_(std::move(req));
  10280. }
  10281. inline Result ClientImpl::Delete(const std::string &path,
  10282. DownloadProgress progress) {
  10283. return Delete(path, Headers(), std::string(), std::string(), progress);
  10284. }
  10285. inline Result ClientImpl::Delete(const std::string &path,
  10286. const Headers &headers,
  10287. DownloadProgress progress) {
  10288. return Delete(path, headers, std::string(), std::string(), progress);
  10289. }
  10290. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  10291. size_t content_length,
  10292. const std::string &content_type,
  10293. DownloadProgress progress) {
  10294. return Delete(path, Headers(), body, content_length, content_type, progress);
  10295. }
  10296. inline Result ClientImpl::Delete(const std::string &path,
  10297. const std::string &body,
  10298. const std::string &content_type,
  10299. DownloadProgress progress) {
  10300. return Delete(path, Headers(), body.data(), body.size(), content_type,
  10301. progress);
  10302. }
  10303. inline Result ClientImpl::Delete(const std::string &path,
  10304. const Headers &headers,
  10305. const std::string &body,
  10306. const std::string &content_type,
  10307. DownloadProgress progress) {
  10308. return Delete(path, headers, body.data(), body.size(), content_type,
  10309. progress);
  10310. }
  10311. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  10312. DownloadProgress progress) {
  10313. return Delete(path, Headers(), params, progress);
  10314. }
  10315. inline Result ClientImpl::Delete(const std::string &path,
  10316. const Headers &headers, const Params &params,
  10317. DownloadProgress progress) {
  10318. auto query = detail::params_to_query_str(params);
  10319. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  10320. progress);
  10321. }
  10322. inline Result ClientImpl::Delete(const std::string &path,
  10323. const Headers &headers, const char *body,
  10324. size_t content_length,
  10325. const std::string &content_type,
  10326. DownloadProgress progress) {
  10327. Request req;
  10328. req.method = "DELETE";
  10329. req.headers = headers;
  10330. req.path = path;
  10331. req.download_progress = std::move(progress);
  10332. if (max_timeout_msec_ > 0) {
  10333. req.start_time_ = std::chrono::steady_clock::now();
  10334. }
  10335. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10336. req.body.assign(body, content_length);
  10337. return send_(std::move(req));
  10338. }
  10339. inline Result ClientImpl::Options(const std::string &path) {
  10340. return Options(path, Headers());
  10341. }
  10342. inline Result ClientImpl::Options(const std::string &path,
  10343. const Headers &headers) {
  10344. Request req;
  10345. req.method = "OPTIONS";
  10346. req.headers = headers;
  10347. req.path = path;
  10348. if (max_timeout_msec_ > 0) {
  10349. req.start_time_ = std::chrono::steady_clock::now();
  10350. }
  10351. return send_(std::move(req));
  10352. }
  10353. inline void ClientImpl::stop() {
  10354. std::lock_guard<std::mutex> guard(socket_mutex_);
  10355. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  10356. // do is to shutdown_socket, so that threads using this socket suddenly
  10357. // discover they can't read/write any more and error out. Everything else
  10358. // (closing the socket, shutting ssl down) is unsafe because these actions
  10359. // are not thread-safe.
  10360. if (socket_requests_in_flight_ > 0) {
  10361. shutdown_socket(socket_);
  10362. // Aside from that, we set a flag for the socket to be closed when we're
  10363. // done.
  10364. socket_should_be_closed_when_request_is_done_ = true;
  10365. return;
  10366. }
  10367. // Otherwise, still holding the mutex, we can shut everything down ourselves
  10368. shutdown_ssl(socket_, true);
  10369. shutdown_socket(socket_);
  10370. close_socket(socket_);
  10371. }
  10372. inline std::string ClientImpl::host() const { return host_; }
  10373. inline int ClientImpl::port() const { return port_; }
  10374. inline size_t ClientImpl::is_socket_open() const {
  10375. std::lock_guard<std::mutex> guard(socket_mutex_);
  10376. return socket_.is_open();
  10377. }
  10378. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  10379. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  10380. connection_timeout_sec_ = sec;
  10381. connection_timeout_usec_ = usec;
  10382. }
  10383. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  10384. read_timeout_sec_ = sec;
  10385. read_timeout_usec_ = usec;
  10386. }
  10387. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  10388. write_timeout_sec_ = sec;
  10389. write_timeout_usec_ = usec;
  10390. }
  10391. inline void ClientImpl::set_max_timeout(time_t msec) {
  10392. max_timeout_msec_ = msec;
  10393. }
  10394. inline void ClientImpl::set_basic_auth(const std::string &username,
  10395. const std::string &password) {
  10396. basic_auth_username_ = username;
  10397. basic_auth_password_ = password;
  10398. }
  10399. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  10400. bearer_token_auth_token_ = token;
  10401. }
  10402. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10403. inline void ClientImpl::set_digest_auth(const std::string &username,
  10404. const std::string &password) {
  10405. digest_auth_username_ = username;
  10406. digest_auth_password_ = password;
  10407. }
  10408. #endif
  10409. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  10410. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  10411. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  10412. inline void
  10413. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  10414. addr_map_ = std::move(addr_map);
  10415. }
  10416. inline void ClientImpl::set_default_headers(Headers headers) {
  10417. default_headers_ = std::move(headers);
  10418. }
  10419. inline void ClientImpl::set_header_writer(
  10420. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  10421. header_writer_ = writer;
  10422. }
  10423. inline void ClientImpl::set_address_family(int family) {
  10424. address_family_ = family;
  10425. }
  10426. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  10427. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  10428. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  10429. socket_options_ = std::move(socket_options);
  10430. }
  10431. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  10432. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  10433. inline void ClientImpl::set_interface(const std::string &intf) {
  10434. interface_ = intf;
  10435. }
  10436. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  10437. proxy_host_ = host;
  10438. proxy_port_ = port;
  10439. }
  10440. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  10441. const std::string &password) {
  10442. proxy_basic_auth_username_ = username;
  10443. proxy_basic_auth_password_ = password;
  10444. }
  10445. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  10446. proxy_bearer_token_auth_token_ = token;
  10447. }
  10448. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10449. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  10450. const std::string &password) {
  10451. proxy_digest_auth_username_ = username;
  10452. proxy_digest_auth_password_ = password;
  10453. }
  10454. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  10455. const std::string &ca_cert_dir_path) {
  10456. ca_cert_file_path_ = ca_cert_file_path;
  10457. ca_cert_dir_path_ = ca_cert_dir_path;
  10458. }
  10459. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  10460. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  10461. ca_cert_store_ = ca_cert_store;
  10462. }
  10463. }
  10464. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  10465. std::size_t size) const {
  10466. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  10467. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  10468. if (!mem) { return nullptr; }
  10469. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  10470. if (!inf) { return nullptr; }
  10471. auto cts = X509_STORE_new();
  10472. if (cts) {
  10473. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  10474. auto itmp = sk_X509_INFO_value(inf, i);
  10475. if (!itmp) { continue; }
  10476. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  10477. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  10478. }
  10479. }
  10480. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  10481. return cts;
  10482. }
  10483. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  10484. server_certificate_verification_ = enabled;
  10485. }
  10486. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  10487. server_hostname_verification_ = enabled;
  10488. }
  10489. inline void ClientImpl::set_server_certificate_verifier(
  10490. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  10491. server_certificate_verifier_ = verifier;
  10492. }
  10493. #endif
  10494. inline void ClientImpl::set_logger(Logger logger) {
  10495. logger_ = std::move(logger);
  10496. }
  10497. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  10498. error_logger_ = std::move(error_logger);
  10499. }
  10500. /*
  10501. * SSL Implementation
  10502. */
  10503. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10504. namespace detail {
  10505. inline bool is_ip_address(const std::string &host) {
  10506. struct in_addr addr4;
  10507. struct in6_addr addr6;
  10508. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  10509. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  10510. }
  10511. template <typename U, typename V>
  10512. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  10513. U SSL_connect_or_accept, V setup) {
  10514. SSL *ssl = nullptr;
  10515. {
  10516. std::lock_guard<std::mutex> guard(ctx_mutex);
  10517. ssl = SSL_new(ctx);
  10518. }
  10519. if (ssl) {
  10520. set_nonblocking(sock, true);
  10521. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  10522. BIO_set_nbio(bio, 1);
  10523. SSL_set_bio(ssl, bio, bio);
  10524. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  10525. SSL_shutdown(ssl);
  10526. {
  10527. std::lock_guard<std::mutex> guard(ctx_mutex);
  10528. SSL_free(ssl);
  10529. }
  10530. set_nonblocking(sock, false);
  10531. return nullptr;
  10532. }
  10533. BIO_set_nbio(bio, 0);
  10534. set_nonblocking(sock, false);
  10535. }
  10536. return ssl;
  10537. }
  10538. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock,
  10539. bool shutdown_gracefully) {
  10540. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  10541. // the remote has closed the network connection
  10542. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  10543. // best-efforts.
  10544. if (shutdown_gracefully) {
  10545. (void)(sock);
  10546. // SSL_shutdown() returns 0 on first call (indicating close_notify alert
  10547. // sent) and 1 on subsequent call (indicating close_notify alert received)
  10548. if (SSL_shutdown(ssl) == 0) {
  10549. // Expected to return 1, but even if it doesn't, we free ssl
  10550. SSL_shutdown(ssl);
  10551. }
  10552. }
  10553. std::lock_guard<std::mutex> guard(ctx_mutex);
  10554. SSL_free(ssl);
  10555. }
  10556. template <typename U>
  10557. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  10558. U ssl_connect_or_accept,
  10559. time_t timeout_sec, time_t timeout_usec,
  10560. int *ssl_error) {
  10561. auto res = 0;
  10562. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  10563. auto err = SSL_get_error(ssl, res);
  10564. switch (err) {
  10565. case SSL_ERROR_WANT_READ:
  10566. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  10567. break;
  10568. case SSL_ERROR_WANT_WRITE:
  10569. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  10570. break;
  10571. default: break;
  10572. }
  10573. if (ssl_error) { *ssl_error = err; }
  10574. return false;
  10575. }
  10576. return true;
  10577. }
  10578. template <typename T>
  10579. inline bool process_server_socket_ssl(
  10580. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  10581. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  10582. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  10583. time_t write_timeout_usec, T callback) {
  10584. return process_server_socket_core(
  10585. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  10586. [&](bool close_connection, bool &connection_closed) {
  10587. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  10588. write_timeout_sec, write_timeout_usec);
  10589. return callback(strm, close_connection, connection_closed);
  10590. });
  10591. }
  10592. template <typename T>
  10593. inline bool process_client_socket_ssl(
  10594. SSL *ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  10595. time_t write_timeout_sec, time_t write_timeout_usec,
  10596. time_t max_timeout_msec,
  10597. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  10598. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  10599. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  10600. start_time);
  10601. return callback(strm);
  10602. }
  10603. // SSL socket stream implementation
  10604. inline SSLSocketStream::SSLSocketStream(
  10605. socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec,
  10606. time_t write_timeout_sec, time_t write_timeout_usec,
  10607. time_t max_timeout_msec,
  10608. std::chrono::time_point<std::chrono::steady_clock> start_time)
  10609. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  10610. read_timeout_usec_(read_timeout_usec),
  10611. write_timeout_sec_(write_timeout_sec),
  10612. write_timeout_usec_(write_timeout_usec),
  10613. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  10614. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  10615. }
  10616. inline SSLSocketStream::~SSLSocketStream() = default;
  10617. inline bool SSLSocketStream::is_readable() const {
  10618. return SSL_pending(ssl_) > 0;
  10619. }
  10620. inline bool SSLSocketStream::wait_readable() const {
  10621. if (max_timeout_msec_ <= 0) {
  10622. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10623. }
  10624. time_t read_timeout_sec;
  10625. time_t read_timeout_usec;
  10626. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  10627. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  10628. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  10629. }
  10630. inline bool SSLSocketStream::wait_writable() const {
  10631. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  10632. is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_);
  10633. }
  10634. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  10635. if (SSL_pending(ssl_) > 0) {
  10636. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  10637. if (ret == 0) { error_ = Error::ConnectionClosed; }
  10638. return ret;
  10639. } else if (wait_readable()) {
  10640. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  10641. if (ret < 0) {
  10642. auto err = SSL_get_error(ssl_, ret);
  10643. auto n = 1000;
  10644. #ifdef _WIN32
  10645. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  10646. (err == SSL_ERROR_SYSCALL &&
  10647. WSAGetLastError() == WSAETIMEDOUT))) {
  10648. #else
  10649. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  10650. #endif
  10651. if (SSL_pending(ssl_) > 0) {
  10652. return SSL_read(ssl_, ptr, static_cast<int>(size));
  10653. } else if (wait_readable()) {
  10654. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10655. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  10656. if (ret >= 0) { return ret; }
  10657. err = SSL_get_error(ssl_, ret);
  10658. } else {
  10659. break;
  10660. }
  10661. }
  10662. assert(ret < 0);
  10663. } else if (ret == 0) {
  10664. error_ = Error::ConnectionClosed;
  10665. }
  10666. return ret;
  10667. } else {
  10668. error_ = Error::Timeout;
  10669. return -1;
  10670. }
  10671. }
  10672. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  10673. if (wait_writable()) {
  10674. auto handle_size = static_cast<int>(
  10675. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  10676. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  10677. if (ret < 0) {
  10678. auto err = SSL_get_error(ssl_, ret);
  10679. auto n = 1000;
  10680. #ifdef _WIN32
  10681. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  10682. (err == SSL_ERROR_SYSCALL &&
  10683. WSAGetLastError() == WSAETIMEDOUT))) {
  10684. #else
  10685. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  10686. #endif
  10687. if (wait_writable()) {
  10688. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10689. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  10690. if (ret >= 0) { return ret; }
  10691. err = SSL_get_error(ssl_, ret);
  10692. } else {
  10693. break;
  10694. }
  10695. }
  10696. assert(ret < 0);
  10697. }
  10698. return ret;
  10699. }
  10700. return -1;
  10701. }
  10702. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  10703. int &port) const {
  10704. detail::get_remote_ip_and_port(sock_, ip, port);
  10705. }
  10706. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  10707. int &port) const {
  10708. detail::get_local_ip_and_port(sock_, ip, port);
  10709. }
  10710. inline socket_t SSLSocketStream::socket() const { return sock_; }
  10711. inline time_t SSLSocketStream::duration() const {
  10712. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10713. std::chrono::steady_clock::now() - start_time_)
  10714. .count();
  10715. }
  10716. } // namespace detail
  10717. // SSL HTTP server implementation
  10718. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  10719. const char *client_ca_cert_file_path,
  10720. const char *client_ca_cert_dir_path,
  10721. const char *private_key_password) {
  10722. ctx_ = SSL_CTX_new(TLS_server_method());
  10723. if (ctx_) {
  10724. SSL_CTX_set_options(ctx_,
  10725. SSL_OP_NO_COMPRESSION |
  10726. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  10727. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  10728. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  10729. SSL_CTX_set_default_passwd_cb_userdata(
  10730. ctx_,
  10731. reinterpret_cast<void *>(const_cast<char *>(private_key_password)));
  10732. }
  10733. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  10734. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  10735. 1 ||
  10736. SSL_CTX_check_private_key(ctx_) != 1) {
  10737. last_ssl_error_ = static_cast<int>(ERR_get_error());
  10738. SSL_CTX_free(ctx_);
  10739. ctx_ = nullptr;
  10740. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  10741. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  10742. client_ca_cert_dir_path);
  10743. // Set client CA list to be sent to clients during TLS handshake
  10744. if (client_ca_cert_file_path) {
  10745. auto ca_list = SSL_load_client_CA_file(client_ca_cert_file_path);
  10746. if (ca_list != nullptr) {
  10747. SSL_CTX_set_client_CA_list(ctx_, ca_list);
  10748. } else {
  10749. // Failed to load client CA list, but we continue since
  10750. // SSL_CTX_load_verify_locations already succeeded and
  10751. // certificate verification will still work
  10752. last_ssl_error_ = static_cast<int>(ERR_get_error());
  10753. }
  10754. }
  10755. SSL_CTX_set_verify(
  10756. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  10757. }
  10758. }
  10759. }
  10760. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  10761. X509_STORE *client_ca_cert_store) {
  10762. ctx_ = SSL_CTX_new(TLS_server_method());
  10763. if (ctx_) {
  10764. SSL_CTX_set_options(ctx_,
  10765. SSL_OP_NO_COMPRESSION |
  10766. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  10767. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  10768. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  10769. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  10770. SSL_CTX_free(ctx_);
  10771. ctx_ = nullptr;
  10772. } else if (client_ca_cert_store) {
  10773. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  10774. // Extract CA names from the store and set them as the client CA list
  10775. auto ca_list = extract_ca_names_from_x509_store(client_ca_cert_store);
  10776. if (ca_list) {
  10777. SSL_CTX_set_client_CA_list(ctx_, ca_list);
  10778. } else {
  10779. // Failed to extract CA names, record the error
  10780. last_ssl_error_ = static_cast<int>(ERR_get_error());
  10781. }
  10782. SSL_CTX_set_verify(
  10783. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  10784. }
  10785. }
  10786. }
  10787. inline SSLServer::SSLServer(
  10788. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  10789. ctx_ = SSL_CTX_new(TLS_method());
  10790. if (ctx_) {
  10791. if (!setup_ssl_ctx_callback(*ctx_)) {
  10792. SSL_CTX_free(ctx_);
  10793. ctx_ = nullptr;
  10794. }
  10795. }
  10796. }
  10797. inline SSLServer::~SSLServer() {
  10798. if (ctx_) { SSL_CTX_free(ctx_); }
  10799. }
  10800. inline bool SSLServer::is_valid() const { return ctx_; }
  10801. inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  10802. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  10803. X509_STORE *client_ca_cert_store) {
  10804. std::lock_guard<std::mutex> guard(ctx_mutex_);
  10805. SSL_CTX_use_certificate(ctx_, cert);
  10806. SSL_CTX_use_PrivateKey(ctx_, private_key);
  10807. if (client_ca_cert_store != nullptr) {
  10808. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  10809. }
  10810. }
  10811. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  10812. auto ssl = detail::ssl_new(
  10813. sock, ctx_, ctx_mutex_,
  10814. [&](SSL *ssl2) {
  10815. return detail::ssl_connect_or_accept_nonblocking(
  10816. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_,
  10817. &last_ssl_error_);
  10818. },
  10819. [](SSL * /*ssl2*/) { return true; });
  10820. auto ret = false;
  10821. if (ssl) {
  10822. std::string remote_addr;
  10823. int remote_port = 0;
  10824. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10825. std::string local_addr;
  10826. int local_port = 0;
  10827. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10828. ret = detail::process_server_socket_ssl(
  10829. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10830. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10831. write_timeout_usec_,
  10832. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10833. return process_request(strm, remote_addr, remote_port, local_addr,
  10834. local_port, close_connection,
  10835. connection_closed,
  10836. [&](Request &req) { req.ssl = ssl; });
  10837. });
  10838. // Shutdown gracefully if the result seemed successful, non-gracefully if
  10839. // the connection appeared to be closed.
  10840. const bool shutdown_gracefully = ret;
  10841. detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
  10842. }
  10843. detail::shutdown_socket(sock);
  10844. detail::close_socket(sock);
  10845. return ret;
  10846. }
  10847. inline STACK_OF(X509_NAME) * SSLServer::extract_ca_names_from_x509_store(
  10848. X509_STORE *store) {
  10849. if (!store) { return nullptr; }
  10850. auto ca_list = sk_X509_NAME_new_null();
  10851. if (!ca_list) { return nullptr; }
  10852. // Get all objects from the store
  10853. auto objs = X509_STORE_get0_objects(store);
  10854. if (!objs) {
  10855. sk_X509_NAME_free(ca_list);
  10856. return nullptr;
  10857. }
  10858. // Iterate through objects and extract certificate subject names
  10859. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  10860. auto obj = sk_X509_OBJECT_value(objs, i);
  10861. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  10862. auto cert = X509_OBJECT_get0_X509(obj);
  10863. if (cert) {
  10864. auto subject = X509_get_subject_name(cert);
  10865. if (subject) {
  10866. auto name_dup = X509_NAME_dup(subject);
  10867. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  10868. }
  10869. }
  10870. }
  10871. }
  10872. // If no names were extracted, free the list and return nullptr
  10873. if (sk_X509_NAME_num(ca_list) == 0) {
  10874. sk_X509_NAME_free(ca_list);
  10875. return nullptr;
  10876. }
  10877. return ca_list;
  10878. }
  10879. // SSL HTTP client implementation
  10880. inline SSLClient::SSLClient(const std::string &host)
  10881. : SSLClient(host, 443, std::string(), std::string()) {}
  10882. inline SSLClient::SSLClient(const std::string &host, int port)
  10883. : SSLClient(host, port, std::string(), std::string()) {}
  10884. inline SSLClient::SSLClient(const std::string &host, int port,
  10885. const std::string &client_cert_path,
  10886. const std::string &client_key_path,
  10887. const std::string &private_key_password)
  10888. : ClientImpl(host, port, client_cert_path, client_key_path) {
  10889. ctx_ = SSL_CTX_new(TLS_client_method());
  10890. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  10891. detail::split(&host_[0], &host_[host_.size()], '.',
  10892. [&](const char *b, const char *e) {
  10893. host_components_.emplace_back(b, e);
  10894. });
  10895. if (!client_cert_path.empty() && !client_key_path.empty()) {
  10896. if (!private_key_password.empty()) {
  10897. SSL_CTX_set_default_passwd_cb_userdata(
  10898. ctx_, reinterpret_cast<void *>(
  10899. const_cast<char *>(private_key_password.c_str())));
  10900. }
  10901. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  10902. SSL_FILETYPE_PEM) != 1 ||
  10903. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  10904. SSL_FILETYPE_PEM) != 1) {
  10905. last_openssl_error_ = ERR_get_error();
  10906. SSL_CTX_free(ctx_);
  10907. ctx_ = nullptr;
  10908. }
  10909. }
  10910. }
  10911. inline SSLClient::SSLClient(const std::string &host, int port,
  10912. X509 *client_cert, EVP_PKEY *client_key,
  10913. const std::string &private_key_password)
  10914. : ClientImpl(host, port) {
  10915. ctx_ = SSL_CTX_new(TLS_client_method());
  10916. detail::split(&host_[0], &host_[host_.size()], '.',
  10917. [&](const char *b, const char *e) {
  10918. host_components_.emplace_back(b, e);
  10919. });
  10920. if (client_cert != nullptr && client_key != nullptr) {
  10921. if (!private_key_password.empty()) {
  10922. SSL_CTX_set_default_passwd_cb_userdata(
  10923. ctx_, reinterpret_cast<void *>(
  10924. const_cast<char *>(private_key_password.c_str())));
  10925. }
  10926. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  10927. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  10928. last_openssl_error_ = ERR_get_error();
  10929. SSL_CTX_free(ctx_);
  10930. ctx_ = nullptr;
  10931. }
  10932. }
  10933. }
  10934. inline SSLClient::~SSLClient() {
  10935. if (ctx_) { SSL_CTX_free(ctx_); }
  10936. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  10937. // base function rather than the derived function once we get to the
  10938. // base class destructor, and won't free the SSL (causing a leak).
  10939. shutdown_ssl_impl(socket_, true);
  10940. }
  10941. inline bool SSLClient::is_valid() const { return ctx_; }
  10942. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  10943. if (ca_cert_store) {
  10944. if (ctx_) {
  10945. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  10946. // Free memory allocated for old cert and use new store
  10947. // `ca_cert_store`
  10948. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  10949. ca_cert_store_ = ca_cert_store;
  10950. }
  10951. } else {
  10952. X509_STORE_free(ca_cert_store);
  10953. }
  10954. }
  10955. }
  10956. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  10957. std::size_t size) {
  10958. set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
  10959. }
  10960. inline long SSLClient::get_openssl_verify_result() const {
  10961. return verify_result_;
  10962. }
  10963. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  10964. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  10965. if (!is_valid()) {
  10966. error = Error::SSLConnection;
  10967. return false;
  10968. }
  10969. return ClientImpl::create_and_connect_socket(socket, error);
  10970. }
  10971. // Assumes that socket_mutex_ is locked and that there are no requests in
  10972. // flight
  10973. inline bool SSLClient::connect_with_proxy(
  10974. Socket &socket,
  10975. std::chrono::time_point<std::chrono::steady_clock> start_time,
  10976. Response &res, bool &success, Error &error) {
  10977. success = true;
  10978. Response proxy_res;
  10979. if (!detail::process_client_socket(
  10980. socket.sock, read_timeout_sec_, read_timeout_usec_,
  10981. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  10982. start_time, [&](Stream &strm) {
  10983. Request req2;
  10984. req2.method = "CONNECT";
  10985. req2.path =
  10986. detail::make_host_and_port_string_always_port(host_, port_);
  10987. if (max_timeout_msec_ > 0) {
  10988. req2.start_time_ = std::chrono::steady_clock::now();
  10989. }
  10990. return process_request(strm, req2, proxy_res, false, error);
  10991. })) {
  10992. // Thread-safe to close everything because we are assuming there are no
  10993. // requests in flight
  10994. shutdown_ssl(socket, true);
  10995. shutdown_socket(socket);
  10996. close_socket(socket);
  10997. success = false;
  10998. return false;
  10999. }
  11000. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  11001. if (!proxy_digest_auth_username_.empty() &&
  11002. !proxy_digest_auth_password_.empty()) {
  11003. std::map<std::string, std::string> auth;
  11004. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  11005. // Close the current socket and create a new one for the authenticated
  11006. // request
  11007. shutdown_ssl(socket, true);
  11008. shutdown_socket(socket);
  11009. close_socket(socket);
  11010. // Create a new socket for the authenticated CONNECT request
  11011. if (!ensure_socket_connection(socket, error)) {
  11012. success = false;
  11013. output_error_log(error, nullptr);
  11014. return false;
  11015. }
  11016. proxy_res = Response();
  11017. if (!detail::process_client_socket(
  11018. socket.sock, read_timeout_sec_, read_timeout_usec_,
  11019. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  11020. start_time, [&](Stream &strm) {
  11021. Request req3;
  11022. req3.method = "CONNECT";
  11023. req3.path = detail::make_host_and_port_string_always_port(
  11024. host_, port_);
  11025. req3.headers.insert(detail::make_digest_authentication_header(
  11026. req3, auth, 1, detail::random_string(10),
  11027. proxy_digest_auth_username_, proxy_digest_auth_password_,
  11028. true));
  11029. if (max_timeout_msec_ > 0) {
  11030. req3.start_time_ = std::chrono::steady_clock::now();
  11031. }
  11032. return process_request(strm, req3, proxy_res, false, error);
  11033. })) {
  11034. // Thread-safe to close everything because we are assuming there are
  11035. // no requests in flight
  11036. shutdown_ssl(socket, true);
  11037. shutdown_socket(socket);
  11038. close_socket(socket);
  11039. success = false;
  11040. return false;
  11041. }
  11042. }
  11043. }
  11044. }
  11045. // If status code is not 200, proxy request is failed.
  11046. // Set error to ProxyConnection and return proxy response
  11047. // as the response of the request
  11048. if (proxy_res.status != StatusCode::OK_200) {
  11049. error = Error::ProxyConnection;
  11050. output_error_log(error, nullptr);
  11051. res = std::move(proxy_res);
  11052. // Thread-safe to close everything because we are assuming there are
  11053. // no requests in flight
  11054. shutdown_ssl(socket, true);
  11055. shutdown_socket(socket);
  11056. close_socket(socket);
  11057. return false;
  11058. }
  11059. return true;
  11060. }
  11061. inline bool SSLClient::load_certs() {
  11062. auto ret = true;
  11063. std::call_once(initialize_cert_, [&]() {
  11064. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11065. if (!ca_cert_file_path_.empty()) {
  11066. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  11067. nullptr)) {
  11068. last_openssl_error_ = ERR_get_error();
  11069. ret = false;
  11070. }
  11071. } else if (!ca_cert_dir_path_.empty()) {
  11072. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  11073. ca_cert_dir_path_.c_str())) {
  11074. last_openssl_error_ = ERR_get_error();
  11075. ret = false;
  11076. }
  11077. } else if (!ca_cert_store_) {
  11078. auto loaded = false;
  11079. #ifdef _WIN32
  11080. loaded =
  11081. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  11082. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  11083. loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
  11084. #endif // _WIN32
  11085. if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }
  11086. }
  11087. });
  11088. return ret;
  11089. }
  11090. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  11091. auto ssl = detail::ssl_new(
  11092. socket.sock, ctx_, ctx_mutex_,
  11093. [&](SSL *ssl2) {
  11094. if (server_certificate_verification_) {
  11095. if (!load_certs()) {
  11096. error = Error::SSLLoadingCerts;
  11097. output_error_log(error, nullptr);
  11098. return false;
  11099. }
  11100. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  11101. }
  11102. if (!detail::ssl_connect_or_accept_nonblocking(
  11103. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  11104. connection_timeout_usec_, &last_ssl_error_)) {
  11105. error = Error::SSLConnection;
  11106. output_error_log(error, nullptr);
  11107. return false;
  11108. }
  11109. if (server_certificate_verification_) {
  11110. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  11111. if (server_certificate_verifier_) {
  11112. verification_status = server_certificate_verifier_(ssl2);
  11113. }
  11114. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  11115. last_openssl_error_ = ERR_get_error();
  11116. error = Error::SSLServerVerification;
  11117. output_error_log(error, nullptr);
  11118. return false;
  11119. }
  11120. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  11121. verify_result_ = SSL_get_verify_result(ssl2);
  11122. if (verify_result_ != X509_V_OK) {
  11123. last_openssl_error_ = static_cast<unsigned long>(verify_result_);
  11124. error = Error::SSLServerVerification;
  11125. output_error_log(error, nullptr);
  11126. return false;
  11127. }
  11128. auto server_cert = SSL_get1_peer_certificate(ssl2);
  11129. auto se = detail::scope_exit([&] { X509_free(server_cert); });
  11130. if (server_cert == nullptr) {
  11131. last_openssl_error_ = ERR_get_error();
  11132. error = Error::SSLServerVerification;
  11133. output_error_log(error, nullptr);
  11134. return false;
  11135. }
  11136. if (server_hostname_verification_) {
  11137. if (!verify_host(server_cert)) {
  11138. last_openssl_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  11139. error = Error::SSLServerHostnameVerification;
  11140. output_error_log(error, nullptr);
  11141. return false;
  11142. }
  11143. }
  11144. }
  11145. }
  11146. return true;
  11147. },
  11148. [&](SSL *ssl2) {
  11149. // Set SNI only if host is not IP address
  11150. if (!detail::is_ip_address(host_)) {
  11151. #if defined(OPENSSL_IS_BORINGSSL)
  11152. SSL_set_tlsext_host_name(ssl2, host_.c_str());
  11153. #else
  11154. // NOTE: Direct call instead of using the OpenSSL macro to suppress
  11155. // -Wold-style-cast warning
  11156. SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME,
  11157. TLSEXT_NAMETYPE_host_name,
  11158. static_cast<void *>(const_cast<char *>(host_.c_str())));
  11159. #endif
  11160. }
  11161. return true;
  11162. });
  11163. if (ssl) {
  11164. socket.ssl = ssl;
  11165. return true;
  11166. }
  11167. if (ctx_ == nullptr) {
  11168. error = Error::SSLConnection;
  11169. last_openssl_error_ = ERR_get_error();
  11170. }
  11171. shutdown_socket(socket);
  11172. close_socket(socket);
  11173. return false;
  11174. }
  11175. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  11176. shutdown_ssl_impl(socket, shutdown_gracefully);
  11177. }
  11178. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  11179. bool shutdown_gracefully) {
  11180. if (socket.sock == INVALID_SOCKET) {
  11181. assert(socket.ssl == nullptr);
  11182. return;
  11183. }
  11184. if (socket.ssl) {
  11185. detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock,
  11186. shutdown_gracefully);
  11187. socket.ssl = nullptr;
  11188. }
  11189. assert(socket.ssl == nullptr);
  11190. }
  11191. inline bool SSLClient::process_socket(
  11192. const Socket &socket,
  11193. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11194. std::function<bool(Stream &strm)> callback) {
  11195. assert(socket.ssl);
  11196. return detail::process_client_socket_ssl(
  11197. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  11198. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  11199. std::move(callback));
  11200. }
  11201. inline bool SSLClient::is_ssl() const { return true; }
  11202. inline bool SSLClient::verify_host(X509 *server_cert) const {
  11203. /* Quote from RFC2818 section 3.1 "Server Identity"
  11204. If a subjectAltName extension of type dNSName is present, that MUST
  11205. be used as the identity. Otherwise, the (most specific) Common Name
  11206. field in the Subject field of the certificate MUST be used. Although
  11207. the use of the Common Name is existing practice, it is deprecated and
  11208. Certification Authorities are encouraged to use the dNSName instead.
  11209. Matching is performed using the matching rules specified by
  11210. [RFC2459]. If more than one identity of a given type is present in
  11211. the certificate (e.g., more than one dNSName name, a match in any one
  11212. of the set is considered acceptable.) Names may contain the wildcard
  11213. character * which is considered to match any single domain name
  11214. component or component fragment. E.g., *.a.com matches foo.a.com but
  11215. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  11216. In some cases, the URI is specified as an IP address rather than a
  11217. hostname. In this case, the iPAddress subjectAltName must be present
  11218. in the certificate and must exactly match the IP in the URI.
  11219. */
  11220. return verify_host_with_subject_alt_name(server_cert) ||
  11221. verify_host_with_common_name(server_cert);
  11222. }
  11223. inline bool
  11224. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  11225. auto ret = false;
  11226. auto type = GEN_DNS;
  11227. struct in6_addr addr6 = {};
  11228. struct in_addr addr = {};
  11229. size_t addr_len = 0;
  11230. #ifndef __MINGW32__
  11231. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  11232. type = GEN_IPADD;
  11233. addr_len = sizeof(struct in6_addr);
  11234. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  11235. type = GEN_IPADD;
  11236. addr_len = sizeof(struct in_addr);
  11237. }
  11238. #endif
  11239. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  11240. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  11241. if (alt_names) {
  11242. auto dsn_matched = false;
  11243. auto ip_matched = false;
  11244. auto count = sk_GENERAL_NAME_num(alt_names);
  11245. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  11246. auto val = sk_GENERAL_NAME_value(alt_names, i);
  11247. if (!val || val->type != type) { continue; }
  11248. auto name =
  11249. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  11250. if (name == nullptr) { continue; }
  11251. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  11252. switch (type) {
  11253. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  11254. case GEN_IPADD:
  11255. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  11256. ip_matched = true;
  11257. }
  11258. break;
  11259. }
  11260. }
  11261. if (dsn_matched || ip_matched) { ret = true; }
  11262. }
  11263. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  11264. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  11265. return ret;
  11266. }
  11267. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  11268. const auto subject_name = X509_get_subject_name(server_cert);
  11269. if (subject_name != nullptr) {
  11270. char name[BUFSIZ];
  11271. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  11272. name, sizeof(name));
  11273. if (name_len != -1) {
  11274. return check_host_name(name, static_cast<size_t>(name_len));
  11275. }
  11276. }
  11277. return false;
  11278. }
  11279. inline bool SSLClient::check_host_name(const char *pattern,
  11280. size_t pattern_len) const {
  11281. // Exact match (case-insensitive)
  11282. if (host_.size() == pattern_len &&
  11283. detail::case_ignore::equal(host_, std::string(pattern, pattern_len))) {
  11284. return true;
  11285. }
  11286. // Wildcard match
  11287. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  11288. std::vector<std::string> pattern_components;
  11289. detail::split(&pattern[0], &pattern[pattern_len], '.',
  11290. [&](const char *b, const char *e) {
  11291. pattern_components.emplace_back(b, e);
  11292. });
  11293. if (host_components_.size() != pattern_components.size()) { return false; }
  11294. auto itr = pattern_components.begin();
  11295. for (const auto &h : host_components_) {
  11296. auto &p = *itr;
  11297. if (!httplib::detail::case_ignore::equal(p, h) && p != "*") {
  11298. bool partial_match = false;
  11299. if (!p.empty() && p[p.size() - 1] == '*') {
  11300. const auto prefix_length = p.size() - 1;
  11301. if (prefix_length == 0) {
  11302. partial_match = true;
  11303. } else if (h.size() >= prefix_length) {
  11304. partial_match =
  11305. std::equal(p.begin(),
  11306. p.begin() + static_cast<std::string::difference_type>(
  11307. prefix_length),
  11308. h.begin(), [](const char ca, const char cb) {
  11309. return httplib::detail::case_ignore::to_lower(ca) ==
  11310. httplib::detail::case_ignore::to_lower(cb);
  11311. });
  11312. }
  11313. }
  11314. if (!partial_match) { return false; }
  11315. }
  11316. ++itr;
  11317. }
  11318. return true;
  11319. }
  11320. #endif
  11321. // Universal client implementation
  11322. inline Client::Client(const std::string &scheme_host_port)
  11323. : Client(scheme_host_port, std::string(), std::string()) {}
  11324. inline Client::Client(const std::string &scheme_host_port,
  11325. const std::string &client_cert_path,
  11326. const std::string &client_key_path) {
  11327. const static std::regex re(
  11328. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  11329. std::smatch m;
  11330. if (std::regex_match(scheme_host_port, m, re)) {
  11331. auto scheme = m[1].str();
  11332. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11333. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  11334. #else
  11335. if (!scheme.empty() && scheme != "http") {
  11336. #endif
  11337. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11338. std::string msg = "'" + scheme + "' scheme is not supported.";
  11339. throw std::invalid_argument(msg);
  11340. #endif
  11341. return;
  11342. }
  11343. auto is_ssl = scheme == "https";
  11344. auto host = m[2].str();
  11345. if (host.empty()) { host = m[3].str(); }
  11346. auto port_str = m[4].str();
  11347. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  11348. if (is_ssl) {
  11349. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11350. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  11351. client_key_path);
  11352. is_ssl_ = is_ssl;
  11353. #endif
  11354. } else {
  11355. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  11356. client_key_path);
  11357. }
  11358. } else {
  11359. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  11360. // if port param below changes.
  11361. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  11362. client_cert_path, client_key_path);
  11363. }
  11364. } // namespace detail
  11365. inline Client::Client(const std::string &host, int port)
  11366. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  11367. inline Client::Client(const std::string &host, int port,
  11368. const std::string &client_cert_path,
  11369. const std::string &client_key_path)
  11370. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  11371. client_key_path)) {}
  11372. inline Client::~Client() = default;
  11373. inline bool Client::is_valid() const {
  11374. return cli_ != nullptr && cli_->is_valid();
  11375. }
  11376. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  11377. return cli_->Get(path, std::move(progress));
  11378. }
  11379. inline Result Client::Get(const std::string &path, const Headers &headers,
  11380. DownloadProgress progress) {
  11381. return cli_->Get(path, headers, std::move(progress));
  11382. }
  11383. inline Result Client::Get(const std::string &path,
  11384. ContentReceiver content_receiver,
  11385. DownloadProgress progress) {
  11386. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  11387. }
  11388. inline Result Client::Get(const std::string &path, const Headers &headers,
  11389. ContentReceiver content_receiver,
  11390. DownloadProgress progress) {
  11391. return cli_->Get(path, headers, std::move(content_receiver),
  11392. std::move(progress));
  11393. }
  11394. inline Result Client::Get(const std::string &path,
  11395. ResponseHandler response_handler,
  11396. ContentReceiver content_receiver,
  11397. DownloadProgress progress) {
  11398. return cli_->Get(path, std::move(response_handler),
  11399. std::move(content_receiver), std::move(progress));
  11400. }
  11401. inline Result Client::Get(const std::string &path, const Headers &headers,
  11402. ResponseHandler response_handler,
  11403. ContentReceiver content_receiver,
  11404. DownloadProgress progress) {
  11405. return cli_->Get(path, headers, std::move(response_handler),
  11406. std::move(content_receiver), std::move(progress));
  11407. }
  11408. inline Result Client::Get(const std::string &path, const Params &params,
  11409. const Headers &headers, DownloadProgress progress) {
  11410. return cli_->Get(path, params, headers, std::move(progress));
  11411. }
  11412. inline Result Client::Get(const std::string &path, const Params &params,
  11413. const Headers &headers,
  11414. ContentReceiver content_receiver,
  11415. DownloadProgress progress) {
  11416. return cli_->Get(path, params, headers, std::move(content_receiver),
  11417. std::move(progress));
  11418. }
  11419. inline Result Client::Get(const std::string &path, const Params &params,
  11420. const Headers &headers,
  11421. ResponseHandler response_handler,
  11422. ContentReceiver content_receiver,
  11423. DownloadProgress progress) {
  11424. return cli_->Get(path, params, headers, std::move(response_handler),
  11425. std::move(content_receiver), std::move(progress));
  11426. }
  11427. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  11428. inline Result Client::Head(const std::string &path, const Headers &headers) {
  11429. return cli_->Head(path, headers);
  11430. }
  11431. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  11432. inline Result Client::Post(const std::string &path, const Headers &headers) {
  11433. return cli_->Post(path, headers);
  11434. }
  11435. inline Result Client::Post(const std::string &path, const char *body,
  11436. size_t content_length,
  11437. const std::string &content_type,
  11438. UploadProgress progress) {
  11439. return cli_->Post(path, body, content_length, content_type, progress);
  11440. }
  11441. inline Result Client::Post(const std::string &path, const Headers &headers,
  11442. const char *body, size_t content_length,
  11443. const std::string &content_type,
  11444. UploadProgress progress) {
  11445. return cli_->Post(path, headers, body, content_length, content_type,
  11446. progress);
  11447. }
  11448. inline Result Client::Post(const std::string &path, const std::string &body,
  11449. const std::string &content_type,
  11450. UploadProgress progress) {
  11451. return cli_->Post(path, body, content_type, progress);
  11452. }
  11453. inline Result Client::Post(const std::string &path, const Headers &headers,
  11454. const std::string &body,
  11455. const std::string &content_type,
  11456. UploadProgress progress) {
  11457. return cli_->Post(path, headers, body, content_type, progress);
  11458. }
  11459. inline Result Client::Post(const std::string &path, size_t content_length,
  11460. ContentProvider content_provider,
  11461. const std::string &content_type,
  11462. UploadProgress progress) {
  11463. return cli_->Post(path, content_length, std::move(content_provider),
  11464. content_type, progress);
  11465. }
  11466. inline Result Client::Post(const std::string &path, size_t content_length,
  11467. ContentProvider content_provider,
  11468. const std::string &content_type,
  11469. ContentReceiver content_receiver,
  11470. UploadProgress progress) {
  11471. return cli_->Post(path, content_length, std::move(content_provider),
  11472. content_type, std::move(content_receiver), progress);
  11473. }
  11474. inline Result Client::Post(const std::string &path,
  11475. ContentProviderWithoutLength content_provider,
  11476. const std::string &content_type,
  11477. UploadProgress progress) {
  11478. return cli_->Post(path, std::move(content_provider), content_type, progress);
  11479. }
  11480. inline Result Client::Post(const std::string &path,
  11481. ContentProviderWithoutLength content_provider,
  11482. const std::string &content_type,
  11483. ContentReceiver content_receiver,
  11484. UploadProgress progress) {
  11485. return cli_->Post(path, std::move(content_provider), content_type,
  11486. std::move(content_receiver), progress);
  11487. }
  11488. inline Result Client::Post(const std::string &path, const Headers &headers,
  11489. size_t content_length,
  11490. ContentProvider content_provider,
  11491. const std::string &content_type,
  11492. UploadProgress progress) {
  11493. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11494. content_type, progress);
  11495. }
  11496. inline Result Client::Post(const std::string &path, const Headers &headers,
  11497. size_t content_length,
  11498. ContentProvider content_provider,
  11499. const std::string &content_type,
  11500. ContentReceiver content_receiver,
  11501. DownloadProgress progress) {
  11502. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11503. content_type, std::move(content_receiver), progress);
  11504. }
  11505. inline Result Client::Post(const std::string &path, const Headers &headers,
  11506. ContentProviderWithoutLength content_provider,
  11507. const std::string &content_type,
  11508. UploadProgress progress) {
  11509. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11510. progress);
  11511. }
  11512. inline Result Client::Post(const std::string &path, const Headers &headers,
  11513. ContentProviderWithoutLength content_provider,
  11514. const std::string &content_type,
  11515. ContentReceiver content_receiver,
  11516. DownloadProgress progress) {
  11517. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11518. std::move(content_receiver), progress);
  11519. }
  11520. inline Result Client::Post(const std::string &path, const Params &params) {
  11521. return cli_->Post(path, params);
  11522. }
  11523. inline Result Client::Post(const std::string &path, const Headers &headers,
  11524. const Params &params) {
  11525. return cli_->Post(path, headers, params);
  11526. }
  11527. inline Result Client::Post(const std::string &path,
  11528. const UploadFormDataItems &items,
  11529. UploadProgress progress) {
  11530. return cli_->Post(path, items, progress);
  11531. }
  11532. inline Result Client::Post(const std::string &path, const Headers &headers,
  11533. const UploadFormDataItems &items,
  11534. UploadProgress progress) {
  11535. return cli_->Post(path, headers, items, progress);
  11536. }
  11537. inline Result Client::Post(const std::string &path, const Headers &headers,
  11538. const UploadFormDataItems &items,
  11539. const std::string &boundary,
  11540. UploadProgress progress) {
  11541. return cli_->Post(path, headers, items, boundary, progress);
  11542. }
  11543. inline Result Client::Post(const std::string &path, const Headers &headers,
  11544. const UploadFormDataItems &items,
  11545. const FormDataProviderItems &provider_items,
  11546. UploadProgress progress) {
  11547. return cli_->Post(path, headers, items, provider_items, progress);
  11548. }
  11549. inline Result Client::Post(const std::string &path, const Headers &headers,
  11550. const std::string &body,
  11551. const std::string &content_type,
  11552. ContentReceiver content_receiver,
  11553. DownloadProgress progress) {
  11554. return cli_->Post(path, headers, body, content_type,
  11555. std::move(content_receiver), progress);
  11556. }
  11557. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  11558. inline Result Client::Put(const std::string &path, const Headers &headers) {
  11559. return cli_->Put(path, headers);
  11560. }
  11561. inline Result Client::Put(const std::string &path, const char *body,
  11562. size_t content_length,
  11563. const std::string &content_type,
  11564. UploadProgress progress) {
  11565. return cli_->Put(path, body, content_length, content_type, progress);
  11566. }
  11567. inline Result Client::Put(const std::string &path, const Headers &headers,
  11568. const char *body, size_t content_length,
  11569. const std::string &content_type,
  11570. UploadProgress progress) {
  11571. return cli_->Put(path, headers, body, content_length, content_type, progress);
  11572. }
  11573. inline Result Client::Put(const std::string &path, const std::string &body,
  11574. const std::string &content_type,
  11575. UploadProgress progress) {
  11576. return cli_->Put(path, body, content_type, progress);
  11577. }
  11578. inline Result Client::Put(const std::string &path, const Headers &headers,
  11579. const std::string &body,
  11580. const std::string &content_type,
  11581. UploadProgress progress) {
  11582. return cli_->Put(path, headers, body, content_type, progress);
  11583. }
  11584. inline Result Client::Put(const std::string &path, size_t content_length,
  11585. ContentProvider content_provider,
  11586. const std::string &content_type,
  11587. UploadProgress progress) {
  11588. return cli_->Put(path, content_length, std::move(content_provider),
  11589. content_type, progress);
  11590. }
  11591. inline Result Client::Put(const std::string &path, size_t content_length,
  11592. ContentProvider content_provider,
  11593. const std::string &content_type,
  11594. ContentReceiver content_receiver,
  11595. UploadProgress progress) {
  11596. return cli_->Put(path, content_length, std::move(content_provider),
  11597. content_type, std::move(content_receiver), progress);
  11598. }
  11599. inline Result Client::Put(const std::string &path,
  11600. ContentProviderWithoutLength content_provider,
  11601. const std::string &content_type,
  11602. UploadProgress progress) {
  11603. return cli_->Put(path, std::move(content_provider), content_type, progress);
  11604. }
  11605. inline Result Client::Put(const std::string &path,
  11606. ContentProviderWithoutLength content_provider,
  11607. const std::string &content_type,
  11608. ContentReceiver content_receiver,
  11609. UploadProgress progress) {
  11610. return cli_->Put(path, std::move(content_provider), content_type,
  11611. std::move(content_receiver), progress);
  11612. }
  11613. inline Result Client::Put(const std::string &path, const Headers &headers,
  11614. size_t content_length,
  11615. ContentProvider content_provider,
  11616. const std::string &content_type,
  11617. UploadProgress progress) {
  11618. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11619. content_type, progress);
  11620. }
  11621. inline Result Client::Put(const std::string &path, const Headers &headers,
  11622. size_t content_length,
  11623. ContentProvider content_provider,
  11624. const std::string &content_type,
  11625. ContentReceiver content_receiver,
  11626. UploadProgress progress) {
  11627. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11628. content_type, std::move(content_receiver), progress);
  11629. }
  11630. inline Result Client::Put(const std::string &path, const Headers &headers,
  11631. ContentProviderWithoutLength content_provider,
  11632. const std::string &content_type,
  11633. UploadProgress progress) {
  11634. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11635. progress);
  11636. }
  11637. inline Result Client::Put(const std::string &path, const Headers &headers,
  11638. ContentProviderWithoutLength content_provider,
  11639. const std::string &content_type,
  11640. ContentReceiver content_receiver,
  11641. UploadProgress progress) {
  11642. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11643. std::move(content_receiver), progress);
  11644. }
  11645. inline Result Client::Put(const std::string &path, const Params &params) {
  11646. return cli_->Put(path, params);
  11647. }
  11648. inline Result Client::Put(const std::string &path, const Headers &headers,
  11649. const Params &params) {
  11650. return cli_->Put(path, headers, params);
  11651. }
  11652. inline Result Client::Put(const std::string &path,
  11653. const UploadFormDataItems &items,
  11654. UploadProgress progress) {
  11655. return cli_->Put(path, items, progress);
  11656. }
  11657. inline Result Client::Put(const std::string &path, const Headers &headers,
  11658. const UploadFormDataItems &items,
  11659. UploadProgress progress) {
  11660. return cli_->Put(path, headers, items, progress);
  11661. }
  11662. inline Result Client::Put(const std::string &path, const Headers &headers,
  11663. const UploadFormDataItems &items,
  11664. const std::string &boundary,
  11665. UploadProgress progress) {
  11666. return cli_->Put(path, headers, items, boundary, progress);
  11667. }
  11668. inline Result Client::Put(const std::string &path, const Headers &headers,
  11669. const UploadFormDataItems &items,
  11670. const FormDataProviderItems &provider_items,
  11671. UploadProgress progress) {
  11672. return cli_->Put(path, headers, items, provider_items, progress);
  11673. }
  11674. inline Result Client::Put(const std::string &path, const Headers &headers,
  11675. const std::string &body,
  11676. const std::string &content_type,
  11677. ContentReceiver content_receiver,
  11678. DownloadProgress progress) {
  11679. return cli_->Put(path, headers, body, content_type, content_receiver,
  11680. progress);
  11681. }
  11682. inline Result Client::Patch(const std::string &path) {
  11683. return cli_->Patch(path);
  11684. }
  11685. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  11686. return cli_->Patch(path, headers);
  11687. }
  11688. inline Result Client::Patch(const std::string &path, const char *body,
  11689. size_t content_length,
  11690. const std::string &content_type,
  11691. UploadProgress progress) {
  11692. return cli_->Patch(path, body, content_length, content_type, progress);
  11693. }
  11694. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11695. const char *body, size_t content_length,
  11696. const std::string &content_type,
  11697. UploadProgress progress) {
  11698. return cli_->Patch(path, headers, body, content_length, content_type,
  11699. progress);
  11700. }
  11701. inline Result Client::Patch(const std::string &path, const std::string &body,
  11702. const std::string &content_type,
  11703. UploadProgress progress) {
  11704. return cli_->Patch(path, body, content_type, progress);
  11705. }
  11706. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11707. const std::string &body,
  11708. const std::string &content_type,
  11709. UploadProgress progress) {
  11710. return cli_->Patch(path, headers, body, content_type, progress);
  11711. }
  11712. inline Result Client::Patch(const std::string &path, size_t content_length,
  11713. ContentProvider content_provider,
  11714. const std::string &content_type,
  11715. UploadProgress progress) {
  11716. return cli_->Patch(path, content_length, std::move(content_provider),
  11717. content_type, progress);
  11718. }
  11719. inline Result Client::Patch(const std::string &path, size_t content_length,
  11720. ContentProvider content_provider,
  11721. const std::string &content_type,
  11722. ContentReceiver content_receiver,
  11723. UploadProgress progress) {
  11724. return cli_->Patch(path, content_length, std::move(content_provider),
  11725. content_type, std::move(content_receiver), progress);
  11726. }
  11727. inline Result Client::Patch(const std::string &path,
  11728. ContentProviderWithoutLength content_provider,
  11729. const std::string &content_type,
  11730. UploadProgress progress) {
  11731. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  11732. }
  11733. inline Result Client::Patch(const std::string &path,
  11734. ContentProviderWithoutLength content_provider,
  11735. const std::string &content_type,
  11736. ContentReceiver content_receiver,
  11737. UploadProgress progress) {
  11738. return cli_->Patch(path, std::move(content_provider), content_type,
  11739. std::move(content_receiver), progress);
  11740. }
  11741. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11742. size_t content_length,
  11743. ContentProvider content_provider,
  11744. const std::string &content_type,
  11745. UploadProgress progress) {
  11746. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11747. content_type, progress);
  11748. }
  11749. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11750. size_t content_length,
  11751. ContentProvider content_provider,
  11752. const std::string &content_type,
  11753. ContentReceiver content_receiver,
  11754. UploadProgress progress) {
  11755. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11756. content_type, std::move(content_receiver), progress);
  11757. }
  11758. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11759. ContentProviderWithoutLength content_provider,
  11760. const std::string &content_type,
  11761. UploadProgress progress) {
  11762. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11763. progress);
  11764. }
  11765. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11766. ContentProviderWithoutLength content_provider,
  11767. const std::string &content_type,
  11768. ContentReceiver content_receiver,
  11769. UploadProgress progress) {
  11770. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11771. std::move(content_receiver), progress);
  11772. }
  11773. inline Result Client::Patch(const std::string &path, const Params &params) {
  11774. return cli_->Patch(path, params);
  11775. }
  11776. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11777. const Params &params) {
  11778. return cli_->Patch(path, headers, params);
  11779. }
  11780. inline Result Client::Patch(const std::string &path,
  11781. const UploadFormDataItems &items,
  11782. UploadProgress progress) {
  11783. return cli_->Patch(path, items, progress);
  11784. }
  11785. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11786. const UploadFormDataItems &items,
  11787. UploadProgress progress) {
  11788. return cli_->Patch(path, headers, items, progress);
  11789. }
  11790. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11791. const UploadFormDataItems &items,
  11792. const std::string &boundary,
  11793. UploadProgress progress) {
  11794. return cli_->Patch(path, headers, items, boundary, progress);
  11795. }
  11796. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11797. const UploadFormDataItems &items,
  11798. const FormDataProviderItems &provider_items,
  11799. UploadProgress progress) {
  11800. return cli_->Patch(path, headers, items, provider_items, progress);
  11801. }
  11802. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11803. const std::string &body,
  11804. const std::string &content_type,
  11805. ContentReceiver content_receiver,
  11806. DownloadProgress progress) {
  11807. return cli_->Patch(path, headers, body, content_type, content_receiver,
  11808. progress);
  11809. }
  11810. inline Result Client::Delete(const std::string &path,
  11811. DownloadProgress progress) {
  11812. return cli_->Delete(path, progress);
  11813. }
  11814. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11815. DownloadProgress progress) {
  11816. return cli_->Delete(path, headers, progress);
  11817. }
  11818. inline Result Client::Delete(const std::string &path, const char *body,
  11819. size_t content_length,
  11820. const std::string &content_type,
  11821. DownloadProgress progress) {
  11822. return cli_->Delete(path, body, content_length, content_type, progress);
  11823. }
  11824. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11825. const char *body, size_t content_length,
  11826. const std::string &content_type,
  11827. DownloadProgress progress) {
  11828. return cli_->Delete(path, headers, body, content_length, content_type,
  11829. progress);
  11830. }
  11831. inline Result Client::Delete(const std::string &path, const std::string &body,
  11832. const std::string &content_type,
  11833. DownloadProgress progress) {
  11834. return cli_->Delete(path, body, content_type, progress);
  11835. }
  11836. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11837. const std::string &body,
  11838. const std::string &content_type,
  11839. DownloadProgress progress) {
  11840. return cli_->Delete(path, headers, body, content_type, progress);
  11841. }
  11842. inline Result Client::Delete(const std::string &path, const Params &params,
  11843. DownloadProgress progress) {
  11844. return cli_->Delete(path, params, progress);
  11845. }
  11846. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11847. const Params &params, DownloadProgress progress) {
  11848. return cli_->Delete(path, headers, params, progress);
  11849. }
  11850. inline Result Client::Options(const std::string &path) {
  11851. return cli_->Options(path);
  11852. }
  11853. inline Result Client::Options(const std::string &path, const Headers &headers) {
  11854. return cli_->Options(path, headers);
  11855. }
  11856. inline ClientImpl::StreamHandle
  11857. Client::open_stream(const std::string &method, const std::string &path,
  11858. const Params &params, const Headers &headers,
  11859. const std::string &body, const std::string &content_type) {
  11860. return cli_->open_stream(method, path, params, headers, body, content_type);
  11861. }
  11862. inline bool Client::send(Request &req, Response &res, Error &error) {
  11863. return cli_->send(req, res, error);
  11864. }
  11865. inline Result Client::send(const Request &req) { return cli_->send(req); }
  11866. inline void Client::stop() { cli_->stop(); }
  11867. inline std::string Client::host() const { return cli_->host(); }
  11868. inline int Client::port() const { return cli_->port(); }
  11869. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  11870. inline socket_t Client::socket() const { return cli_->socket(); }
  11871. inline void
  11872. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  11873. cli_->set_hostname_addr_map(std::move(addr_map));
  11874. }
  11875. inline void Client::set_default_headers(Headers headers) {
  11876. cli_->set_default_headers(std::move(headers));
  11877. }
  11878. inline void Client::set_header_writer(
  11879. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11880. cli_->set_header_writer(writer);
  11881. }
  11882. inline void Client::set_address_family(int family) {
  11883. cli_->set_address_family(family);
  11884. }
  11885. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  11886. inline void Client::set_socket_options(SocketOptions socket_options) {
  11887. cli_->set_socket_options(std::move(socket_options));
  11888. }
  11889. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  11890. cli_->set_connection_timeout(sec, usec);
  11891. }
  11892. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  11893. cli_->set_read_timeout(sec, usec);
  11894. }
  11895. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  11896. cli_->set_write_timeout(sec, usec);
  11897. }
  11898. inline void Client::set_basic_auth(const std::string &username,
  11899. const std::string &password) {
  11900. cli_->set_basic_auth(username, password);
  11901. }
  11902. inline void Client::set_bearer_token_auth(const std::string &token) {
  11903. cli_->set_bearer_token_auth(token);
  11904. }
  11905. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11906. inline void Client::set_digest_auth(const std::string &username,
  11907. const std::string &password) {
  11908. cli_->set_digest_auth(username, password);
  11909. }
  11910. #endif
  11911. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  11912. inline void Client::set_follow_location(bool on) {
  11913. cli_->set_follow_location(on);
  11914. }
  11915. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  11916. [[deprecated("Use set_path_encode instead")]]
  11917. inline void Client::set_url_encode(bool on) {
  11918. cli_->set_path_encode(on);
  11919. }
  11920. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  11921. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  11922. inline void Client::set_interface(const std::string &intf) {
  11923. cli_->set_interface(intf);
  11924. }
  11925. inline void Client::set_proxy(const std::string &host, int port) {
  11926. cli_->set_proxy(host, port);
  11927. }
  11928. inline void Client::set_proxy_basic_auth(const std::string &username,
  11929. const std::string &password) {
  11930. cli_->set_proxy_basic_auth(username, password);
  11931. }
  11932. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  11933. cli_->set_proxy_bearer_token_auth(token);
  11934. }
  11935. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11936. inline void Client::set_proxy_digest_auth(const std::string &username,
  11937. const std::string &password) {
  11938. cli_->set_proxy_digest_auth(username, password);
  11939. }
  11940. #endif
  11941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11942. inline void Client::enable_server_certificate_verification(bool enabled) {
  11943. cli_->enable_server_certificate_verification(enabled);
  11944. }
  11945. inline void Client::enable_server_hostname_verification(bool enabled) {
  11946. cli_->enable_server_hostname_verification(enabled);
  11947. }
  11948. inline void Client::set_server_certificate_verifier(
  11949. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  11950. cli_->set_server_certificate_verifier(verifier);
  11951. }
  11952. #endif
  11953. inline void Client::set_logger(Logger logger) {
  11954. cli_->set_logger(std::move(logger));
  11955. }
  11956. inline void Client::set_error_logger(ErrorLogger error_logger) {
  11957. cli_->set_error_logger(std::move(error_logger));
  11958. }
  11959. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11960. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  11961. const std::string &ca_cert_dir_path) {
  11962. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  11963. }
  11964. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  11965. if (is_ssl_) {
  11966. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  11967. } else {
  11968. cli_->set_ca_cert_store(ca_cert_store);
  11969. }
  11970. }
  11971. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  11972. set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
  11973. }
  11974. inline long Client::get_openssl_verify_result() const {
  11975. if (is_ssl_) {
  11976. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  11977. }
  11978. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  11979. }
  11980. inline SSL_CTX *Client::ssl_context() const {
  11981. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  11982. return nullptr;
  11983. }
  11984. #endif
  11985. // ----------------------------------------------------------------------------
  11986. } // namespace httplib
  11987. #endif // CPPHTTPLIB_HTTPLIB_H