httplib.h 475 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2026 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.30.1"
  10. #define CPPHTTPLIB_VERSION_NUM "0x001E01"
  11. /*
  12. * Platform compatibility check
  13. */
  14. #if defined(_WIN32) && !defined(_WIN64)
  15. #if defined(_MSC_VER)
  16. #pragma message( \
  17. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler.")
  18. #else
  19. #warning \
  20. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler."
  21. #endif
  22. #elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ < 8
  23. #warning \
  24. "cpp-httplib doesn't support 32-bit platforms. Please use a 64-bit compiler."
  25. #elif defined(__SIZEOF_SIZE_T__) && __SIZEOF_SIZE_T__ < 8
  26. #warning \
  27. "cpp-httplib doesn't support platforms where size_t is less than 64 bits."
  28. #endif
  29. #ifdef _WIN32
  30. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  31. #error \
  32. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  33. #endif
  34. #endif
  35. /*
  36. * Configuration
  37. */
  38. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  39. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  40. #endif
  41. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  42. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  43. #endif
  44. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  45. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  46. #endif
  47. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  60. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  61. #endif
  62. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  63. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  64. #endif
  65. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  66. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  67. #endif
  68. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  69. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  70. #endif
  71. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  72. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  73. #endif
  74. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  75. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  78. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  79. #endif
  80. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  81. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  82. #endif
  83. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  84. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  85. #endif
  86. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  87. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  88. #endif
  89. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  90. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  91. #endif
  92. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  93. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  94. #endif
  95. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  96. #ifdef _WIN32
  97. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  98. #else
  99. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  100. #endif
  101. #endif
  102. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  103. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  106. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  107. #endif
  108. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  109. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  110. #endif
  111. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  112. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  113. #endif
  114. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  115. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  116. #endif
  117. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  118. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  119. #endif
  120. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  121. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  122. #endif
  123. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  124. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  125. #endif
  126. #ifndef CPPHTTPLIB_TCP_NODELAY
  127. #define CPPHTTPLIB_TCP_NODELAY false
  128. #endif
  129. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  130. #define CPPHTTPLIB_IPV6_V6ONLY false
  131. #endif
  132. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  133. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  134. #endif
  135. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  136. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  137. #endif
  138. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  139. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  140. #endif
  141. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  142. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  143. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  144. ? std::thread::hardware_concurrency() - 1 \
  145. : 0))
  146. #endif
  147. #ifndef CPPHTTPLIB_RECV_FLAGS
  148. #define CPPHTTPLIB_RECV_FLAGS 0
  149. #endif
  150. #ifndef CPPHTTPLIB_SEND_FLAGS
  151. #define CPPHTTPLIB_SEND_FLAGS 0
  152. #endif
  153. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  154. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  155. #endif
  156. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  157. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  158. #endif
  159. /*
  160. * Headers
  161. */
  162. #ifdef _WIN32
  163. #ifndef _CRT_SECURE_NO_WARNINGS
  164. #define _CRT_SECURE_NO_WARNINGS
  165. #endif //_CRT_SECURE_NO_WARNINGS
  166. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  167. #define _CRT_NONSTDC_NO_DEPRECATE
  168. #endif //_CRT_NONSTDC_NO_DEPRECATE
  169. #if defined(_MSC_VER)
  170. #if _MSC_VER < 1900
  171. #error Sorry, Visual Studio versions prior to 2015 are not supported
  172. #endif
  173. #pragma comment(lib, "ws2_32.lib")
  174. #ifndef _SSIZE_T_DEFINED
  175. using ssize_t = __int64;
  176. #define _SSIZE_T_DEFINED
  177. #endif
  178. #endif // _MSC_VER
  179. #ifndef S_ISREG
  180. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  181. #endif // S_ISREG
  182. #ifndef S_ISDIR
  183. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  184. #endif // S_ISDIR
  185. #ifndef NOMINMAX
  186. #define NOMINMAX
  187. #endif // NOMINMAX
  188. #include <io.h>
  189. #include <winsock2.h>
  190. #include <ws2tcpip.h>
  191. #if defined(__has_include)
  192. #if __has_include(<afunix.h>)
  193. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  194. #include <afunix.h>
  195. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  196. #endif
  197. #endif
  198. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  199. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  200. #endif
  201. using nfds_t = unsigned long;
  202. using socket_t = SOCKET;
  203. using socklen_t = int;
  204. #else // not _WIN32
  205. #include <arpa/inet.h>
  206. #if !defined(_AIX) && !defined(__MVS__)
  207. #include <ifaddrs.h>
  208. #endif
  209. #ifdef __MVS__
  210. #include <strings.h>
  211. #ifndef NI_MAXHOST
  212. #define NI_MAXHOST 1025
  213. #endif
  214. #endif
  215. #include <net/if.h>
  216. #include <netdb.h>
  217. #include <netinet/in.h>
  218. #ifdef __linux__
  219. #include <resolv.h>
  220. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  221. #endif
  222. #include <csignal>
  223. #include <netinet/tcp.h>
  224. #include <poll.h>
  225. #include <pthread.h>
  226. #include <sys/mman.h>
  227. #include <sys/socket.h>
  228. #include <sys/un.h>
  229. #include <unistd.h>
  230. using socket_t = int;
  231. #ifndef INVALID_SOCKET
  232. #define INVALID_SOCKET (-1)
  233. #endif
  234. #endif //_WIN32
  235. #if defined(__APPLE__)
  236. #include <TargetConditionals.h>
  237. #endif
  238. #include <algorithm>
  239. #include <array>
  240. #include <atomic>
  241. #include <cassert>
  242. #include <cctype>
  243. #include <chrono>
  244. #include <climits>
  245. #include <condition_variable>
  246. #include <cstring>
  247. #include <errno.h>
  248. #include <exception>
  249. #include <fcntl.h>
  250. #include <functional>
  251. #include <iomanip>
  252. #include <iostream>
  253. #include <list>
  254. #include <map>
  255. #include <memory>
  256. #include <mutex>
  257. #include <random>
  258. #include <regex>
  259. #include <set>
  260. #include <sstream>
  261. #include <string>
  262. #include <sys/stat.h>
  263. #include <thread>
  264. #include <unordered_map>
  265. #include <unordered_set>
  266. #include <utility>
  267. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  268. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  269. #if TARGET_OS_MAC
  270. #include <CFNetwork/CFHost.h>
  271. #include <CoreFoundation/CoreFoundation.h>
  272. #endif
  273. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO or
  274. // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  275. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  276. #ifdef _WIN32
  277. #include <wincrypt.h>
  278. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  279. // used
  280. #undef X509_NAME
  281. #undef X509_CERT_PAIR
  282. #undef X509_EXTENSIONS
  283. #undef PKCS7_SIGNER_INFO
  284. #ifdef _MSC_VER
  285. #pragma comment(lib, "crypt32.lib")
  286. #endif
  287. #endif // _WIN32
  288. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  289. #if TARGET_OS_MAC
  290. #include <Security/Security.h>
  291. #endif
  292. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  293. #include <openssl/err.h>
  294. #include <openssl/evp.h>
  295. #include <openssl/ssl.h>
  296. #include <openssl/x509v3.h>
  297. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  298. #include <openssl/applink.c>
  299. #endif
  300. #include <iostream>
  301. #include <sstream>
  302. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  303. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  304. #error Please use OpenSSL or a current version of BoringSSL
  305. #endif
  306. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  307. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  308. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  309. #endif
  310. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  311. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  312. #include <zlib.h>
  313. #endif
  314. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  315. #include <brotli/decode.h>
  316. #include <brotli/encode.h>
  317. #endif
  318. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  319. #include <zstd.h>
  320. #endif
  321. /*
  322. * Declaration
  323. */
  324. namespace httplib {
  325. namespace detail {
  326. /*
  327. * Backport std::make_unique from C++14.
  328. *
  329. * NOTE: This code came up with the following stackoverflow post:
  330. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  331. *
  332. */
  333. template <class T, class... Args>
  334. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  335. make_unique(Args &&...args) {
  336. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  337. }
  338. template <class T>
  339. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  340. make_unique(std::size_t n) {
  341. typedef typename std::remove_extent<T>::type RT;
  342. return std::unique_ptr<T>(new RT[n]);
  343. }
  344. namespace case_ignore {
  345. inline unsigned char to_lower(int c) {
  346. const static unsigned char table[256] = {
  347. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  348. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  349. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  350. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  351. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  352. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  353. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  354. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  355. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  356. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  357. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  358. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  359. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  360. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  361. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  362. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  363. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  364. 255,
  365. };
  366. return table[(unsigned char)(char)c];
  367. }
  368. inline bool equal(const std::string &a, const std::string &b) {
  369. return a.size() == b.size() &&
  370. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  371. return to_lower(ca) == to_lower(cb);
  372. });
  373. }
  374. struct equal_to {
  375. bool operator()(const std::string &a, const std::string &b) const {
  376. return equal(a, b);
  377. }
  378. };
  379. struct hash {
  380. size_t operator()(const std::string &key) const {
  381. return hash_core(key.data(), key.size(), 0);
  382. }
  383. size_t hash_core(const char *s, size_t l, size_t h) const {
  384. return (l == 0) ? h
  385. : hash_core(s + 1, l - 1,
  386. // Unsets the 6 high bits of h, therefore no
  387. // overflow happens
  388. (((std::numeric_limits<size_t>::max)() >> 6) &
  389. h * 33) ^
  390. static_cast<unsigned char>(to_lower(*s)));
  391. }
  392. };
  393. template <typename T>
  394. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  395. detail::case_ignore::equal_to>;
  396. } // namespace case_ignore
  397. // This is based on
  398. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  399. struct scope_exit {
  400. explicit scope_exit(std::function<void(void)> &&f)
  401. : exit_function(std::move(f)), execute_on_destruction{true} {}
  402. scope_exit(scope_exit &&rhs) noexcept
  403. : exit_function(std::move(rhs.exit_function)),
  404. execute_on_destruction{rhs.execute_on_destruction} {
  405. rhs.release();
  406. }
  407. ~scope_exit() {
  408. if (execute_on_destruction) { this->exit_function(); }
  409. }
  410. void release() { this->execute_on_destruction = false; }
  411. private:
  412. scope_exit(const scope_exit &) = delete;
  413. void operator=(const scope_exit &) = delete;
  414. scope_exit &operator=(scope_exit &&) = delete;
  415. std::function<void(void)> exit_function;
  416. bool execute_on_destruction;
  417. };
  418. } // namespace detail
  419. enum SSLVerifierResponse {
  420. // no decision has been made, use the built-in certificate verifier
  421. NoDecisionMade,
  422. // connection certificate is verified and accepted
  423. CertificateAccepted,
  424. // connection certificate was processed but is rejected
  425. CertificateRejected
  426. };
  427. enum StatusCode {
  428. // Information responses
  429. Continue_100 = 100,
  430. SwitchingProtocol_101 = 101,
  431. Processing_102 = 102,
  432. EarlyHints_103 = 103,
  433. // Successful responses
  434. OK_200 = 200,
  435. Created_201 = 201,
  436. Accepted_202 = 202,
  437. NonAuthoritativeInformation_203 = 203,
  438. NoContent_204 = 204,
  439. ResetContent_205 = 205,
  440. PartialContent_206 = 206,
  441. MultiStatus_207 = 207,
  442. AlreadyReported_208 = 208,
  443. IMUsed_226 = 226,
  444. // Redirection messages
  445. MultipleChoices_300 = 300,
  446. MovedPermanently_301 = 301,
  447. Found_302 = 302,
  448. SeeOther_303 = 303,
  449. NotModified_304 = 304,
  450. UseProxy_305 = 305,
  451. unused_306 = 306,
  452. TemporaryRedirect_307 = 307,
  453. PermanentRedirect_308 = 308,
  454. // Client error responses
  455. BadRequest_400 = 400,
  456. Unauthorized_401 = 401,
  457. PaymentRequired_402 = 402,
  458. Forbidden_403 = 403,
  459. NotFound_404 = 404,
  460. MethodNotAllowed_405 = 405,
  461. NotAcceptable_406 = 406,
  462. ProxyAuthenticationRequired_407 = 407,
  463. RequestTimeout_408 = 408,
  464. Conflict_409 = 409,
  465. Gone_410 = 410,
  466. LengthRequired_411 = 411,
  467. PreconditionFailed_412 = 412,
  468. PayloadTooLarge_413 = 413,
  469. UriTooLong_414 = 414,
  470. UnsupportedMediaType_415 = 415,
  471. RangeNotSatisfiable_416 = 416,
  472. ExpectationFailed_417 = 417,
  473. ImATeapot_418 = 418,
  474. MisdirectedRequest_421 = 421,
  475. UnprocessableContent_422 = 422,
  476. Locked_423 = 423,
  477. FailedDependency_424 = 424,
  478. TooEarly_425 = 425,
  479. UpgradeRequired_426 = 426,
  480. PreconditionRequired_428 = 428,
  481. TooManyRequests_429 = 429,
  482. RequestHeaderFieldsTooLarge_431 = 431,
  483. UnavailableForLegalReasons_451 = 451,
  484. // Server error responses
  485. InternalServerError_500 = 500,
  486. NotImplemented_501 = 501,
  487. BadGateway_502 = 502,
  488. ServiceUnavailable_503 = 503,
  489. GatewayTimeout_504 = 504,
  490. HttpVersionNotSupported_505 = 505,
  491. VariantAlsoNegotiates_506 = 506,
  492. InsufficientStorage_507 = 507,
  493. LoopDetected_508 = 508,
  494. NotExtended_510 = 510,
  495. NetworkAuthenticationRequired_511 = 511,
  496. };
  497. using Headers =
  498. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  499. detail::case_ignore::equal_to>;
  500. using Params = std::multimap<std::string, std::string>;
  501. using Match = std::smatch;
  502. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  503. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  504. struct Response;
  505. using ResponseHandler = std::function<bool(const Response &response)>;
  506. struct FormData {
  507. std::string name;
  508. std::string content;
  509. std::string filename;
  510. std::string content_type;
  511. Headers headers;
  512. };
  513. struct FormField {
  514. std::string name;
  515. std::string content;
  516. Headers headers;
  517. };
  518. using FormFields = std::multimap<std::string, FormField>;
  519. using FormFiles = std::multimap<std::string, FormData>;
  520. struct MultipartFormData {
  521. FormFields fields; // Text fields from multipart
  522. FormFiles files; // Files from multipart
  523. // Text field access
  524. std::string get_field(const std::string &key, size_t id = 0) const;
  525. std::vector<std::string> get_fields(const std::string &key) const;
  526. bool has_field(const std::string &key) const;
  527. size_t get_field_count(const std::string &key) const;
  528. // File access
  529. FormData get_file(const std::string &key, size_t id = 0) const;
  530. std::vector<FormData> get_files(const std::string &key) const;
  531. bool has_file(const std::string &key) const;
  532. size_t get_file_count(const std::string &key) const;
  533. };
  534. struct UploadFormData {
  535. std::string name;
  536. std::string content;
  537. std::string filename;
  538. std::string content_type;
  539. };
  540. using UploadFormDataItems = std::vector<UploadFormData>;
  541. class DataSink {
  542. public:
  543. DataSink() : os(&sb_), sb_(*this) {}
  544. DataSink(const DataSink &) = delete;
  545. DataSink &operator=(const DataSink &) = delete;
  546. DataSink(DataSink &&) = delete;
  547. DataSink &operator=(DataSink &&) = delete;
  548. std::function<bool(const char *data, size_t data_len)> write;
  549. std::function<bool()> is_writable;
  550. std::function<void()> done;
  551. std::function<void(const Headers &trailer)> done_with_trailer;
  552. std::ostream os;
  553. private:
  554. class data_sink_streambuf final : public std::streambuf {
  555. public:
  556. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  557. protected:
  558. std::streamsize xsputn(const char *s, std::streamsize n) override {
  559. sink_.write(s, static_cast<size_t>(n));
  560. return n;
  561. }
  562. private:
  563. DataSink &sink_;
  564. };
  565. data_sink_streambuf sb_;
  566. };
  567. using ContentProvider =
  568. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  569. using ContentProviderWithoutLength =
  570. std::function<bool(size_t offset, DataSink &sink)>;
  571. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  572. struct FormDataProvider {
  573. std::string name;
  574. ContentProviderWithoutLength provider;
  575. std::string filename;
  576. std::string content_type;
  577. };
  578. using FormDataProviderItems = std::vector<FormDataProvider>;
  579. using ContentReceiverWithProgress = std::function<bool(
  580. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  581. using ContentReceiver =
  582. std::function<bool(const char *data, size_t data_length)>;
  583. using FormDataHeader = std::function<bool(const FormData &file)>;
  584. class ContentReader {
  585. public:
  586. using Reader = std::function<bool(ContentReceiver receiver)>;
  587. using FormDataReader =
  588. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  589. ContentReader(Reader reader, FormDataReader multipart_reader)
  590. : reader_(std::move(reader)),
  591. formdata_reader_(std::move(multipart_reader)) {}
  592. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  593. return formdata_reader_(std::move(header), std::move(receiver));
  594. }
  595. bool operator()(ContentReceiver receiver) const {
  596. return reader_(std::move(receiver));
  597. }
  598. Reader reader_;
  599. FormDataReader formdata_reader_;
  600. };
  601. using Range = std::pair<ssize_t, ssize_t>;
  602. using Ranges = std::vector<Range>;
  603. struct Request {
  604. std::string method;
  605. std::string path;
  606. std::string matched_route;
  607. Params params;
  608. Headers headers;
  609. Headers trailers;
  610. std::string body;
  611. std::string remote_addr;
  612. int remote_port = -1;
  613. std::string local_addr;
  614. int local_port = -1;
  615. // for server
  616. std::string version;
  617. std::string target;
  618. MultipartFormData form;
  619. Ranges ranges;
  620. Match matches;
  621. std::unordered_map<std::string, std::string> path_params;
  622. std::function<bool()> is_connection_closed = []() { return true; };
  623. // for client
  624. std::vector<std::string> accept_content_types;
  625. ResponseHandler response_handler;
  626. ContentReceiverWithProgress content_receiver;
  627. DownloadProgress download_progress;
  628. UploadProgress upload_progress;
  629. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  630. const SSL *ssl = nullptr;
  631. #endif
  632. bool has_header(const std::string &key) const;
  633. std::string get_header_value(const std::string &key, const char *def = "",
  634. size_t id = 0) const;
  635. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  636. size_t id = 0) const;
  637. size_t get_header_value_count(const std::string &key) const;
  638. void set_header(const std::string &key, const std::string &val);
  639. bool has_trailer(const std::string &key) const;
  640. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  641. size_t get_trailer_value_count(const std::string &key) const;
  642. bool has_param(const std::string &key) const;
  643. std::string get_param_value(const std::string &key, size_t id = 0) const;
  644. size_t get_param_value_count(const std::string &key) const;
  645. bool is_multipart_form_data() const;
  646. // private members...
  647. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  648. size_t content_length_ = 0;
  649. ContentProvider content_provider_;
  650. bool is_chunked_content_provider_ = false;
  651. size_t authorization_count_ = 0;
  652. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  653. (std::chrono::steady_clock::time_point::min)();
  654. };
  655. struct Response {
  656. std::string version;
  657. int status = -1;
  658. std::string reason;
  659. Headers headers;
  660. Headers trailers;
  661. std::string body;
  662. std::string location; // Redirect location
  663. bool has_header(const std::string &key) const;
  664. std::string get_header_value(const std::string &key, const char *def = "",
  665. size_t id = 0) const;
  666. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  667. size_t id = 0) const;
  668. size_t get_header_value_count(const std::string &key) const;
  669. void set_header(const std::string &key, const std::string &val);
  670. bool has_trailer(const std::string &key) const;
  671. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  672. size_t get_trailer_value_count(const std::string &key) const;
  673. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  674. void set_content(const char *s, size_t n, const std::string &content_type);
  675. void set_content(const std::string &s, const std::string &content_type);
  676. void set_content(std::string &&s, const std::string &content_type);
  677. void set_content_provider(
  678. size_t length, const std::string &content_type, ContentProvider provider,
  679. ContentProviderResourceReleaser resource_releaser = nullptr);
  680. void set_content_provider(
  681. const std::string &content_type, ContentProviderWithoutLength provider,
  682. ContentProviderResourceReleaser resource_releaser = nullptr);
  683. void set_chunked_content_provider(
  684. const std::string &content_type, ContentProviderWithoutLength provider,
  685. ContentProviderResourceReleaser resource_releaser = nullptr);
  686. void set_file_content(const std::string &path,
  687. const std::string &content_type);
  688. void set_file_content(const std::string &path);
  689. Response() = default;
  690. Response(const Response &) = default;
  691. Response &operator=(const Response &) = default;
  692. Response(Response &&) = default;
  693. Response &operator=(Response &&) = default;
  694. ~Response() {
  695. if (content_provider_resource_releaser_) {
  696. content_provider_resource_releaser_(content_provider_success_);
  697. }
  698. }
  699. // private members...
  700. size_t content_length_ = 0;
  701. ContentProvider content_provider_;
  702. ContentProviderResourceReleaser content_provider_resource_releaser_;
  703. bool is_chunked_content_provider_ = false;
  704. bool content_provider_success_ = false;
  705. std::string file_content_path_;
  706. std::string file_content_content_type_;
  707. };
  708. enum class Error {
  709. Success = 0,
  710. Unknown,
  711. Connection,
  712. BindIPAddress,
  713. Read,
  714. Write,
  715. ExceedRedirectCount,
  716. Canceled,
  717. SSLConnection,
  718. SSLLoadingCerts,
  719. SSLServerVerification,
  720. SSLServerHostnameVerification,
  721. UnsupportedMultipartBoundaryChars,
  722. Compression,
  723. ConnectionTimeout,
  724. ProxyConnection,
  725. ConnectionClosed,
  726. Timeout,
  727. ResourceExhaustion,
  728. TooManyFormDataFiles,
  729. ExceedMaxPayloadSize,
  730. ExceedUriMaxLength,
  731. ExceedMaxSocketDescriptorCount,
  732. InvalidRequestLine,
  733. InvalidHTTPMethod,
  734. InvalidHTTPVersion,
  735. InvalidHeaders,
  736. MultipartParsing,
  737. OpenFile,
  738. Listen,
  739. GetSockName,
  740. UnsupportedAddressFamily,
  741. HTTPParsing,
  742. InvalidRangeHeader,
  743. // For internal use only
  744. SSLPeerCouldBeClosed_,
  745. };
  746. std::string to_string(Error error);
  747. std::ostream &operator<<(std::ostream &os, const Error &obj);
  748. class Stream {
  749. public:
  750. virtual ~Stream() = default;
  751. virtual bool is_readable() const = 0;
  752. virtual bool wait_readable() const = 0;
  753. virtual bool wait_writable() const = 0;
  754. virtual ssize_t read(char *ptr, size_t size) = 0;
  755. virtual ssize_t write(const char *ptr, size_t size) = 0;
  756. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  757. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  758. virtual socket_t socket() const = 0;
  759. virtual time_t duration() const = 0;
  760. ssize_t write(const char *ptr);
  761. ssize_t write(const std::string &s);
  762. Error get_error() const { return error_; }
  763. protected:
  764. Error error_ = Error::Success;
  765. };
  766. class TaskQueue {
  767. public:
  768. TaskQueue() = default;
  769. virtual ~TaskQueue() = default;
  770. virtual bool enqueue(std::function<void()> fn) = 0;
  771. virtual void shutdown() = 0;
  772. virtual void on_idle() {}
  773. };
  774. class ThreadPool final : public TaskQueue {
  775. public:
  776. explicit ThreadPool(size_t n, size_t mqr = 0)
  777. : shutdown_(false), max_queued_requests_(mqr) {
  778. threads_.reserve(n);
  779. while (n) {
  780. threads_.emplace_back(worker(*this));
  781. n--;
  782. }
  783. }
  784. ThreadPool(const ThreadPool &) = delete;
  785. ~ThreadPool() override = default;
  786. bool enqueue(std::function<void()> fn) override {
  787. {
  788. std::unique_lock<std::mutex> lock(mutex_);
  789. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  790. return false;
  791. }
  792. jobs_.push_back(std::move(fn));
  793. }
  794. cond_.notify_one();
  795. return true;
  796. }
  797. void shutdown() override {
  798. // Stop all worker threads...
  799. {
  800. std::unique_lock<std::mutex> lock(mutex_);
  801. shutdown_ = true;
  802. }
  803. cond_.notify_all();
  804. // Join...
  805. for (auto &t : threads_) {
  806. t.join();
  807. }
  808. }
  809. private:
  810. struct worker {
  811. explicit worker(ThreadPool &pool) : pool_(pool) {}
  812. void operator()() {
  813. for (;;) {
  814. std::function<void()> fn;
  815. {
  816. std::unique_lock<std::mutex> lock(pool_.mutex_);
  817. pool_.cond_.wait(
  818. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  819. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  820. fn = pool_.jobs_.front();
  821. pool_.jobs_.pop_front();
  822. }
  823. assert(true == static_cast<bool>(fn));
  824. fn();
  825. }
  826. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  827. !defined(LIBRESSL_VERSION_NUMBER)
  828. OPENSSL_thread_stop();
  829. #endif
  830. }
  831. ThreadPool &pool_;
  832. };
  833. friend struct worker;
  834. std::vector<std::thread> threads_;
  835. std::list<std::function<void()>> jobs_;
  836. bool shutdown_;
  837. size_t max_queued_requests_ = 0;
  838. std::condition_variable cond_;
  839. std::mutex mutex_;
  840. };
  841. using Logger = std::function<void(const Request &, const Response &)>;
  842. // Forward declaration for Error type
  843. enum class Error;
  844. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  845. using SocketOptions = std::function<void(socket_t sock)>;
  846. void default_socket_options(socket_t sock);
  847. const char *status_message(int status);
  848. std::string to_string(Error error);
  849. std::ostream &operator<<(std::ostream &os, const Error &obj);
  850. std::string get_bearer_token_auth(const Request &req);
  851. namespace detail {
  852. class MatcherBase {
  853. public:
  854. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  855. virtual ~MatcherBase() = default;
  856. const std::string &pattern() const { return pattern_; }
  857. // Match request path and populate its matches and
  858. virtual bool match(Request &request) const = 0;
  859. private:
  860. std::string pattern_;
  861. };
  862. /**
  863. * Captures parameters in request path and stores them in Request::path_params
  864. *
  865. * Capture name is a substring of a pattern from : to /.
  866. * The rest of the pattern is matched against the request path directly
  867. * Parameters are captured starting from the next character after
  868. * the end of the last matched static pattern fragment until the next /.
  869. *
  870. * Example pattern:
  871. * "/path/fragments/:capture/more/fragments/:second_capture"
  872. * Static fragments:
  873. * "/path/fragments/", "more/fragments/"
  874. *
  875. * Given the following request path:
  876. * "/path/fragments/:1/more/fragments/:2"
  877. * the resulting capture will be
  878. * {{"capture", "1"}, {"second_capture", "2"}}
  879. */
  880. class PathParamsMatcher final : public MatcherBase {
  881. public:
  882. PathParamsMatcher(const std::string &pattern);
  883. bool match(Request &request) const override;
  884. private:
  885. // Treat segment separators as the end of path parameter capture
  886. // Does not need to handle query parameters as they are parsed before path
  887. // matching
  888. static constexpr char separator = '/';
  889. // Contains static path fragments to match against, excluding the '/' after
  890. // path params
  891. // Fragments are separated by path params
  892. std::vector<std::string> static_fragments_;
  893. // Stores the names of the path parameters to be used as keys in the
  894. // Request::path_params map
  895. std::vector<std::string> param_names_;
  896. };
  897. /**
  898. * Performs std::regex_match on request path
  899. * and stores the result in Request::matches
  900. *
  901. * Note that regex match is performed directly on the whole request.
  902. * This means that wildcard patterns may match multiple path segments with /:
  903. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  904. */
  905. class RegexMatcher final : public MatcherBase {
  906. public:
  907. RegexMatcher(const std::string &pattern)
  908. : MatcherBase(pattern), regex_(pattern) {}
  909. bool match(Request &request) const override;
  910. private:
  911. std::regex regex_;
  912. };
  913. int close_socket(socket_t sock);
  914. ssize_t write_headers(Stream &strm, const Headers &headers);
  915. } // namespace detail
  916. class Server {
  917. public:
  918. using Handler = std::function<void(const Request &, Response &)>;
  919. using ExceptionHandler =
  920. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  921. enum class HandlerResponse {
  922. Handled,
  923. Unhandled,
  924. };
  925. using HandlerWithResponse =
  926. std::function<HandlerResponse(const Request &, Response &)>;
  927. using HandlerWithContentReader = std::function<void(
  928. const Request &, Response &, const ContentReader &content_reader)>;
  929. using Expect100ContinueHandler =
  930. std::function<int(const Request &, Response &)>;
  931. Server();
  932. virtual ~Server();
  933. virtual bool is_valid() const;
  934. Server &Get(const std::string &pattern, Handler handler);
  935. Server &Post(const std::string &pattern, Handler handler);
  936. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  937. Server &Put(const std::string &pattern, Handler handler);
  938. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  939. Server &Patch(const std::string &pattern, Handler handler);
  940. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  941. Server &Delete(const std::string &pattern, Handler handler);
  942. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  943. Server &Options(const std::string &pattern, Handler handler);
  944. bool set_base_dir(const std::string &dir,
  945. const std::string &mount_point = std::string());
  946. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  947. Headers headers = Headers());
  948. bool remove_mount_point(const std::string &mount_point);
  949. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  950. const std::string &mime);
  951. Server &set_default_file_mimetype(const std::string &mime);
  952. Server &set_file_request_handler(Handler handler);
  953. template <class ErrorHandlerFunc>
  954. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  955. return set_error_handler_core(
  956. std::forward<ErrorHandlerFunc>(handler),
  957. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  958. }
  959. Server &set_exception_handler(ExceptionHandler handler);
  960. Server &set_pre_routing_handler(HandlerWithResponse handler);
  961. Server &set_post_routing_handler(Handler handler);
  962. Server &set_pre_request_handler(HandlerWithResponse handler);
  963. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  964. Server &set_logger(Logger logger);
  965. Server &set_pre_compression_logger(Logger logger);
  966. Server &set_error_logger(ErrorLogger error_logger);
  967. Server &set_address_family(int family);
  968. Server &set_tcp_nodelay(bool on);
  969. Server &set_ipv6_v6only(bool on);
  970. Server &set_socket_options(SocketOptions socket_options);
  971. Server &set_default_headers(Headers headers);
  972. Server &
  973. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  974. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  975. Server &set_keep_alive_max_count(size_t count);
  976. Server &set_keep_alive_timeout(time_t sec);
  977. Server &set_read_timeout(time_t sec, time_t usec = 0);
  978. template <class Rep, class Period>
  979. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  980. Server &set_write_timeout(time_t sec, time_t usec = 0);
  981. template <class Rep, class Period>
  982. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  983. Server &set_idle_interval(time_t sec, time_t usec = 0);
  984. template <class Rep, class Period>
  985. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  986. Server &set_payload_max_length(size_t length);
  987. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  988. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  989. bool listen_after_bind();
  990. bool listen(const std::string &host, int port, int socket_flags = 0);
  991. bool is_running() const;
  992. void wait_until_ready() const;
  993. void stop();
  994. void decommission();
  995. std::function<TaskQueue *(void)> new_task_queue;
  996. protected:
  997. bool process_request(Stream &strm, const std::string &remote_addr,
  998. int remote_port, const std::string &local_addr,
  999. int local_port, bool close_connection,
  1000. bool &connection_closed,
  1001. const std::function<void(Request &)> &setup_request);
  1002. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1003. std::vector<std::string> trusted_proxies_;
  1004. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1005. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1006. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1007. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1008. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1009. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1010. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1011. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1012. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1013. private:
  1014. using Handlers =
  1015. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1016. using HandlersForContentReader =
  1017. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1018. HandlerWithContentReader>>;
  1019. static std::unique_ptr<detail::MatcherBase>
  1020. make_matcher(const std::string &pattern);
  1021. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1022. Server &set_error_handler_core(Handler handler, std::false_type);
  1023. socket_t create_server_socket(const std::string &host, int port,
  1024. int socket_flags,
  1025. SocketOptions socket_options) const;
  1026. int bind_internal(const std::string &host, int port, int socket_flags);
  1027. bool listen_internal();
  1028. bool routing(Request &req, Response &res, Stream &strm);
  1029. bool handle_file_request(Request &req, Response &res);
  1030. bool check_if_not_modified(const Request &req, Response &res,
  1031. const std::string &etag, time_t mtime) const;
  1032. bool check_if_range(Request &req, const std::string &etag,
  1033. time_t mtime) const;
  1034. bool dispatch_request(Request &req, Response &res,
  1035. const Handlers &handlers) const;
  1036. bool dispatch_request_for_content_reader(
  1037. Request &req, Response &res, ContentReader content_reader,
  1038. const HandlersForContentReader &handlers) const;
  1039. bool parse_request_line(const char *s, Request &req) const;
  1040. void apply_ranges(const Request &req, Response &res,
  1041. std::string &content_type, std::string &boundary) const;
  1042. bool write_response(Stream &strm, bool close_connection, Request &req,
  1043. Response &res);
  1044. bool write_response_with_content(Stream &strm, bool close_connection,
  1045. const Request &req, Response &res);
  1046. bool write_response_core(Stream &strm, bool close_connection,
  1047. const Request &req, Response &res,
  1048. bool need_apply_ranges);
  1049. bool write_content_with_provider(Stream &strm, const Request &req,
  1050. Response &res, const std::string &boundary,
  1051. const std::string &content_type);
  1052. bool read_content(Stream &strm, Request &req, Response &res);
  1053. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1054. Response &res,
  1055. ContentReceiver receiver,
  1056. FormDataHeader multipart_header,
  1057. ContentReceiver multipart_receiver);
  1058. bool read_content_core(Stream &strm, Request &req, Response &res,
  1059. ContentReceiver receiver,
  1060. FormDataHeader multipart_header,
  1061. ContentReceiver multipart_receiver) const;
  1062. virtual bool process_and_close_socket(socket_t sock);
  1063. void output_log(const Request &req, const Response &res) const;
  1064. void output_pre_compression_log(const Request &req,
  1065. const Response &res) const;
  1066. void output_error_log(const Error &err, const Request *req) const;
  1067. std::atomic<bool> is_running_{false};
  1068. std::atomic<bool> is_decommissioned{false};
  1069. struct MountPointEntry {
  1070. std::string mount_point;
  1071. std::string base_dir;
  1072. Headers headers;
  1073. };
  1074. std::vector<MountPointEntry> base_dirs_;
  1075. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1076. std::string default_file_mimetype_ = "application/octet-stream";
  1077. Handler file_request_handler_;
  1078. Handlers get_handlers_;
  1079. Handlers post_handlers_;
  1080. HandlersForContentReader post_handlers_for_content_reader_;
  1081. Handlers put_handlers_;
  1082. HandlersForContentReader put_handlers_for_content_reader_;
  1083. Handlers patch_handlers_;
  1084. HandlersForContentReader patch_handlers_for_content_reader_;
  1085. Handlers delete_handlers_;
  1086. HandlersForContentReader delete_handlers_for_content_reader_;
  1087. Handlers options_handlers_;
  1088. HandlerWithResponse error_handler_;
  1089. ExceptionHandler exception_handler_;
  1090. HandlerWithResponse pre_routing_handler_;
  1091. Handler post_routing_handler_;
  1092. HandlerWithResponse pre_request_handler_;
  1093. Expect100ContinueHandler expect_100_continue_handler_;
  1094. mutable std::mutex logger_mutex_;
  1095. Logger logger_;
  1096. Logger pre_compression_logger_;
  1097. ErrorLogger error_logger_;
  1098. int address_family_ = AF_UNSPEC;
  1099. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1100. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1101. SocketOptions socket_options_ = default_socket_options;
  1102. Headers default_headers_;
  1103. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1104. detail::write_headers;
  1105. };
  1106. class Result {
  1107. public:
  1108. Result() = default;
  1109. Result(std::unique_ptr<Response> &&res, Error err,
  1110. Headers &&request_headers = Headers{})
  1111. : res_(std::move(res)), err_(err),
  1112. request_headers_(std::move(request_headers)) {}
  1113. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1114. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1115. int ssl_error)
  1116. : res_(std::move(res)), err_(err),
  1117. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1118. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1119. int ssl_error, unsigned long ssl_openssl_error)
  1120. : res_(std::move(res)), err_(err),
  1121. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1122. ssl_openssl_error_(ssl_openssl_error) {}
  1123. #endif
  1124. // Response
  1125. operator bool() const { return res_ != nullptr; }
  1126. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1127. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1128. const Response &value() const { return *res_; }
  1129. Response &value() { return *res_; }
  1130. const Response &operator*() const { return *res_; }
  1131. Response &operator*() { return *res_; }
  1132. const Response *operator->() const { return res_.get(); }
  1133. Response *operator->() { return res_.get(); }
  1134. // Error
  1135. Error error() const { return err_; }
  1136. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1137. // SSL Error
  1138. int ssl_error() const { return ssl_error_; }
  1139. // OpenSSL Error
  1140. unsigned long ssl_openssl_error() const { return ssl_openssl_error_; }
  1141. #endif
  1142. // Request Headers
  1143. bool has_request_header(const std::string &key) const;
  1144. std::string get_request_header_value(const std::string &key,
  1145. const char *def = "",
  1146. size_t id = 0) const;
  1147. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1148. size_t id = 0) const;
  1149. size_t get_request_header_value_count(const std::string &key) const;
  1150. private:
  1151. std::unique_ptr<Response> res_;
  1152. Error err_ = Error::Unknown;
  1153. Headers request_headers_;
  1154. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1155. int ssl_error_ = 0;
  1156. unsigned long ssl_openssl_error_ = 0;
  1157. #endif
  1158. };
  1159. struct ClientConnection {
  1160. socket_t sock = INVALID_SOCKET;
  1161. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1162. SSL *ssl = nullptr;
  1163. #endif
  1164. bool is_open() const { return sock != INVALID_SOCKET; }
  1165. ClientConnection() = default;
  1166. ~ClientConnection() {
  1167. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1168. if (ssl) {
  1169. SSL_free(ssl);
  1170. ssl = nullptr;
  1171. }
  1172. #endif
  1173. if (sock != INVALID_SOCKET) {
  1174. detail::close_socket(sock);
  1175. sock = INVALID_SOCKET;
  1176. }
  1177. }
  1178. ClientConnection(const ClientConnection &) = delete;
  1179. ClientConnection &operator=(const ClientConnection &) = delete;
  1180. ClientConnection(ClientConnection &&other) noexcept
  1181. : sock(other.sock)
  1182. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1183. ,
  1184. ssl(other.ssl)
  1185. #endif
  1186. {
  1187. other.sock = INVALID_SOCKET;
  1188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1189. other.ssl = nullptr;
  1190. #endif
  1191. }
  1192. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1193. if (this != &other) {
  1194. sock = other.sock;
  1195. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1196. ssl = other.ssl;
  1197. #endif
  1198. other.sock = INVALID_SOCKET;
  1199. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1200. other.ssl = nullptr;
  1201. #endif
  1202. }
  1203. return *this;
  1204. }
  1205. };
  1206. namespace detail {
  1207. struct ChunkedDecoder;
  1208. struct BodyReader {
  1209. Stream *stream = nullptr;
  1210. size_t content_length = 0;
  1211. size_t bytes_read = 0;
  1212. bool chunked = false;
  1213. bool eof = false;
  1214. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1215. Error last_error = Error::Success;
  1216. ssize_t read(char *buf, size_t len);
  1217. bool has_error() const { return last_error != Error::Success; }
  1218. };
  1219. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1220. size_t len) {
  1221. (void)stream;
  1222. return br.read(buf, len);
  1223. }
  1224. class decompressor;
  1225. } // namespace detail
  1226. class ClientImpl {
  1227. public:
  1228. explicit ClientImpl(const std::string &host);
  1229. explicit ClientImpl(const std::string &host, int port);
  1230. explicit ClientImpl(const std::string &host, int port,
  1231. const std::string &client_cert_path,
  1232. const std::string &client_key_path);
  1233. virtual ~ClientImpl();
  1234. virtual bool is_valid() const;
  1235. struct StreamHandle {
  1236. std::unique_ptr<Response> response;
  1237. Error error = Error::Success;
  1238. StreamHandle() = default;
  1239. StreamHandle(const StreamHandle &) = delete;
  1240. StreamHandle &operator=(const StreamHandle &) = delete;
  1241. StreamHandle(StreamHandle &&) = default;
  1242. StreamHandle &operator=(StreamHandle &&) = default;
  1243. ~StreamHandle() = default;
  1244. bool is_valid() const {
  1245. return response != nullptr && error == Error::Success;
  1246. }
  1247. ssize_t read(char *buf, size_t len);
  1248. void parse_trailers_if_needed();
  1249. Error get_read_error() const { return body_reader_.last_error; }
  1250. bool has_read_error() const { return body_reader_.has_error(); }
  1251. bool trailers_parsed_ = false;
  1252. private:
  1253. friend class ClientImpl;
  1254. ssize_t read_with_decompression(char *buf, size_t len);
  1255. std::unique_ptr<ClientConnection> connection_;
  1256. std::unique_ptr<Stream> socket_stream_;
  1257. Stream *stream_ = nullptr;
  1258. detail::BodyReader body_reader_;
  1259. std::unique_ptr<detail::decompressor> decompressor_;
  1260. std::string decompress_buffer_;
  1261. size_t decompress_offset_ = 0;
  1262. };
  1263. // clang-format off
  1264. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1265. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1266. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1267. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1268. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1269. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1270. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1271. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1272. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1273. Result Head(const std::string &path);
  1274. Result Head(const std::string &path, const Headers &headers);
  1275. Result Post(const std::string &path);
  1276. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1277. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1278. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1279. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1280. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1281. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1282. Result Post(const std::string &path, const Params &params);
  1283. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1284. Result Post(const std::string &path, const Headers &headers);
  1285. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1286. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1287. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1288. 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);
  1289. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1290. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1291. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1292. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1293. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1294. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1295. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1296. Result Put(const std::string &path);
  1297. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1298. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1299. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1300. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1301. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1302. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1303. Result Put(const std::string &path, const Params &params);
  1304. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1305. Result Put(const std::string &path, const Headers &headers);
  1306. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1307. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1308. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1309. 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);
  1310. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1311. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1312. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1313. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1314. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1315. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1316. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1317. Result Patch(const std::string &path);
  1318. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1319. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1320. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1321. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1322. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1323. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1324. Result Patch(const std::string &path, const Params &params);
  1325. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1326. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1327. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1328. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1329. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1330. 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);
  1331. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1332. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1333. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1334. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1335. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1336. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1337. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1338. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1339. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1340. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1341. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1342. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1343. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1344. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1345. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1346. Result Options(const std::string &path);
  1347. Result Options(const std::string &path, const Headers &headers);
  1348. // clang-format on
  1349. // Streaming API: Open a stream for reading response body incrementally
  1350. // Socket ownership is transferred to StreamHandle for true streaming
  1351. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1352. StreamHandle open_stream(const std::string &method, const std::string &path,
  1353. const Params &params = {},
  1354. const Headers &headers = {},
  1355. const std::string &body = {},
  1356. const std::string &content_type = {});
  1357. bool send(Request &req, Response &res, Error &error);
  1358. Result send(const Request &req);
  1359. void stop();
  1360. std::string host() const;
  1361. int port() const;
  1362. size_t is_socket_open() const;
  1363. socket_t socket() const;
  1364. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1365. void set_default_headers(Headers headers);
  1366. void
  1367. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1368. void set_address_family(int family);
  1369. void set_tcp_nodelay(bool on);
  1370. void set_ipv6_v6only(bool on);
  1371. void set_socket_options(SocketOptions socket_options);
  1372. void set_connection_timeout(time_t sec, time_t usec = 0);
  1373. template <class Rep, class Period>
  1374. void
  1375. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1376. void set_read_timeout(time_t sec, time_t usec = 0);
  1377. template <class Rep, class Period>
  1378. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1379. void set_write_timeout(time_t sec, time_t usec = 0);
  1380. template <class Rep, class Period>
  1381. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1382. void set_max_timeout(time_t msec);
  1383. template <class Rep, class Period>
  1384. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1385. void set_basic_auth(const std::string &username, const std::string &password);
  1386. void set_bearer_token_auth(const std::string &token);
  1387. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1388. void set_digest_auth(const std::string &username,
  1389. const std::string &password);
  1390. #endif
  1391. void set_keep_alive(bool on);
  1392. void set_follow_location(bool on);
  1393. void set_path_encode(bool on);
  1394. void set_compress(bool on);
  1395. void set_decompress(bool on);
  1396. void set_interface(const std::string &intf);
  1397. void set_proxy(const std::string &host, int port);
  1398. void set_proxy_basic_auth(const std::string &username,
  1399. const std::string &password);
  1400. void set_proxy_bearer_token_auth(const std::string &token);
  1401. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1402. void set_proxy_digest_auth(const std::string &username,
  1403. const std::string &password);
  1404. #endif
  1405. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1406. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1407. const std::string &ca_cert_dir_path = std::string());
  1408. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1409. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1410. #endif
  1411. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1412. void enable_server_certificate_verification(bool enabled);
  1413. void enable_server_hostname_verification(bool enabled);
  1414. void set_server_certificate_verifier(
  1415. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1416. #endif
  1417. void set_logger(Logger logger);
  1418. void set_error_logger(ErrorLogger error_logger);
  1419. protected:
  1420. struct Socket {
  1421. socket_t sock = INVALID_SOCKET;
  1422. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1423. SSL *ssl = nullptr;
  1424. #endif
  1425. bool is_open() const { return sock != INVALID_SOCKET; }
  1426. };
  1427. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1428. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1429. // All of:
  1430. // shutdown_ssl
  1431. // shutdown_socket
  1432. // close_socket
  1433. // should ONLY be called when socket_mutex_ is locked.
  1434. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1435. // with a DIFFERENT thread sending requests using that socket.
  1436. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1437. void shutdown_socket(Socket &socket) const;
  1438. void close_socket(Socket &socket);
  1439. bool process_request(Stream &strm, Request &req, Response &res,
  1440. bool close_connection, Error &error);
  1441. bool write_content_with_provider(Stream &strm, const Request &req,
  1442. Error &error) const;
  1443. void copy_settings(const ClientImpl &rhs);
  1444. void output_log(const Request &req, const Response &res) const;
  1445. void output_error_log(const Error &err, const Request *req) const;
  1446. // Socket endpoint information
  1447. const std::string host_;
  1448. const int port_;
  1449. // Current open socket
  1450. Socket socket_;
  1451. mutable std::mutex socket_mutex_;
  1452. std::recursive_mutex request_mutex_;
  1453. // These are all protected under socket_mutex
  1454. size_t socket_requests_in_flight_ = 0;
  1455. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1456. bool socket_should_be_closed_when_request_is_done_ = false;
  1457. // Hostname-IP map
  1458. std::map<std::string, std::string> addr_map_;
  1459. // Default headers
  1460. Headers default_headers_;
  1461. // Header writer
  1462. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1463. detail::write_headers;
  1464. // Settings
  1465. std::string client_cert_path_;
  1466. std::string client_key_path_;
  1467. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1468. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1469. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1470. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1471. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1472. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1473. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1474. std::string basic_auth_username_;
  1475. std::string basic_auth_password_;
  1476. std::string bearer_token_auth_token_;
  1477. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1478. std::string digest_auth_username_;
  1479. std::string digest_auth_password_;
  1480. #endif
  1481. bool keep_alive_ = false;
  1482. bool follow_location_ = false;
  1483. bool path_encode_ = true;
  1484. int address_family_ = AF_UNSPEC;
  1485. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1486. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1487. SocketOptions socket_options_ = nullptr;
  1488. bool compress_ = false;
  1489. bool decompress_ = true;
  1490. std::string interface_;
  1491. std::string proxy_host_;
  1492. int proxy_port_ = -1;
  1493. std::string proxy_basic_auth_username_;
  1494. std::string proxy_basic_auth_password_;
  1495. std::string proxy_bearer_token_auth_token_;
  1496. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1497. std::string proxy_digest_auth_username_;
  1498. std::string proxy_digest_auth_password_;
  1499. #endif
  1500. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1501. std::string ca_cert_file_path_;
  1502. std::string ca_cert_dir_path_;
  1503. X509_STORE *ca_cert_store_ = nullptr;
  1504. #endif
  1505. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1506. bool server_certificate_verification_ = true;
  1507. bool server_hostname_verification_ = true;
  1508. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1509. #endif
  1510. mutable std::mutex logger_mutex_;
  1511. Logger logger_;
  1512. ErrorLogger error_logger_;
  1513. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1514. int last_ssl_error_ = 0;
  1515. unsigned long last_openssl_error_ = 0;
  1516. #endif
  1517. private:
  1518. bool send_(Request &req, Response &res, Error &error);
  1519. Result send_(Request &&req);
  1520. socket_t create_client_socket(Error &error) const;
  1521. bool read_response_line(Stream &strm, const Request &req, Response &res,
  1522. bool skip_100_continue = true) const;
  1523. bool write_request(Stream &strm, Request &req, bool close_connection,
  1524. Error &error, bool skip_body = false);
  1525. bool write_request_body(Stream &strm, Request &req, Error &error);
  1526. void prepare_default_headers(Request &r, bool for_stream,
  1527. const std::string &ct);
  1528. bool redirect(Request &req, Response &res, Error &error);
  1529. bool create_redirect_client(const std::string &scheme,
  1530. const std::string &host, int port, Request &req,
  1531. Response &res, const std::string &path,
  1532. const std::string &location, Error &error);
  1533. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1534. bool handle_request(Stream &strm, Request &req, Response &res,
  1535. bool close_connection, Error &error);
  1536. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1537. Request &req, const char *body, size_t content_length,
  1538. ContentProvider content_provider,
  1539. ContentProviderWithoutLength content_provider_without_length,
  1540. const std::string &content_type, ContentReceiver content_receiver,
  1541. Error &error);
  1542. Result send_with_content_provider_and_receiver(
  1543. const std::string &method, const std::string &path,
  1544. const Headers &headers, const char *body, size_t content_length,
  1545. ContentProvider content_provider,
  1546. ContentProviderWithoutLength content_provider_without_length,
  1547. const std::string &content_type, ContentReceiver content_receiver,
  1548. UploadProgress progress);
  1549. ContentProviderWithoutLength get_multipart_content_provider(
  1550. const std::string &boundary, const UploadFormDataItems &items,
  1551. const FormDataProviderItems &provider_items) const;
  1552. virtual bool
  1553. process_socket(const Socket &socket,
  1554. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1555. std::function<bool(Stream &strm)> callback);
  1556. virtual bool is_ssl() const;
  1557. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1558. };
  1559. class Client {
  1560. public:
  1561. // Universal interface
  1562. explicit Client(const std::string &scheme_host_port);
  1563. explicit Client(const std::string &scheme_host_port,
  1564. const std::string &client_cert_path,
  1565. const std::string &client_key_path);
  1566. // HTTP only interface
  1567. explicit Client(const std::string &host, int port);
  1568. explicit Client(const std::string &host, int port,
  1569. const std::string &client_cert_path,
  1570. const std::string &client_key_path);
  1571. Client(Client &&) = default;
  1572. Client &operator=(Client &&) = default;
  1573. ~Client();
  1574. bool is_valid() const;
  1575. // clang-format off
  1576. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1577. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1578. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1579. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1580. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1581. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1582. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1583. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1584. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1585. Result Head(const std::string &path);
  1586. Result Head(const std::string &path, const Headers &headers);
  1587. Result Post(const std::string &path);
  1588. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1589. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1590. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1591. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1592. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1593. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1594. Result Post(const std::string &path, const Params &params);
  1595. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1596. Result Post(const std::string &path, const Headers &headers);
  1597. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1598. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1599. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1600. 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);
  1601. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1602. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1603. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1604. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1605. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1606. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1607. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1608. Result Put(const std::string &path);
  1609. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1610. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1611. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1612. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1613. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1614. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1615. Result Put(const std::string &path, const Params &params);
  1616. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1617. Result Put(const std::string &path, const Headers &headers);
  1618. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1619. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1620. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1621. 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);
  1622. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1623. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1624. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1625. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1626. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1627. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1628. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1629. Result Patch(const std::string &path);
  1630. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1631. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1632. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1633. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1634. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1635. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1636. Result Patch(const std::string &path, const Params &params);
  1637. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1638. Result Patch(const std::string &path, const Headers &headers);
  1639. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1640. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1641. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1642. 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);
  1643. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1644. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1645. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1646. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1647. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1648. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1649. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1650. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1651. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1652. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1653. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1654. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1655. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1656. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1657. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1658. Result Options(const std::string &path);
  1659. Result Options(const std::string &path, const Headers &headers);
  1660. // clang-format on
  1661. // Streaming API: Open a stream for reading response body incrementally
  1662. // Socket ownership is transferred to StreamHandle for true streaming
  1663. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1664. ClientImpl::StreamHandle open_stream(const std::string &method,
  1665. const std::string &path,
  1666. const Params &params = {},
  1667. const Headers &headers = {},
  1668. const std::string &body = {},
  1669. const std::string &content_type = {});
  1670. bool send(Request &req, Response &res, Error &error);
  1671. Result send(const Request &req);
  1672. void stop();
  1673. std::string host() const;
  1674. int port() const;
  1675. size_t is_socket_open() const;
  1676. socket_t socket() const;
  1677. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1678. void set_default_headers(Headers headers);
  1679. void
  1680. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1681. void set_address_family(int family);
  1682. void set_tcp_nodelay(bool on);
  1683. void set_socket_options(SocketOptions socket_options);
  1684. void set_connection_timeout(time_t sec, time_t usec = 0);
  1685. template <class Rep, class Period>
  1686. void
  1687. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1688. void set_read_timeout(time_t sec, time_t usec = 0);
  1689. template <class Rep, class Period>
  1690. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1691. void set_write_timeout(time_t sec, time_t usec = 0);
  1692. template <class Rep, class Period>
  1693. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1694. void set_max_timeout(time_t msec);
  1695. template <class Rep, class Period>
  1696. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1697. void set_basic_auth(const std::string &username, const std::string &password);
  1698. void set_bearer_token_auth(const std::string &token);
  1699. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1700. void set_digest_auth(const std::string &username,
  1701. const std::string &password);
  1702. #endif
  1703. void set_keep_alive(bool on);
  1704. void set_follow_location(bool on);
  1705. void set_path_encode(bool on);
  1706. void set_url_encode(bool on);
  1707. void set_compress(bool on);
  1708. void set_decompress(bool on);
  1709. void set_interface(const std::string &intf);
  1710. void set_proxy(const std::string &host, int port);
  1711. void set_proxy_basic_auth(const std::string &username,
  1712. const std::string &password);
  1713. void set_proxy_bearer_token_auth(const std::string &token);
  1714. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1715. void set_proxy_digest_auth(const std::string &username,
  1716. const std::string &password);
  1717. #endif
  1718. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1719. void enable_server_certificate_verification(bool enabled);
  1720. void enable_server_hostname_verification(bool enabled);
  1721. void set_server_certificate_verifier(
  1722. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1723. #endif
  1724. void set_logger(Logger logger);
  1725. void set_error_logger(ErrorLogger error_logger);
  1726. // SSL
  1727. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1728. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1729. const std::string &ca_cert_dir_path = std::string());
  1730. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1731. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1732. long get_openssl_verify_result() const;
  1733. SSL_CTX *ssl_context() const;
  1734. #endif
  1735. private:
  1736. std::unique_ptr<ClientImpl> cli_;
  1737. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1738. bool is_ssl_ = false;
  1739. #endif
  1740. };
  1741. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1742. class SSLServer : public Server {
  1743. public:
  1744. SSLServer(const char *cert_path, const char *private_key_path,
  1745. const char *client_ca_cert_file_path = nullptr,
  1746. const char *client_ca_cert_dir_path = nullptr,
  1747. const char *private_key_password = nullptr);
  1748. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1749. X509_STORE *client_ca_cert_store = nullptr);
  1750. SSLServer(
  1751. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1752. ~SSLServer() override;
  1753. bool is_valid() const override;
  1754. SSL_CTX *ssl_context() const;
  1755. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1756. X509_STORE *client_ca_cert_store = nullptr);
  1757. int ssl_last_error() const { return last_ssl_error_; }
  1758. private:
  1759. bool process_and_close_socket(socket_t sock) override;
  1760. STACK_OF(X509_NAME) * extract_ca_names_from_x509_store(X509_STORE *store);
  1761. SSL_CTX *ctx_;
  1762. std::mutex ctx_mutex_;
  1763. int last_ssl_error_ = 0;
  1764. };
  1765. class SSLClient final : public ClientImpl {
  1766. public:
  1767. explicit SSLClient(const std::string &host);
  1768. explicit SSLClient(const std::string &host, int port);
  1769. explicit SSLClient(const std::string &host, int port,
  1770. const std::string &client_cert_path,
  1771. const std::string &client_key_path,
  1772. const std::string &private_key_password = std::string());
  1773. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1774. EVP_PKEY *client_key,
  1775. const std::string &private_key_password = std::string());
  1776. ~SSLClient() override;
  1777. bool is_valid() const override;
  1778. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1779. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1780. long get_openssl_verify_result() const;
  1781. SSL_CTX *ssl_context() const;
  1782. private:
  1783. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1784. bool ensure_socket_connection(Socket &socket, Error &error) override;
  1785. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1786. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1787. bool
  1788. process_socket(const Socket &socket,
  1789. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1790. std::function<bool(Stream &strm)> callback) override;
  1791. bool is_ssl() const override;
  1792. bool connect_with_proxy(
  1793. Socket &sock,
  1794. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1795. Response &res, bool &success, Error &error);
  1796. bool initialize_ssl(Socket &socket, Error &error);
  1797. bool load_certs();
  1798. bool verify_host(X509 *server_cert) const;
  1799. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1800. bool verify_host_with_common_name(X509 *server_cert) const;
  1801. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1802. SSL_CTX *ctx_;
  1803. std::mutex ctx_mutex_;
  1804. std::once_flag initialize_cert_;
  1805. std::vector<std::string> host_components_;
  1806. long verify_result_ = 0;
  1807. friend class ClientImpl;
  1808. };
  1809. #endif
  1810. /*
  1811. * Implementation of template methods.
  1812. */
  1813. namespace detail {
  1814. template <typename T, typename U>
  1815. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1816. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1817. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1818. duration - std::chrono::seconds(sec))
  1819. .count();
  1820. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1821. }
  1822. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1823. return N - 1;
  1824. }
  1825. inline bool is_numeric(const std::string &str) {
  1826. return !str.empty() &&
  1827. std::all_of(str.cbegin(), str.cend(),
  1828. [](unsigned char c) { return std::isdigit(c); });
  1829. }
  1830. inline size_t get_header_value_u64(const Headers &headers,
  1831. const std::string &key, size_t def,
  1832. size_t id, bool &is_invalid_value) {
  1833. is_invalid_value = false;
  1834. auto rng = headers.equal_range(key);
  1835. auto it = rng.first;
  1836. std::advance(it, static_cast<ssize_t>(id));
  1837. if (it != rng.second) {
  1838. if (is_numeric(it->second)) {
  1839. return std::strtoull(it->second.data(), nullptr, 10);
  1840. } else {
  1841. is_invalid_value = true;
  1842. }
  1843. }
  1844. return def;
  1845. }
  1846. inline size_t get_header_value_u64(const Headers &headers,
  1847. const std::string &key, size_t def,
  1848. size_t id) {
  1849. auto dummy = false;
  1850. return get_header_value_u64(headers, key, def, id, dummy);
  1851. }
  1852. } // namespace detail
  1853. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  1854. size_t id) const {
  1855. return detail::get_header_value_u64(headers, key, def, id);
  1856. }
  1857. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  1858. size_t id) const {
  1859. return detail::get_header_value_u64(headers, key, def, id);
  1860. }
  1861. namespace detail {
  1862. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1863. const void *optval, socklen_t optlen) {
  1864. return setsockopt(sock, level, optname,
  1865. #ifdef _WIN32
  1866. reinterpret_cast<const char *>(optval),
  1867. #else
  1868. optval,
  1869. #endif
  1870. optlen) == 0;
  1871. }
  1872. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1873. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1874. }
  1875. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1876. time_t sec, time_t usec) {
  1877. #ifdef _WIN32
  1878. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1879. #else
  1880. timeval timeout;
  1881. timeout.tv_sec = static_cast<long>(sec);
  1882. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1883. #endif
  1884. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  1885. }
  1886. } // namespace detail
  1887. inline void default_socket_options(socket_t sock) {
  1888. detail::set_socket_opt(sock, SOL_SOCKET,
  1889. #ifdef SO_REUSEPORT
  1890. SO_REUSEPORT,
  1891. #else
  1892. SO_REUSEADDR,
  1893. #endif
  1894. 1);
  1895. }
  1896. inline std::string get_bearer_token_auth(const Request &req) {
  1897. if (req.has_header("Authorization")) {
  1898. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  1899. return req.get_header_value("Authorization")
  1900. .substr(bearer_header_prefix_len);
  1901. }
  1902. return "";
  1903. }
  1904. template <class Rep, class Period>
  1905. inline Server &
  1906. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1907. detail::duration_to_sec_and_usec(
  1908. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1909. return *this;
  1910. }
  1911. template <class Rep, class Period>
  1912. inline Server &
  1913. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1914. detail::duration_to_sec_and_usec(
  1915. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1916. return *this;
  1917. }
  1918. template <class Rep, class Period>
  1919. inline Server &
  1920. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  1921. detail::duration_to_sec_and_usec(
  1922. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  1923. return *this;
  1924. }
  1925. inline size_t Result::get_request_header_value_u64(const std::string &key,
  1926. size_t def,
  1927. size_t id) const {
  1928. return detail::get_header_value_u64(request_headers_, key, def, id);
  1929. }
  1930. template <class Rep, class Period>
  1931. inline void ClientImpl::set_connection_timeout(
  1932. const std::chrono::duration<Rep, Period> &duration) {
  1933. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  1934. set_connection_timeout(sec, usec);
  1935. });
  1936. }
  1937. template <class Rep, class Period>
  1938. inline void ClientImpl::set_read_timeout(
  1939. const std::chrono::duration<Rep, Period> &duration) {
  1940. detail::duration_to_sec_and_usec(
  1941. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1942. }
  1943. template <class Rep, class Period>
  1944. inline void ClientImpl::set_write_timeout(
  1945. const std::chrono::duration<Rep, Period> &duration) {
  1946. detail::duration_to_sec_and_usec(
  1947. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1948. }
  1949. template <class Rep, class Period>
  1950. inline void ClientImpl::set_max_timeout(
  1951. const std::chrono::duration<Rep, Period> &duration) {
  1952. auto msec =
  1953. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  1954. set_max_timeout(msec);
  1955. }
  1956. template <class Rep, class Period>
  1957. inline void Client::set_connection_timeout(
  1958. const std::chrono::duration<Rep, Period> &duration) {
  1959. cli_->set_connection_timeout(duration);
  1960. }
  1961. template <class Rep, class Period>
  1962. inline void
  1963. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1964. cli_->set_read_timeout(duration);
  1965. }
  1966. template <class Rep, class Period>
  1967. inline void
  1968. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1969. cli_->set_write_timeout(duration);
  1970. }
  1971. inline void Client::set_max_timeout(time_t msec) {
  1972. cli_->set_max_timeout(msec);
  1973. }
  1974. template <class Rep, class Period>
  1975. inline void
  1976. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1977. cli_->set_max_timeout(duration);
  1978. }
  1979. /*
  1980. * Forward declarations and types that will be part of the .h file if split into
  1981. * .h + .cc.
  1982. */
  1983. std::string hosted_at(const std::string &hostname);
  1984. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  1985. // JavaScript-style URL encoding/decoding functions
  1986. std::string encode_uri_component(const std::string &value);
  1987. std::string encode_uri(const std::string &value);
  1988. std::string decode_uri_component(const std::string &value);
  1989. std::string decode_uri(const std::string &value);
  1990. // RFC 3986 compliant URL component encoding/decoding functions
  1991. std::string encode_path_component(const std::string &component);
  1992. std::string decode_path_component(const std::string &component);
  1993. std::string encode_query_component(const std::string &component,
  1994. bool space_as_plus = true);
  1995. std::string decode_query_component(const std::string &component,
  1996. bool plus_as_space = true);
  1997. std::string append_query_params(const std::string &path, const Params &params);
  1998. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  1999. std::pair<std::string, std::string>
  2000. make_basic_authentication_header(const std::string &username,
  2001. const std::string &password,
  2002. bool is_proxy = false);
  2003. namespace detail {
  2004. #if defined(_WIN32)
  2005. inline std::wstring u8string_to_wstring(const char *s) {
  2006. if (!s) { return std::wstring(); }
  2007. auto len = static_cast<int>(strlen(s));
  2008. if (!len) { return std::wstring(); }
  2009. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2010. if (!wlen) { return std::wstring(); }
  2011. std::wstring ws;
  2012. ws.resize(wlen);
  2013. wlen = ::MultiByteToWideChar(
  2014. CP_UTF8, 0, s, len,
  2015. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2016. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2017. return ws;
  2018. }
  2019. #endif
  2020. struct FileStat {
  2021. FileStat(const std::string &path);
  2022. bool is_file() const;
  2023. bool is_dir() const;
  2024. time_t mtime() const;
  2025. size_t size() const;
  2026. private:
  2027. #if defined(_WIN32)
  2028. struct _stat st_;
  2029. #else
  2030. struct stat st_;
  2031. #endif
  2032. int ret_ = -1;
  2033. };
  2034. std::string make_host_and_port_string(const std::string &host, int port,
  2035. bool is_ssl);
  2036. std::string trim_copy(const std::string &s);
  2037. void divide(
  2038. const char *data, std::size_t size, char d,
  2039. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2040. fn);
  2041. void divide(
  2042. const std::string &str, char d,
  2043. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2044. fn);
  2045. void split(const char *b, const char *e, char d,
  2046. std::function<void(const char *, const char *)> fn);
  2047. void split(const char *b, const char *e, char d, size_t m,
  2048. std::function<void(const char *, const char *)> fn);
  2049. bool process_client_socket(
  2050. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2051. time_t write_timeout_sec, time_t write_timeout_usec,
  2052. time_t max_timeout_msec,
  2053. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2054. std::function<bool(Stream &)> callback);
  2055. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2056. int port, int address_family, bool tcp_nodelay,
  2057. bool ipv6_v6only, SocketOptions socket_options,
  2058. time_t connection_timeout_sec,
  2059. time_t connection_timeout_usec,
  2060. time_t read_timeout_sec, time_t read_timeout_usec,
  2061. time_t write_timeout_sec,
  2062. time_t write_timeout_usec,
  2063. const std::string &intf, Error &error);
  2064. const char *get_header_value(const Headers &headers, const std::string &key,
  2065. const char *def, size_t id);
  2066. std::string params_to_query_str(const Params &params);
  2067. void parse_query_text(const char *data, std::size_t size, Params &params);
  2068. void parse_query_text(const std::string &s, Params &params);
  2069. bool parse_multipart_boundary(const std::string &content_type,
  2070. std::string &boundary);
  2071. bool parse_range_header(const std::string &s, Ranges &ranges);
  2072. bool parse_accept_header(const std::string &s,
  2073. std::vector<std::string> &content_types);
  2074. int close_socket(socket_t sock);
  2075. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2076. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2077. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2078. EncodingType encoding_type(const Request &req, const Response &res);
  2079. class BufferStream final : public Stream {
  2080. public:
  2081. BufferStream() = default;
  2082. ~BufferStream() override = default;
  2083. bool is_readable() const override;
  2084. bool wait_readable() const override;
  2085. bool wait_writable() const override;
  2086. ssize_t read(char *ptr, size_t size) override;
  2087. ssize_t write(const char *ptr, size_t size) override;
  2088. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2089. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2090. socket_t socket() const override;
  2091. time_t duration() const override;
  2092. const std::string &get_buffer() const;
  2093. private:
  2094. std::string buffer;
  2095. size_t position = 0;
  2096. };
  2097. class compressor {
  2098. public:
  2099. virtual ~compressor() = default;
  2100. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2101. virtual bool compress(const char *data, size_t data_length, bool last,
  2102. Callback callback) = 0;
  2103. };
  2104. class decompressor {
  2105. public:
  2106. virtual ~decompressor() = default;
  2107. virtual bool is_valid() const = 0;
  2108. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2109. virtual bool decompress(const char *data, size_t data_length,
  2110. Callback callback) = 0;
  2111. };
  2112. class nocompressor final : public compressor {
  2113. public:
  2114. ~nocompressor() override = default;
  2115. bool compress(const char *data, size_t data_length, bool /*last*/,
  2116. Callback callback) override;
  2117. };
  2118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2119. class gzip_compressor final : public compressor {
  2120. public:
  2121. gzip_compressor();
  2122. ~gzip_compressor() override;
  2123. bool compress(const char *data, size_t data_length, bool last,
  2124. Callback callback) override;
  2125. private:
  2126. bool is_valid_ = false;
  2127. z_stream strm_;
  2128. };
  2129. class gzip_decompressor final : public decompressor {
  2130. public:
  2131. gzip_decompressor();
  2132. ~gzip_decompressor() override;
  2133. bool is_valid() const override;
  2134. bool decompress(const char *data, size_t data_length,
  2135. Callback callback) override;
  2136. private:
  2137. bool is_valid_ = false;
  2138. z_stream strm_;
  2139. };
  2140. #endif
  2141. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2142. class brotli_compressor final : public compressor {
  2143. public:
  2144. brotli_compressor();
  2145. ~brotli_compressor();
  2146. bool compress(const char *data, size_t data_length, bool last,
  2147. Callback callback) override;
  2148. private:
  2149. BrotliEncoderState *state_ = nullptr;
  2150. };
  2151. class brotli_decompressor final : public decompressor {
  2152. public:
  2153. brotli_decompressor();
  2154. ~brotli_decompressor();
  2155. bool is_valid() const override;
  2156. bool decompress(const char *data, size_t data_length,
  2157. Callback callback) override;
  2158. private:
  2159. BrotliDecoderResult decoder_r;
  2160. BrotliDecoderState *decoder_s = nullptr;
  2161. };
  2162. #endif
  2163. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2164. class zstd_compressor : public compressor {
  2165. public:
  2166. zstd_compressor();
  2167. ~zstd_compressor();
  2168. bool compress(const char *data, size_t data_length, bool last,
  2169. Callback callback) override;
  2170. private:
  2171. ZSTD_CCtx *ctx_ = nullptr;
  2172. };
  2173. class zstd_decompressor : public decompressor {
  2174. public:
  2175. zstd_decompressor();
  2176. ~zstd_decompressor();
  2177. bool is_valid() const override;
  2178. bool decompress(const char *data, size_t data_length,
  2179. Callback callback) override;
  2180. private:
  2181. ZSTD_DCtx *ctx_ = nullptr;
  2182. };
  2183. #endif
  2184. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2185. // to store data. The call can set memory on stack for performance.
  2186. class stream_line_reader {
  2187. public:
  2188. stream_line_reader(Stream &strm, char *fixed_buffer,
  2189. size_t fixed_buffer_size);
  2190. const char *ptr() const;
  2191. size_t size() const;
  2192. bool end_with_crlf() const;
  2193. bool getline();
  2194. private:
  2195. void append(char c);
  2196. Stream &strm_;
  2197. char *fixed_buffer_;
  2198. const size_t fixed_buffer_size_;
  2199. size_t fixed_buffer_used_size_ = 0;
  2200. std::string growable_buffer_;
  2201. };
  2202. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2203. const Headers &src_headers);
  2204. struct ChunkedDecoder {
  2205. Stream &strm;
  2206. size_t chunk_remaining = 0;
  2207. bool finished = false;
  2208. char line_buf[64];
  2209. size_t last_chunk_total = 0;
  2210. size_t last_chunk_offset = 0;
  2211. explicit ChunkedDecoder(Stream &s);
  2212. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2213. size_t &out_chunk_total);
  2214. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2215. };
  2216. class mmap {
  2217. public:
  2218. mmap(const char *path);
  2219. ~mmap();
  2220. bool open(const char *path);
  2221. void close();
  2222. bool is_open() const;
  2223. size_t size() const;
  2224. const char *data() const;
  2225. private:
  2226. #if defined(_WIN32)
  2227. HANDLE hFile_ = NULL;
  2228. HANDLE hMapping_ = NULL;
  2229. #else
  2230. int fd_ = -1;
  2231. #endif
  2232. size_t size_ = 0;
  2233. void *addr_ = nullptr;
  2234. bool is_open_empty_file = false;
  2235. };
  2236. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2237. namespace fields {
  2238. bool is_token_char(char c);
  2239. bool is_token(const std::string &s);
  2240. bool is_field_name(const std::string &s);
  2241. bool is_vchar(char c);
  2242. bool is_obs_text(char c);
  2243. bool is_field_vchar(char c);
  2244. bool is_field_content(const std::string &s);
  2245. bool is_field_value(const std::string &s);
  2246. } // namespace fields
  2247. } // namespace detail
  2248. namespace stream {
  2249. class Result {
  2250. public:
  2251. Result() : chunk_size_(8192) {}
  2252. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192)
  2253. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  2254. Result(Result &&other) noexcept
  2255. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  2256. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  2257. finished_(other.finished_) {
  2258. other.current_size_ = 0;
  2259. other.finished_ = true;
  2260. }
  2261. Result &operator=(Result &&other) noexcept {
  2262. if (this != &other) {
  2263. handle_ = std::move(other.handle_);
  2264. buffer_ = std::move(other.buffer_);
  2265. current_size_ = other.current_size_;
  2266. chunk_size_ = other.chunk_size_;
  2267. finished_ = other.finished_;
  2268. other.current_size_ = 0;
  2269. other.finished_ = true;
  2270. }
  2271. return *this;
  2272. }
  2273. Result(const Result &) = delete;
  2274. Result &operator=(const Result &) = delete;
  2275. // Check if the result is valid (connection succeeded and response received)
  2276. bool is_valid() const { return handle_.is_valid(); }
  2277. explicit operator bool() const { return is_valid(); }
  2278. // Response status code
  2279. int status() const {
  2280. return handle_.response ? handle_.response->status : -1;
  2281. }
  2282. // Response headers
  2283. const Headers &headers() const {
  2284. static const Headers empty_headers;
  2285. return handle_.response ? handle_.response->headers : empty_headers;
  2286. }
  2287. std::string get_header_value(const std::string &key,
  2288. const char *def = "") const {
  2289. return handle_.response ? handle_.response->get_header_value(key, def)
  2290. : def;
  2291. }
  2292. bool has_header(const std::string &key) const {
  2293. return handle_.response ? handle_.response->has_header(key) : false;
  2294. }
  2295. // Error information
  2296. Error error() const { return handle_.error; }
  2297. Error read_error() const { return handle_.get_read_error(); }
  2298. bool has_read_error() const { return handle_.has_read_error(); }
  2299. // Streaming iteration API
  2300. // Call next() to read the next chunk, then access data via data()/size()
  2301. // Returns true if data was read, false when stream is exhausted
  2302. bool next() {
  2303. if (!handle_.is_valid() || finished_) { return false; }
  2304. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  2305. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  2306. if (n > 0) {
  2307. current_size_ = static_cast<size_t>(n);
  2308. return true;
  2309. }
  2310. current_size_ = 0;
  2311. finished_ = true;
  2312. return false;
  2313. }
  2314. // Pointer to current chunk data (valid after next() returns true)
  2315. const char *data() const { return buffer_.data(); }
  2316. // Size of current chunk (valid after next() returns true)
  2317. size_t size() const { return current_size_; }
  2318. // Convenience method: read all remaining data into a string
  2319. std::string read_all() {
  2320. std::string result;
  2321. while (next()) {
  2322. result.append(data(), size());
  2323. }
  2324. return result;
  2325. }
  2326. private:
  2327. ClientImpl::StreamHandle handle_;
  2328. std::string buffer_;
  2329. size_t current_size_ = 0;
  2330. size_t chunk_size_;
  2331. bool finished_ = false;
  2332. };
  2333. // GET
  2334. template <typename ClientType>
  2335. inline Result Get(ClientType &cli, const std::string &path,
  2336. size_t chunk_size = 8192) {
  2337. return Result{cli.open_stream("GET", path), chunk_size};
  2338. }
  2339. template <typename ClientType>
  2340. inline Result Get(ClientType &cli, const std::string &path,
  2341. const Headers &headers, size_t chunk_size = 8192) {
  2342. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2343. }
  2344. template <typename ClientType>
  2345. inline Result Get(ClientType &cli, const std::string &path,
  2346. const Params &params, size_t chunk_size = 8192) {
  2347. return Result{cli.open_stream("GET", path, params), chunk_size};
  2348. }
  2349. template <typename ClientType>
  2350. inline Result Get(ClientType &cli, const std::string &path,
  2351. const Params &params, const Headers &headers,
  2352. size_t chunk_size = 8192) {
  2353. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2354. }
  2355. // POST
  2356. template <typename ClientType>
  2357. inline Result Post(ClientType &cli, const std::string &path,
  2358. const std::string &body, const std::string &content_type,
  2359. size_t chunk_size = 8192) {
  2360. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2361. chunk_size};
  2362. }
  2363. template <typename ClientType>
  2364. inline Result Post(ClientType &cli, const std::string &path,
  2365. const Headers &headers, const std::string &body,
  2366. const std::string &content_type, size_t chunk_size = 8192) {
  2367. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2368. chunk_size};
  2369. }
  2370. template <typename ClientType>
  2371. inline Result Post(ClientType &cli, const std::string &path,
  2372. const Params &params, const std::string &body,
  2373. const std::string &content_type, size_t chunk_size = 8192) {
  2374. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2375. chunk_size};
  2376. }
  2377. template <typename ClientType>
  2378. inline Result Post(ClientType &cli, const std::string &path,
  2379. const Params &params, const Headers &headers,
  2380. const std::string &body, const std::string &content_type,
  2381. size_t chunk_size = 8192) {
  2382. return Result{
  2383. cli.open_stream("POST", path, params, headers, body, content_type),
  2384. chunk_size};
  2385. }
  2386. // PUT
  2387. template <typename ClientType>
  2388. inline Result Put(ClientType &cli, const std::string &path,
  2389. const std::string &body, const std::string &content_type,
  2390. size_t chunk_size = 8192) {
  2391. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2392. chunk_size};
  2393. }
  2394. template <typename ClientType>
  2395. inline Result Put(ClientType &cli, const std::string &path,
  2396. const Headers &headers, const std::string &body,
  2397. const std::string &content_type, size_t chunk_size = 8192) {
  2398. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2399. chunk_size};
  2400. }
  2401. template <typename ClientType>
  2402. inline Result Put(ClientType &cli, const std::string &path,
  2403. const Params &params, const std::string &body,
  2404. const std::string &content_type, size_t chunk_size = 8192) {
  2405. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2406. chunk_size};
  2407. }
  2408. template <typename ClientType>
  2409. inline Result Put(ClientType &cli, const std::string &path,
  2410. const Params &params, const Headers &headers,
  2411. const std::string &body, const std::string &content_type,
  2412. size_t chunk_size = 8192) {
  2413. return Result{
  2414. cli.open_stream("PUT", path, params, headers, body, content_type),
  2415. chunk_size};
  2416. }
  2417. // PATCH
  2418. template <typename ClientType>
  2419. inline Result Patch(ClientType &cli, const std::string &path,
  2420. const std::string &body, const std::string &content_type,
  2421. size_t chunk_size = 8192) {
  2422. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2423. chunk_size};
  2424. }
  2425. template <typename ClientType>
  2426. inline Result Patch(ClientType &cli, const std::string &path,
  2427. const Headers &headers, const std::string &body,
  2428. const std::string &content_type, size_t chunk_size = 8192) {
  2429. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2430. chunk_size};
  2431. }
  2432. template <typename ClientType>
  2433. inline Result Patch(ClientType &cli, const std::string &path,
  2434. const Params &params, const std::string &body,
  2435. const std::string &content_type, size_t chunk_size = 8192) {
  2436. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2437. chunk_size};
  2438. }
  2439. template <typename ClientType>
  2440. inline Result Patch(ClientType &cli, const std::string &path,
  2441. const Params &params, const Headers &headers,
  2442. const std::string &body, const std::string &content_type,
  2443. size_t chunk_size = 8192) {
  2444. return Result{
  2445. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2446. chunk_size};
  2447. }
  2448. // DELETE
  2449. template <typename ClientType>
  2450. inline Result Delete(ClientType &cli, const std::string &path,
  2451. size_t chunk_size = 8192) {
  2452. return Result{cli.open_stream("DELETE", path), chunk_size};
  2453. }
  2454. template <typename ClientType>
  2455. inline Result Delete(ClientType &cli, const std::string &path,
  2456. const Headers &headers, size_t chunk_size = 8192) {
  2457. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2458. }
  2459. template <typename ClientType>
  2460. inline Result Delete(ClientType &cli, const std::string &path,
  2461. const std::string &body, const std::string &content_type,
  2462. size_t chunk_size = 8192) {
  2463. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2464. chunk_size};
  2465. }
  2466. template <typename ClientType>
  2467. inline Result Delete(ClientType &cli, const std::string &path,
  2468. const Headers &headers, const std::string &body,
  2469. const std::string &content_type,
  2470. size_t chunk_size = 8192) {
  2471. return Result{
  2472. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2473. chunk_size};
  2474. }
  2475. template <typename ClientType>
  2476. inline Result Delete(ClientType &cli, const std::string &path,
  2477. const Params &params, size_t chunk_size = 8192) {
  2478. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2479. }
  2480. template <typename ClientType>
  2481. inline Result Delete(ClientType &cli, const std::string &path,
  2482. const Params &params, const Headers &headers,
  2483. size_t chunk_size = 8192) {
  2484. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2485. }
  2486. template <typename ClientType>
  2487. inline Result Delete(ClientType &cli, const std::string &path,
  2488. const Params &params, const std::string &body,
  2489. const std::string &content_type,
  2490. size_t chunk_size = 8192) {
  2491. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2492. chunk_size};
  2493. }
  2494. template <typename ClientType>
  2495. inline Result Delete(ClientType &cli, const std::string &path,
  2496. const Params &params, const Headers &headers,
  2497. const std::string &body, const std::string &content_type,
  2498. size_t chunk_size = 8192) {
  2499. return Result{
  2500. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2501. chunk_size};
  2502. }
  2503. // HEAD
  2504. template <typename ClientType>
  2505. inline Result Head(ClientType &cli, const std::string &path,
  2506. size_t chunk_size = 8192) {
  2507. return Result{cli.open_stream("HEAD", path), chunk_size};
  2508. }
  2509. template <typename ClientType>
  2510. inline Result Head(ClientType &cli, const std::string &path,
  2511. const Headers &headers, size_t chunk_size = 8192) {
  2512. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2513. }
  2514. template <typename ClientType>
  2515. inline Result Head(ClientType &cli, const std::string &path,
  2516. const Params &params, size_t chunk_size = 8192) {
  2517. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2518. }
  2519. template <typename ClientType>
  2520. inline Result Head(ClientType &cli, const std::string &path,
  2521. const Params &params, const Headers &headers,
  2522. size_t chunk_size = 8192) {
  2523. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2524. }
  2525. // OPTIONS
  2526. template <typename ClientType>
  2527. inline Result Options(ClientType &cli, const std::string &path,
  2528. size_t chunk_size = 8192) {
  2529. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2530. }
  2531. template <typename ClientType>
  2532. inline Result Options(ClientType &cli, const std::string &path,
  2533. const Headers &headers, size_t chunk_size = 8192) {
  2534. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2535. }
  2536. template <typename ClientType>
  2537. inline Result Options(ClientType &cli, const std::string &path,
  2538. const Params &params, size_t chunk_size = 8192) {
  2539. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2540. }
  2541. template <typename ClientType>
  2542. inline Result Options(ClientType &cli, const std::string &path,
  2543. const Params &params, const Headers &headers,
  2544. size_t chunk_size = 8192) {
  2545. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2546. }
  2547. } // namespace stream
  2548. namespace sse {
  2549. struct SSEMessage {
  2550. std::string event; // Event type (default: "message")
  2551. std::string data; // Event payload
  2552. std::string id; // Event ID for Last-Event-ID header
  2553. SSEMessage() : event("message") {}
  2554. void clear() {
  2555. event = "message";
  2556. data.clear();
  2557. id.clear();
  2558. }
  2559. };
  2560. class SSEClient {
  2561. public:
  2562. using MessageHandler = std::function<void(const SSEMessage &)>;
  2563. using ErrorHandler = std::function<void(Error)>;
  2564. using OpenHandler = std::function<void()>;
  2565. SSEClient(Client &client, const std::string &path)
  2566. : client_(client), path_(path) {}
  2567. SSEClient(Client &client, const std::string &path, const Headers &headers)
  2568. : client_(client), path_(path), headers_(headers) {}
  2569. ~SSEClient() { stop(); }
  2570. SSEClient(const SSEClient &) = delete;
  2571. SSEClient &operator=(const SSEClient &) = delete;
  2572. // Event handlers
  2573. SSEClient &on_message(MessageHandler handler) {
  2574. on_message_ = std::move(handler);
  2575. return *this;
  2576. }
  2577. SSEClient &on_event(const std::string &type, MessageHandler handler) {
  2578. event_handlers_[type] = std::move(handler);
  2579. return *this;
  2580. }
  2581. SSEClient &on_open(OpenHandler handler) {
  2582. on_open_ = std::move(handler);
  2583. return *this;
  2584. }
  2585. SSEClient &on_error(ErrorHandler handler) {
  2586. on_error_ = std::move(handler);
  2587. return *this;
  2588. }
  2589. SSEClient &set_reconnect_interval(int ms) {
  2590. reconnect_interval_ms_ = ms;
  2591. return *this;
  2592. }
  2593. SSEClient &set_max_reconnect_attempts(int n) {
  2594. max_reconnect_attempts_ = n;
  2595. return *this;
  2596. }
  2597. // State accessors
  2598. bool is_connected() const { return connected_.load(); }
  2599. const std::string &last_event_id() const { return last_event_id_; }
  2600. // Blocking start - runs event loop with auto-reconnect
  2601. void start() {
  2602. running_.store(true);
  2603. run_event_loop();
  2604. }
  2605. // Non-blocking start - runs in background thread
  2606. void start_async() {
  2607. running_.store(true);
  2608. async_thread_ = std::thread([this]() { run_event_loop(); });
  2609. }
  2610. // Stop the client (thread-safe)
  2611. void stop() {
  2612. running_.store(false);
  2613. client_.stop(); // Cancel any pending operations
  2614. if (async_thread_.joinable()) { async_thread_.join(); }
  2615. }
  2616. private:
  2617. // Parse a single SSE field line
  2618. // Returns true if this line ends an event (blank line)
  2619. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms) {
  2620. // Blank line signals end of event
  2621. if (line.empty() || line == "\r") { return true; }
  2622. // Lines starting with ':' are comments (ignored)
  2623. if (!line.empty() && line[0] == ':') { return false; }
  2624. // Find the colon separator
  2625. auto colon_pos = line.find(':');
  2626. if (colon_pos == std::string::npos) {
  2627. // Line with no colon is treated as field name with empty value
  2628. return false;
  2629. }
  2630. auto field = line.substr(0, colon_pos);
  2631. std::string value;
  2632. // Value starts after colon, skip optional single space
  2633. if (colon_pos + 1 < line.size()) {
  2634. auto value_start = colon_pos + 1;
  2635. if (line[value_start] == ' ') { value_start++; }
  2636. value = line.substr(value_start);
  2637. // Remove trailing \r if present
  2638. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  2639. }
  2640. // Handle known fields
  2641. if (field == "event") {
  2642. msg.event = value;
  2643. } else if (field == "data") {
  2644. // Multiple data lines are concatenated with newlines
  2645. if (!msg.data.empty()) { msg.data += "\n"; }
  2646. msg.data += value;
  2647. } else if (field == "id") {
  2648. // Empty id is valid (clears the last event ID)
  2649. msg.id = value;
  2650. } else if (field == "retry") {
  2651. // Parse retry interval in milliseconds
  2652. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  2653. {
  2654. std::istringstream iss(value);
  2655. iss >> retry_ms;
  2656. }
  2657. #else
  2658. try {
  2659. retry_ms = std::stoi(value);
  2660. } catch (...) {
  2661. // Invalid retry value, ignore
  2662. }
  2663. #endif
  2664. }
  2665. // Unknown fields are ignored per SSE spec
  2666. return false;
  2667. }
  2668. // Main event loop with auto-reconnect
  2669. void run_event_loop() {
  2670. auto reconnect_count = 0;
  2671. while (running_.load()) {
  2672. // Build headers, including Last-Event-ID if we have one
  2673. auto request_headers = headers_;
  2674. if (!last_event_id_.empty()) {
  2675. request_headers.emplace("Last-Event-ID", last_event_id_);
  2676. }
  2677. // Open streaming connection
  2678. auto result = stream::Get(client_, path_, request_headers);
  2679. // Connection error handling
  2680. if (!result) {
  2681. connected_.store(false);
  2682. if (on_error_) { on_error_(result.error()); }
  2683. if (!should_reconnect(reconnect_count)) { break; }
  2684. wait_for_reconnect();
  2685. reconnect_count++;
  2686. continue;
  2687. }
  2688. if (result.status() != 200) {
  2689. connected_.store(false);
  2690. // For certain errors, don't reconnect
  2691. if (result.status() == 204 || // No Content - server wants us to stop
  2692. result.status() == 404 || // Not Found
  2693. result.status() == 401 || // Unauthorized
  2694. result.status() == 403) { // Forbidden
  2695. if (on_error_) { on_error_(Error::Connection); }
  2696. break;
  2697. }
  2698. if (on_error_) { on_error_(Error::Connection); }
  2699. if (!should_reconnect(reconnect_count)) { break; }
  2700. wait_for_reconnect();
  2701. reconnect_count++;
  2702. continue;
  2703. }
  2704. // Connection successful
  2705. connected_.store(true);
  2706. reconnect_count = 0;
  2707. if (on_open_) { on_open_(); }
  2708. // Event receiving loop
  2709. std::string buffer;
  2710. SSEMessage current_msg;
  2711. while (running_.load() && result.next()) {
  2712. buffer.append(result.data(), result.size());
  2713. // Process complete lines in the buffer
  2714. size_t line_start = 0;
  2715. size_t newline_pos;
  2716. while ((newline_pos = buffer.find('\n', line_start)) !=
  2717. std::string::npos) {
  2718. auto line = buffer.substr(line_start, newline_pos - line_start);
  2719. line_start = newline_pos + 1;
  2720. // Parse the line and check if event is complete
  2721. auto event_complete =
  2722. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  2723. if (event_complete && !current_msg.data.empty()) {
  2724. // Update last_event_id for reconnection
  2725. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  2726. // Dispatch event to appropriate handler
  2727. dispatch_event(current_msg);
  2728. current_msg.clear();
  2729. }
  2730. }
  2731. // Keep unprocessed data in buffer
  2732. buffer.erase(0, line_start);
  2733. }
  2734. // Connection ended
  2735. connected_.store(false);
  2736. if (!running_.load()) { break; }
  2737. // Check for read errors
  2738. if (result.has_read_error()) {
  2739. if (on_error_) { on_error_(result.read_error()); }
  2740. }
  2741. if (!should_reconnect(reconnect_count)) { break; }
  2742. wait_for_reconnect();
  2743. reconnect_count++;
  2744. }
  2745. connected_.store(false);
  2746. }
  2747. // Dispatch event to appropriate handler
  2748. void dispatch_event(const SSEMessage &msg) {
  2749. // Check for specific event type handler first
  2750. auto it = event_handlers_.find(msg.event);
  2751. if (it != event_handlers_.end()) {
  2752. it->second(msg);
  2753. return;
  2754. }
  2755. // Fall back to generic message handler
  2756. if (on_message_) { on_message_(msg); }
  2757. }
  2758. // Check if we should attempt to reconnect
  2759. bool should_reconnect(int count) const {
  2760. if (!running_.load()) { return false; }
  2761. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  2762. return count < max_reconnect_attempts_;
  2763. }
  2764. // Wait for reconnect interval
  2765. void wait_for_reconnect() {
  2766. // Use small increments to check running_ flag frequently
  2767. auto waited = 0;
  2768. while (running_.load() && waited < reconnect_interval_ms_) {
  2769. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2770. waited += 100;
  2771. }
  2772. }
  2773. // Client and path
  2774. Client &client_;
  2775. std::string path_;
  2776. Headers headers_;
  2777. // Callbacks
  2778. MessageHandler on_message_;
  2779. std::map<std::string, MessageHandler> event_handlers_;
  2780. OpenHandler on_open_;
  2781. ErrorHandler on_error_;
  2782. // Configuration
  2783. int reconnect_interval_ms_ = 3000;
  2784. int max_reconnect_attempts_ = 0; // 0 = unlimited
  2785. // State
  2786. std::atomic<bool> running_{false};
  2787. std::atomic<bool> connected_{false};
  2788. std::string last_event_id_;
  2789. // Async support
  2790. std::thread async_thread_;
  2791. };
  2792. } // namespace sse
  2793. // ----------------------------------------------------------------------------
  2794. /*
  2795. * Implementation that will be part of the .cc file if split into .h + .cc.
  2796. */
  2797. namespace detail {
  2798. inline bool is_hex(char c, int &v) {
  2799. if (isdigit(c)) {
  2800. v = c - '0';
  2801. return true;
  2802. } else if ('A' <= c && c <= 'F') {
  2803. v = c - 'A' + 10;
  2804. return true;
  2805. } else if ('a' <= c && c <= 'f') {
  2806. v = c - 'a' + 10;
  2807. return true;
  2808. }
  2809. return false;
  2810. }
  2811. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  2812. int &val) {
  2813. if (i >= s.size()) { return false; }
  2814. val = 0;
  2815. for (; cnt; i++, cnt--) {
  2816. if (!s[i]) { return false; }
  2817. auto v = 0;
  2818. if (is_hex(s[i], v)) {
  2819. val = val * 16 + v;
  2820. } else {
  2821. return false;
  2822. }
  2823. }
  2824. return true;
  2825. }
  2826. inline std::string from_i_to_hex(size_t n) {
  2827. static const auto charset = "0123456789abcdef";
  2828. std::string ret;
  2829. do {
  2830. ret = charset[n & 15] + ret;
  2831. n >>= 4;
  2832. } while (n > 0);
  2833. return ret;
  2834. }
  2835. inline std::string compute_etag(const FileStat &fs) {
  2836. if (!fs.is_file()) { return std::string(); }
  2837. // If mtime cannot be determined (negative value indicates an error
  2838. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  2839. // value like 0 could collide with a real file that legitimately has
  2840. // mtime == 0 (epoch) and lead to misleading validators.
  2841. auto mtime_raw = fs.mtime();
  2842. if (mtime_raw < 0) { return std::string(); }
  2843. auto mtime = static_cast<size_t>(mtime_raw);
  2844. auto size = fs.size();
  2845. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  2846. from_i_to_hex(size) + "\"";
  2847. }
  2848. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  2849. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  2850. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  2851. inline std::string file_mtime_to_http_date(time_t mtime) {
  2852. if (mtime < 0) { return std::string(); }
  2853. struct tm tm_buf;
  2854. #ifdef _WIN32
  2855. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  2856. #else
  2857. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  2858. #endif
  2859. char buf[64];
  2860. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  2861. return std::string();
  2862. }
  2863. return std::string(buf);
  2864. }
  2865. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  2866. inline time_t parse_http_date(const std::string &date_str) {
  2867. struct tm tm_buf;
  2868. // Create a classic locale object once for all parsing attempts
  2869. const std::locale classic_locale = std::locale::classic();
  2870. // Try to parse using std::get_time (C++11, cross-platform)
  2871. auto try_parse = [&](const char *fmt) -> bool {
  2872. std::istringstream ss(date_str);
  2873. ss.imbue(classic_locale);
  2874. memset(&tm_buf, 0, sizeof(tm_buf));
  2875. ss >> std::get_time(&tm_buf, fmt);
  2876. return !ss.fail();
  2877. };
  2878. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  2879. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  2880. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  2881. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  2882. // asctime format: "Sun Nov 6 08:49:37 1994"
  2883. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  2884. return static_cast<time_t>(-1);
  2885. }
  2886. }
  2887. }
  2888. #ifdef _WIN32
  2889. return _mkgmtime(&tm_buf);
  2890. #elif defined _AIX
  2891. return mktime(&tm_buf);
  2892. #else
  2893. return timegm(&tm_buf);
  2894. #endif
  2895. }
  2896. inline bool is_weak_etag(const std::string &s) {
  2897. // Check if the string is a weak ETag (starts with 'W/"')
  2898. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  2899. }
  2900. inline bool is_strong_etag(const std::string &s) {
  2901. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  2902. // chars)
  2903. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  2904. }
  2905. inline size_t to_utf8(int code, char *buff) {
  2906. if (code < 0x0080) {
  2907. buff[0] = static_cast<char>(code & 0x7F);
  2908. return 1;
  2909. } else if (code < 0x0800) {
  2910. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  2911. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  2912. return 2;
  2913. } else if (code < 0xD800) {
  2914. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2915. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2916. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2917. return 3;
  2918. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  2919. return 0;
  2920. } else if (code < 0x10000) {
  2921. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2922. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2923. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2924. return 3;
  2925. } else if (code < 0x110000) {
  2926. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  2927. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  2928. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2929. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  2930. return 4;
  2931. }
  2932. // NOTREACHED
  2933. return 0;
  2934. }
  2935. // NOTE: This code came up with the following stackoverflow post:
  2936. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  2937. inline std::string base64_encode(const std::string &in) {
  2938. static const auto lookup =
  2939. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2940. std::string out;
  2941. out.reserve(in.size());
  2942. auto val = 0;
  2943. auto valb = -6;
  2944. for (auto c : in) {
  2945. val = (val << 8) + static_cast<uint8_t>(c);
  2946. valb += 8;
  2947. while (valb >= 0) {
  2948. out.push_back(lookup[(val >> valb) & 0x3F]);
  2949. valb -= 6;
  2950. }
  2951. }
  2952. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  2953. while (out.size() % 4) {
  2954. out.push_back('=');
  2955. }
  2956. return out;
  2957. }
  2958. inline bool is_valid_path(const std::string &path) {
  2959. size_t level = 0;
  2960. size_t i = 0;
  2961. // Skip slash
  2962. while (i < path.size() && path[i] == '/') {
  2963. i++;
  2964. }
  2965. while (i < path.size()) {
  2966. // Read component
  2967. auto beg = i;
  2968. while (i < path.size() && path[i] != '/') {
  2969. if (path[i] == '\0') {
  2970. return false;
  2971. } else if (path[i] == '\\') {
  2972. return false;
  2973. }
  2974. i++;
  2975. }
  2976. auto len = i - beg;
  2977. assert(len > 0);
  2978. if (!path.compare(beg, len, ".")) {
  2979. ;
  2980. } else if (!path.compare(beg, len, "..")) {
  2981. if (level == 0) { return false; }
  2982. level--;
  2983. } else {
  2984. level++;
  2985. }
  2986. // Skip slash
  2987. while (i < path.size() && path[i] == '/') {
  2988. i++;
  2989. }
  2990. }
  2991. return true;
  2992. }
  2993. inline FileStat::FileStat(const std::string &path) {
  2994. #if defined(_WIN32)
  2995. auto wpath = u8string_to_wstring(path.c_str());
  2996. ret_ = _wstat(wpath.c_str(), &st_);
  2997. #else
  2998. ret_ = stat(path.c_str(), &st_);
  2999. #endif
  3000. }
  3001. inline bool FileStat::is_file() const {
  3002. return ret_ >= 0 && S_ISREG(st_.st_mode);
  3003. }
  3004. inline bool FileStat::is_dir() const {
  3005. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  3006. }
  3007. inline time_t FileStat::mtime() const {
  3008. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  3009. : static_cast<time_t>(-1);
  3010. }
  3011. inline size_t FileStat::size() const {
  3012. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  3013. }
  3014. inline std::string encode_path(const std::string &s) {
  3015. std::string result;
  3016. result.reserve(s.size());
  3017. for (size_t i = 0; s[i]; i++) {
  3018. switch (s[i]) {
  3019. case ' ': result += "%20"; break;
  3020. case '+': result += "%2B"; break;
  3021. case '\r': result += "%0D"; break;
  3022. case '\n': result += "%0A"; break;
  3023. case '\'': result += "%27"; break;
  3024. case ',': result += "%2C"; break;
  3025. // case ':': result += "%3A"; break; // ok? probably...
  3026. case ';': result += "%3B"; break;
  3027. default:
  3028. auto c = static_cast<uint8_t>(s[i]);
  3029. if (c >= 0x80) {
  3030. result += '%';
  3031. char hex[4];
  3032. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  3033. assert(len == 2);
  3034. result.append(hex, static_cast<size_t>(len));
  3035. } else {
  3036. result += s[i];
  3037. }
  3038. break;
  3039. }
  3040. }
  3041. return result;
  3042. }
  3043. inline std::string file_extension(const std::string &path) {
  3044. std::smatch m;
  3045. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  3046. if (std::regex_search(path, m, re)) { return m[1].str(); }
  3047. return std::string();
  3048. }
  3049. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  3050. template <typename T>
  3051. inline bool parse_header(const char *beg, const char *end, T fn);
  3052. template <typename T>
  3053. inline bool parse_header(const char *beg, const char *end, T fn) {
  3054. // Skip trailing spaces and tabs.
  3055. while (beg < end && is_space_or_tab(end[-1])) {
  3056. end--;
  3057. }
  3058. auto p = beg;
  3059. while (p < end && *p != ':') {
  3060. p++;
  3061. }
  3062. auto name = std::string(beg, p);
  3063. if (!detail::fields::is_field_name(name)) { return false; }
  3064. if (p == end) { return false; }
  3065. auto key_end = p;
  3066. if (*p++ != ':') { return false; }
  3067. while (p < end && is_space_or_tab(*p)) {
  3068. p++;
  3069. }
  3070. if (p <= end) {
  3071. auto key_len = key_end - beg;
  3072. if (!key_len) { return false; }
  3073. auto key = std::string(beg, key_end);
  3074. auto val = std::string(p, end);
  3075. if (!detail::fields::is_field_value(val)) { return false; }
  3076. if (case_ignore::equal(key, "Location") ||
  3077. case_ignore::equal(key, "Referer")) {
  3078. fn(key, val);
  3079. } else {
  3080. fn(key, decode_path_component(val));
  3081. }
  3082. return true;
  3083. }
  3084. return false;
  3085. }
  3086. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3087. const Headers &src_headers) {
  3088. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3089. // transfer coding is complete when a chunk with a chunk-size of zero is
  3090. // received, possibly followed by a trailer section, and finally terminated by
  3091. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3092. //
  3093. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3094. // doesn't care for the existence of the final CRLF. In other words, it seems
  3095. // to be ok whether the final CRLF exists or not in the chunked data.
  3096. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3097. //
  3098. // According to the reference code in RFC 9112, cpp-httplib now allows
  3099. // chunked transfer coding data without the final CRLF.
  3100. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3101. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3102. "transfer-encoding",
  3103. "content-length",
  3104. "host",
  3105. "authorization",
  3106. "www-authenticate",
  3107. "proxy-authenticate",
  3108. "proxy-authorization",
  3109. "cookie",
  3110. "set-cookie",
  3111. "cache-control",
  3112. "expect",
  3113. "max-forwards",
  3114. "pragma",
  3115. "range",
  3116. "te",
  3117. "age",
  3118. "expires",
  3119. "date",
  3120. "location",
  3121. "retry-after",
  3122. "vary",
  3123. "warning",
  3124. "content-encoding",
  3125. "content-type",
  3126. "content-range",
  3127. "trailer"};
  3128. case_ignore::unordered_set<std::string> declared_trailers;
  3129. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  3130. if (trailer_header && std::strlen(trailer_header)) {
  3131. auto len = std::strlen(trailer_header);
  3132. split(trailer_header, trailer_header + len, ',',
  3133. [&](const char *b, const char *e) {
  3134. const char *kbeg = b;
  3135. const char *kend = e;
  3136. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  3137. ++kbeg;
  3138. }
  3139. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  3140. --kend;
  3141. }
  3142. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  3143. if (!key.empty() &&
  3144. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  3145. declared_trailers.insert(key);
  3146. }
  3147. });
  3148. }
  3149. size_t trailer_header_count = 0;
  3150. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3151. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3152. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3153. constexpr auto line_terminator_len = 2;
  3154. auto line_beg = line_reader.ptr();
  3155. auto line_end =
  3156. line_reader.ptr() + line_reader.size() - line_terminator_len;
  3157. if (!parse_header(line_beg, line_end,
  3158. [&](const std::string &key, const std::string &val) {
  3159. if (declared_trailers.find(key) !=
  3160. declared_trailers.end()) {
  3161. dest.emplace(key, val);
  3162. trailer_header_count++;
  3163. }
  3164. })) {
  3165. return false;
  3166. }
  3167. if (!line_reader.getline()) { return false; }
  3168. }
  3169. return true;
  3170. }
  3171. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  3172. size_t right) {
  3173. while (b + left < e && is_space_or_tab(b[left])) {
  3174. left++;
  3175. }
  3176. while (right > 0 && is_space_or_tab(b[right - 1])) {
  3177. right--;
  3178. }
  3179. return std::make_pair(left, right);
  3180. }
  3181. inline std::string trim_copy(const std::string &s) {
  3182. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  3183. return s.substr(r.first, r.second - r.first);
  3184. }
  3185. inline std::string trim_double_quotes_copy(const std::string &s) {
  3186. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  3187. return s.substr(1, s.size() - 2);
  3188. }
  3189. return s;
  3190. }
  3191. inline void
  3192. divide(const char *data, std::size_t size, char d,
  3193. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3194. fn) {
  3195. const auto it = std::find(data, data + size, d);
  3196. const auto found = static_cast<std::size_t>(it != data + size);
  3197. const auto lhs_data = data;
  3198. const auto lhs_size = static_cast<std::size_t>(it - data);
  3199. const auto rhs_data = it + found;
  3200. const auto rhs_size = size - lhs_size - found;
  3201. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  3202. }
  3203. inline void
  3204. divide(const std::string &str, char d,
  3205. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3206. fn) {
  3207. divide(str.data(), str.size(), d, std::move(fn));
  3208. }
  3209. inline void split(const char *b, const char *e, char d,
  3210. std::function<void(const char *, const char *)> fn) {
  3211. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  3212. }
  3213. inline void split(const char *b, const char *e, char d, size_t m,
  3214. std::function<void(const char *, const char *)> fn) {
  3215. size_t i = 0;
  3216. size_t beg = 0;
  3217. size_t count = 1;
  3218. while (e ? (b + i < e) : (b[i] != '\0')) {
  3219. if (b[i] == d && count < m) {
  3220. auto r = trim(b, e, beg, i);
  3221. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3222. beg = i + 1;
  3223. count++;
  3224. }
  3225. i++;
  3226. }
  3227. if (i) {
  3228. auto r = trim(b, e, beg, i);
  3229. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3230. }
  3231. }
  3232. inline bool split_find(const char *b, const char *e, char d, size_t m,
  3233. std::function<bool(const char *, const char *)> fn) {
  3234. size_t i = 0;
  3235. size_t beg = 0;
  3236. size_t count = 1;
  3237. while (e ? (b + i < e) : (b[i] != '\0')) {
  3238. if (b[i] == d && count < m) {
  3239. auto r = trim(b, e, beg, i);
  3240. if (r.first < r.second) {
  3241. auto found = fn(&b[r.first], &b[r.second]);
  3242. if (found) { return true; }
  3243. }
  3244. beg = i + 1;
  3245. count++;
  3246. }
  3247. i++;
  3248. }
  3249. if (i) {
  3250. auto r = trim(b, e, beg, i);
  3251. if (r.first < r.second) {
  3252. auto found = fn(&b[r.first], &b[r.second]);
  3253. if (found) { return true; }
  3254. }
  3255. }
  3256. return false;
  3257. }
  3258. inline bool split_find(const char *b, const char *e, char d,
  3259. std::function<bool(const char *, const char *)> fn) {
  3260. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  3261. std::move(fn));
  3262. }
  3263. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  3264. size_t fixed_buffer_size)
  3265. : strm_(strm), fixed_buffer_(fixed_buffer),
  3266. fixed_buffer_size_(fixed_buffer_size) {}
  3267. inline const char *stream_line_reader::ptr() const {
  3268. if (growable_buffer_.empty()) {
  3269. return fixed_buffer_;
  3270. } else {
  3271. return growable_buffer_.data();
  3272. }
  3273. }
  3274. inline size_t stream_line_reader::size() const {
  3275. if (growable_buffer_.empty()) {
  3276. return fixed_buffer_used_size_;
  3277. } else {
  3278. return growable_buffer_.size();
  3279. }
  3280. }
  3281. inline bool stream_line_reader::end_with_crlf() const {
  3282. auto end = ptr() + size();
  3283. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  3284. }
  3285. inline bool stream_line_reader::getline() {
  3286. fixed_buffer_used_size_ = 0;
  3287. growable_buffer_.clear();
  3288. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3289. char prev_byte = 0;
  3290. #endif
  3291. for (size_t i = 0;; i++) {
  3292. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  3293. // Treat exceptionally long lines as an error to
  3294. // prevent infinite loops/memory exhaustion
  3295. return false;
  3296. }
  3297. char byte;
  3298. auto n = strm_.read(&byte, 1);
  3299. if (n < 0) {
  3300. return false;
  3301. } else if (n == 0) {
  3302. if (i == 0) {
  3303. return false;
  3304. } else {
  3305. break;
  3306. }
  3307. }
  3308. append(byte);
  3309. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3310. if (byte == '\n') { break; }
  3311. #else
  3312. if (prev_byte == '\r' && byte == '\n') { break; }
  3313. prev_byte = byte;
  3314. #endif
  3315. }
  3316. return true;
  3317. }
  3318. inline void stream_line_reader::append(char c) {
  3319. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  3320. fixed_buffer_[fixed_buffer_used_size_++] = c;
  3321. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  3322. } else {
  3323. if (growable_buffer_.empty()) {
  3324. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  3325. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  3326. }
  3327. growable_buffer_ += c;
  3328. }
  3329. }
  3330. inline mmap::mmap(const char *path) { open(path); }
  3331. inline mmap::~mmap() { close(); }
  3332. inline bool mmap::open(const char *path) {
  3333. close();
  3334. #if defined(_WIN32)
  3335. auto wpath = u8string_to_wstring(path);
  3336. if (wpath.empty()) { return false; }
  3337. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  3338. OPEN_EXISTING, NULL);
  3339. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  3340. LARGE_INTEGER size{};
  3341. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  3342. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  3343. // See:
  3344. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  3345. if (static_cast<ULONGLONG>(size.QuadPart) >
  3346. (std::numeric_limits<decltype(size_)>::max)()) {
  3347. // `size_t` might be 32-bits, on 32-bits Windows.
  3348. return false;
  3349. }
  3350. size_ = static_cast<size_t>(size.QuadPart);
  3351. hMapping_ =
  3352. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  3353. // Special treatment for an empty file...
  3354. if (hMapping_ == NULL && size_ == 0) {
  3355. close();
  3356. is_open_empty_file = true;
  3357. return true;
  3358. }
  3359. if (hMapping_ == NULL) {
  3360. close();
  3361. return false;
  3362. }
  3363. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  3364. if (addr_ == nullptr) {
  3365. close();
  3366. return false;
  3367. }
  3368. #else
  3369. fd_ = ::open(path, O_RDONLY);
  3370. if (fd_ == -1) { return false; }
  3371. struct stat sb;
  3372. if (fstat(fd_, &sb) == -1) {
  3373. close();
  3374. return false;
  3375. }
  3376. size_ = static_cast<size_t>(sb.st_size);
  3377. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  3378. // Special treatment for an empty file...
  3379. if (addr_ == MAP_FAILED && size_ == 0) {
  3380. close();
  3381. is_open_empty_file = true;
  3382. return false;
  3383. }
  3384. #endif
  3385. return true;
  3386. }
  3387. inline bool mmap::is_open() const {
  3388. return is_open_empty_file ? true : addr_ != nullptr;
  3389. }
  3390. inline size_t mmap::size() const { return size_; }
  3391. inline const char *mmap::data() const {
  3392. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  3393. }
  3394. inline void mmap::close() {
  3395. #if defined(_WIN32)
  3396. if (addr_) {
  3397. ::UnmapViewOfFile(addr_);
  3398. addr_ = nullptr;
  3399. }
  3400. if (hMapping_) {
  3401. ::CloseHandle(hMapping_);
  3402. hMapping_ = NULL;
  3403. }
  3404. if (hFile_ != INVALID_HANDLE_VALUE) {
  3405. ::CloseHandle(hFile_);
  3406. hFile_ = INVALID_HANDLE_VALUE;
  3407. }
  3408. is_open_empty_file = false;
  3409. #else
  3410. if (addr_ != nullptr) {
  3411. munmap(addr_, size_);
  3412. addr_ = nullptr;
  3413. }
  3414. if (fd_ != -1) {
  3415. ::close(fd_);
  3416. fd_ = -1;
  3417. }
  3418. #endif
  3419. size_ = 0;
  3420. }
  3421. inline int close_socket(socket_t sock) {
  3422. #ifdef _WIN32
  3423. return closesocket(sock);
  3424. #else
  3425. return close(sock);
  3426. #endif
  3427. }
  3428. template <typename T> inline ssize_t handle_EINTR(T fn) {
  3429. ssize_t res = 0;
  3430. while (true) {
  3431. res = fn();
  3432. if (res < 0 && errno == EINTR) {
  3433. std::this_thread::sleep_for(std::chrono::microseconds{1});
  3434. continue;
  3435. }
  3436. break;
  3437. }
  3438. return res;
  3439. }
  3440. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  3441. return handle_EINTR([&]() {
  3442. return recv(sock,
  3443. #ifdef _WIN32
  3444. static_cast<char *>(ptr), static_cast<int>(size),
  3445. #else
  3446. ptr, size,
  3447. #endif
  3448. flags);
  3449. });
  3450. }
  3451. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  3452. int flags) {
  3453. return handle_EINTR([&]() {
  3454. return send(sock,
  3455. #ifdef _WIN32
  3456. static_cast<const char *>(ptr), static_cast<int>(size),
  3457. #else
  3458. ptr, size,
  3459. #endif
  3460. flags);
  3461. });
  3462. }
  3463. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  3464. #ifdef _WIN32
  3465. return ::WSAPoll(fds, nfds, timeout);
  3466. #else
  3467. return ::poll(fds, nfds, timeout);
  3468. #endif
  3469. }
  3470. template <bool Read>
  3471. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  3472. #ifdef __APPLE__
  3473. if (sock >= FD_SETSIZE) { return -1; }
  3474. fd_set fds, *rfds, *wfds;
  3475. FD_ZERO(&fds);
  3476. FD_SET(sock, &fds);
  3477. rfds = (Read ? &fds : nullptr);
  3478. wfds = (Read ? nullptr : &fds);
  3479. timeval tv;
  3480. tv.tv_sec = static_cast<long>(sec);
  3481. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3482. return handle_EINTR([&]() {
  3483. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  3484. });
  3485. #else
  3486. struct pollfd pfd;
  3487. pfd.fd = sock;
  3488. pfd.events = (Read ? POLLIN : POLLOUT);
  3489. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3490. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  3491. #endif
  3492. }
  3493. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  3494. return select_impl<true>(sock, sec, usec);
  3495. }
  3496. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  3497. return select_impl<false>(sock, sec, usec);
  3498. }
  3499. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  3500. time_t usec) {
  3501. #ifdef __APPLE__
  3502. if (sock >= FD_SETSIZE) { return Error::Connection; }
  3503. fd_set fdsr, fdsw;
  3504. FD_ZERO(&fdsr);
  3505. FD_ZERO(&fdsw);
  3506. FD_SET(sock, &fdsr);
  3507. FD_SET(sock, &fdsw);
  3508. timeval tv;
  3509. tv.tv_sec = static_cast<long>(sec);
  3510. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3511. auto ret = handle_EINTR([&]() {
  3512. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  3513. });
  3514. if (ret == 0) { return Error::ConnectionTimeout; }
  3515. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  3516. auto error = 0;
  3517. socklen_t len = sizeof(error);
  3518. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3519. reinterpret_cast<char *>(&error), &len);
  3520. auto successful = res >= 0 && !error;
  3521. return successful ? Error::Success : Error::Connection;
  3522. }
  3523. return Error::Connection;
  3524. #else
  3525. struct pollfd pfd_read;
  3526. pfd_read.fd = sock;
  3527. pfd_read.events = POLLIN | POLLOUT;
  3528. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3529. auto poll_res =
  3530. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  3531. if (poll_res == 0) { return Error::ConnectionTimeout; }
  3532. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  3533. auto error = 0;
  3534. socklen_t len = sizeof(error);
  3535. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3536. reinterpret_cast<char *>(&error), &len);
  3537. auto successful = res >= 0 && !error;
  3538. return successful ? Error::Success : Error::Connection;
  3539. }
  3540. return Error::Connection;
  3541. #endif
  3542. }
  3543. inline bool is_socket_alive(socket_t sock) {
  3544. const auto val = detail::select_read(sock, 0, 0);
  3545. if (val == 0) {
  3546. return true;
  3547. } else if (val < 0 && errno == EBADF) {
  3548. return false;
  3549. }
  3550. char buf[1];
  3551. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  3552. }
  3553. class SocketStream final : public Stream {
  3554. public:
  3555. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3556. time_t write_timeout_sec, time_t write_timeout_usec,
  3557. time_t max_timeout_msec = 0,
  3558. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3559. (std::chrono::steady_clock::time_point::min)());
  3560. ~SocketStream() override;
  3561. bool is_readable() const override;
  3562. bool wait_readable() const override;
  3563. bool wait_writable() const override;
  3564. ssize_t read(char *ptr, size_t size) override;
  3565. ssize_t write(const char *ptr, size_t size) override;
  3566. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3567. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3568. socket_t socket() const override;
  3569. time_t duration() const override;
  3570. private:
  3571. socket_t sock_;
  3572. time_t read_timeout_sec_;
  3573. time_t read_timeout_usec_;
  3574. time_t write_timeout_sec_;
  3575. time_t write_timeout_usec_;
  3576. time_t max_timeout_msec_;
  3577. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3578. std::vector<char> read_buff_;
  3579. size_t read_buff_off_ = 0;
  3580. size_t read_buff_content_size_ = 0;
  3581. static const size_t read_buff_size_ = 1024l * 4;
  3582. };
  3583. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3584. class SSLSocketStream final : public Stream {
  3585. public:
  3586. SSLSocketStream(
  3587. socket_t sock, SSL *ssl, time_t read_timeout_sec,
  3588. time_t read_timeout_usec, time_t write_timeout_sec,
  3589. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  3590. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3591. (std::chrono::steady_clock::time_point::min)());
  3592. ~SSLSocketStream() override;
  3593. bool is_readable() const override;
  3594. bool wait_readable() const override;
  3595. bool wait_writable() const override;
  3596. ssize_t read(char *ptr, size_t size) override;
  3597. ssize_t write(const char *ptr, size_t size) override;
  3598. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3599. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3600. socket_t socket() const override;
  3601. time_t duration() const override;
  3602. private:
  3603. socket_t sock_;
  3604. SSL *ssl_;
  3605. time_t read_timeout_sec_;
  3606. time_t read_timeout_usec_;
  3607. time_t write_timeout_sec_;
  3608. time_t write_timeout_usec_;
  3609. time_t max_timeout_msec_;
  3610. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3611. };
  3612. #endif
  3613. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3614. time_t keep_alive_timeout_sec) {
  3615. using namespace std::chrono;
  3616. const auto interval_usec =
  3617. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  3618. // Avoid expensive `steady_clock::now()` call for the first time
  3619. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  3620. const auto start = steady_clock::now() - microseconds{interval_usec};
  3621. const auto timeout = seconds{keep_alive_timeout_sec};
  3622. while (true) {
  3623. if (svr_sock == INVALID_SOCKET) {
  3624. break; // Server socket is closed
  3625. }
  3626. auto val = select_read(sock, 0, interval_usec);
  3627. if (val < 0) {
  3628. break; // Ssocket error
  3629. } else if (val == 0) {
  3630. if (steady_clock::now() - start > timeout) {
  3631. break; // Timeout
  3632. }
  3633. } else {
  3634. return true; // Ready for read
  3635. }
  3636. }
  3637. return false;
  3638. }
  3639. template <typename T>
  3640. inline bool
  3641. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3642. size_t keep_alive_max_count,
  3643. time_t keep_alive_timeout_sec, T callback) {
  3644. assert(keep_alive_max_count > 0);
  3645. auto ret = false;
  3646. auto count = keep_alive_max_count;
  3647. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  3648. auto close_connection = count == 1;
  3649. auto connection_closed = false;
  3650. ret = callback(close_connection, connection_closed);
  3651. if (!ret || connection_closed) { break; }
  3652. count--;
  3653. }
  3654. return ret;
  3655. }
  3656. template <typename T>
  3657. inline bool
  3658. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3659. size_t keep_alive_max_count,
  3660. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  3661. time_t read_timeout_usec, time_t write_timeout_sec,
  3662. time_t write_timeout_usec, T callback) {
  3663. return process_server_socket_core(
  3664. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  3665. [&](bool close_connection, bool &connection_closed) {
  3666. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3667. write_timeout_sec, write_timeout_usec);
  3668. return callback(strm, close_connection, connection_closed);
  3669. });
  3670. }
  3671. inline bool process_client_socket(
  3672. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3673. time_t write_timeout_sec, time_t write_timeout_usec,
  3674. time_t max_timeout_msec,
  3675. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3676. std::function<bool(Stream &)> callback) {
  3677. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3678. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  3679. start_time);
  3680. return callback(strm);
  3681. }
  3682. inline int shutdown_socket(socket_t sock) {
  3683. #ifdef _WIN32
  3684. return shutdown(sock, SD_BOTH);
  3685. #else
  3686. return shutdown(sock, SHUT_RDWR);
  3687. #endif
  3688. }
  3689. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  3690. if (s.size() > 1 && s[0] == '\0') {
  3691. auto ret = s;
  3692. ret[0] = '@';
  3693. return ret;
  3694. }
  3695. return s;
  3696. }
  3697. inline std::string
  3698. unescape_abstract_namespace_unix_domain(const std::string &s) {
  3699. if (s.size() > 1 && s[0] == '@') {
  3700. auto ret = s;
  3701. ret[0] = '\0';
  3702. return ret;
  3703. }
  3704. return s;
  3705. }
  3706. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  3707. const struct addrinfo *hints,
  3708. struct addrinfo **res, time_t timeout_sec) {
  3709. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  3710. if (timeout_sec <= 0) {
  3711. // No timeout specified, use standard getaddrinfo
  3712. return getaddrinfo(node, service, hints, res);
  3713. }
  3714. #ifdef _WIN32
  3715. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  3716. OVERLAPPED overlapped = {0};
  3717. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  3718. if (!event) { return EAI_FAIL; }
  3719. overlapped.hEvent = event;
  3720. PADDRINFOEXW result_addrinfo = nullptr;
  3721. HANDLE cancel_handle = nullptr;
  3722. ADDRINFOEXW hints_ex = {0};
  3723. if (hints) {
  3724. hints_ex.ai_flags = hints->ai_flags;
  3725. hints_ex.ai_family = hints->ai_family;
  3726. hints_ex.ai_socktype = hints->ai_socktype;
  3727. hints_ex.ai_protocol = hints->ai_protocol;
  3728. }
  3729. auto wnode = u8string_to_wstring(node);
  3730. auto wservice = u8string_to_wstring(service);
  3731. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  3732. hints ? &hints_ex : nullptr, &result_addrinfo,
  3733. nullptr, &overlapped, nullptr, &cancel_handle);
  3734. if (ret == WSA_IO_PENDING) {
  3735. auto wait_result =
  3736. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  3737. if (wait_result == WAIT_TIMEOUT) {
  3738. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  3739. ::CloseHandle(event);
  3740. return EAI_AGAIN;
  3741. }
  3742. DWORD bytes_returned;
  3743. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  3744. &bytes_returned, FALSE)) {
  3745. ::CloseHandle(event);
  3746. return ::WSAGetLastError();
  3747. }
  3748. }
  3749. ::CloseHandle(event);
  3750. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  3751. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  3752. return 0;
  3753. }
  3754. return ret;
  3755. #elif TARGET_OS_MAC
  3756. if (!node) { return EAI_NONAME; }
  3757. // macOS implementation using CFHost API for asynchronous DNS resolution
  3758. CFStringRef hostname_ref = CFStringCreateWithCString(
  3759. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  3760. if (!hostname_ref) { return EAI_MEMORY; }
  3761. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  3762. CFRelease(hostname_ref);
  3763. if (!host_ref) { return EAI_MEMORY; }
  3764. // Set up context for callback
  3765. struct CFHostContext {
  3766. bool completed = false;
  3767. bool success = false;
  3768. CFArrayRef addresses = nullptr;
  3769. std::mutex mutex;
  3770. std::condition_variable cv;
  3771. } context;
  3772. CFHostClientContext client_context;
  3773. memset(&client_context, 0, sizeof(client_context));
  3774. client_context.info = &context;
  3775. // Set callback
  3776. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  3777. const CFStreamError *error, void *info) {
  3778. auto ctx = static_cast<CFHostContext *>(info);
  3779. std::lock_guard<std::mutex> lock(ctx->mutex);
  3780. if (error && error->error != 0) {
  3781. ctx->success = false;
  3782. } else {
  3783. Boolean hasBeenResolved;
  3784. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  3785. if (ctx->addresses && hasBeenResolved) {
  3786. CFRetain(ctx->addresses);
  3787. ctx->success = true;
  3788. } else {
  3789. ctx->success = false;
  3790. }
  3791. }
  3792. ctx->completed = true;
  3793. ctx->cv.notify_one();
  3794. };
  3795. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  3796. CFRelease(host_ref);
  3797. return EAI_SYSTEM;
  3798. }
  3799. // Schedule on run loop
  3800. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  3801. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3802. // Start resolution
  3803. CFStreamError stream_error;
  3804. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  3805. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3806. CFRelease(host_ref);
  3807. return EAI_FAIL;
  3808. }
  3809. // Wait for completion with timeout
  3810. auto timeout_time =
  3811. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  3812. bool timed_out = false;
  3813. {
  3814. std::unique_lock<std::mutex> lock(context.mutex);
  3815. while (!context.completed) {
  3816. auto now = std::chrono::steady_clock::now();
  3817. if (now >= timeout_time) {
  3818. timed_out = true;
  3819. break;
  3820. }
  3821. // Run the runloop for a short time
  3822. lock.unlock();
  3823. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  3824. lock.lock();
  3825. }
  3826. }
  3827. // Clean up
  3828. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3829. CFHostSetClient(host_ref, nullptr, nullptr);
  3830. if (timed_out || !context.completed) {
  3831. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  3832. CFRelease(host_ref);
  3833. return EAI_AGAIN;
  3834. }
  3835. if (!context.success || !context.addresses) {
  3836. CFRelease(host_ref);
  3837. return EAI_NODATA;
  3838. }
  3839. // Convert CFArray to addrinfo
  3840. CFIndex count = CFArrayGetCount(context.addresses);
  3841. if (count == 0) {
  3842. CFRelease(context.addresses);
  3843. CFRelease(host_ref);
  3844. return EAI_NODATA;
  3845. }
  3846. struct addrinfo *result_addrinfo = nullptr;
  3847. struct addrinfo **current = &result_addrinfo;
  3848. for (CFIndex i = 0; i < count; i++) {
  3849. CFDataRef addr_data =
  3850. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  3851. if (!addr_data) continue;
  3852. const struct sockaddr *sockaddr_ptr =
  3853. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  3854. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  3855. // Allocate addrinfo structure
  3856. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  3857. if (!*current) {
  3858. freeaddrinfo(result_addrinfo);
  3859. CFRelease(context.addresses);
  3860. CFRelease(host_ref);
  3861. return EAI_MEMORY;
  3862. }
  3863. memset(*current, 0, sizeof(struct addrinfo));
  3864. // Set up addrinfo fields
  3865. (*current)->ai_family = sockaddr_ptr->sa_family;
  3866. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  3867. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  3868. (*current)->ai_addrlen = sockaddr_len;
  3869. // Copy sockaddr
  3870. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  3871. if (!(*current)->ai_addr) {
  3872. freeaddrinfo(result_addrinfo);
  3873. CFRelease(context.addresses);
  3874. CFRelease(host_ref);
  3875. return EAI_MEMORY;
  3876. }
  3877. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  3878. // Set port if service is specified
  3879. if (service && strlen(service) > 0) {
  3880. int port = atoi(service);
  3881. if (port > 0) {
  3882. if (sockaddr_ptr->sa_family == AF_INET) {
  3883. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  3884. ->sin_port = htons(static_cast<uint16_t>(port));
  3885. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  3886. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  3887. ->sin6_port = htons(static_cast<uint16_t>(port));
  3888. }
  3889. }
  3890. }
  3891. current = &((*current)->ai_next);
  3892. }
  3893. CFRelease(context.addresses);
  3894. CFRelease(host_ref);
  3895. *res = result_addrinfo;
  3896. return 0;
  3897. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  3898. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  3899. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  3900. struct gaicb request;
  3901. struct gaicb *requests[1] = {&request};
  3902. struct sigevent sevp;
  3903. struct timespec timeout;
  3904. // Initialize the request structure
  3905. memset(&request, 0, sizeof(request));
  3906. request.ar_name = node;
  3907. request.ar_service = service;
  3908. request.ar_request = hints;
  3909. // Set up timeout
  3910. timeout.tv_sec = timeout_sec;
  3911. timeout.tv_nsec = 0;
  3912. // Initialize sigevent structure (not used, but required)
  3913. memset(&sevp, 0, sizeof(sevp));
  3914. sevp.sigev_notify = SIGEV_NONE;
  3915. // Start asynchronous resolution
  3916. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  3917. if (start_result != 0) { return start_result; }
  3918. // Wait for completion with timeout
  3919. int wait_result =
  3920. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  3921. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  3922. // Completed successfully, get the result
  3923. int gai_result = gai_error(&request);
  3924. if (gai_result == 0) {
  3925. *res = request.ar_result;
  3926. return 0;
  3927. } else {
  3928. // Clean up on error
  3929. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  3930. return gai_result;
  3931. }
  3932. } else if (wait_result == EAI_AGAIN) {
  3933. // Timeout occurred, cancel the request
  3934. gai_cancel(&request);
  3935. return EAI_AGAIN;
  3936. } else {
  3937. // Other error occurred
  3938. gai_cancel(&request);
  3939. return wait_result;
  3940. }
  3941. #else
  3942. // Fallback implementation using thread-based timeout for other Unix systems
  3943. struct GetAddrInfoState {
  3944. ~GetAddrInfoState() {
  3945. if (info) { freeaddrinfo(info); }
  3946. }
  3947. std::mutex mutex;
  3948. std::condition_variable result_cv;
  3949. bool completed = false;
  3950. int result = EAI_SYSTEM;
  3951. std::string node;
  3952. std::string service;
  3953. struct addrinfo hints;
  3954. struct addrinfo *info = nullptr;
  3955. };
  3956. // Allocate on the heap, so the resolver thread can keep using the data.
  3957. auto state = std::make_shared<GetAddrInfoState>();
  3958. if (node) { state->node = node; }
  3959. state->service = service;
  3960. state->hints = *hints;
  3961. std::thread resolve_thread([state]() {
  3962. auto thread_result =
  3963. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  3964. &state->info);
  3965. std::lock_guard<std::mutex> lock(state->mutex);
  3966. state->result = thread_result;
  3967. state->completed = true;
  3968. state->result_cv.notify_one();
  3969. });
  3970. // Wait for completion or timeout
  3971. std::unique_lock<std::mutex> lock(state->mutex);
  3972. auto finished =
  3973. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  3974. [&] { return state->completed; });
  3975. if (finished) {
  3976. // Operation completed within timeout
  3977. resolve_thread.join();
  3978. *res = state->info;
  3979. state->info = nullptr; // Pass ownership to caller
  3980. return state->result;
  3981. } else {
  3982. // Timeout occurred
  3983. resolve_thread.detach(); // Let the thread finish in background
  3984. return EAI_AGAIN; // Return timeout error
  3985. }
  3986. #endif
  3987. #else
  3988. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  3989. return getaddrinfo(node, service, hints, res);
  3990. #endif
  3991. }
  3992. template <typename BindOrConnect>
  3993. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  3994. int address_family, int socket_flags, bool tcp_nodelay,
  3995. bool ipv6_v6only, SocketOptions socket_options,
  3996. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  3997. // Get address info
  3998. const char *node = nullptr;
  3999. struct addrinfo hints;
  4000. struct addrinfo *result;
  4001. memset(&hints, 0, sizeof(struct addrinfo));
  4002. hints.ai_socktype = SOCK_STREAM;
  4003. hints.ai_protocol = IPPROTO_IP;
  4004. if (!ip.empty()) {
  4005. node = ip.c_str();
  4006. // Ask getaddrinfo to convert IP in c-string to address
  4007. hints.ai_family = AF_UNSPEC;
  4008. hints.ai_flags = AI_NUMERICHOST;
  4009. } else {
  4010. if (!host.empty()) { node = host.c_str(); }
  4011. hints.ai_family = address_family;
  4012. hints.ai_flags = socket_flags;
  4013. }
  4014. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  4015. if (hints.ai_family == AF_UNIX) {
  4016. const auto addrlen = host.length();
  4017. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  4018. #ifdef SOCK_CLOEXEC
  4019. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  4020. hints.ai_protocol);
  4021. #else
  4022. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4023. #endif
  4024. if (sock != INVALID_SOCKET) {
  4025. sockaddr_un addr{};
  4026. addr.sun_family = AF_UNIX;
  4027. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  4028. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  4029. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  4030. hints.ai_addrlen = static_cast<socklen_t>(
  4031. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  4032. #ifndef SOCK_CLOEXEC
  4033. #ifndef _WIN32
  4034. fcntl(sock, F_SETFD, FD_CLOEXEC);
  4035. #endif
  4036. #endif
  4037. if (socket_options) { socket_options(sock); }
  4038. #ifdef _WIN32
  4039. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  4040. // remove the option.
  4041. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  4042. #endif
  4043. bool dummy;
  4044. if (!bind_or_connect(sock, hints, dummy)) {
  4045. close_socket(sock);
  4046. sock = INVALID_SOCKET;
  4047. }
  4048. }
  4049. return sock;
  4050. }
  4051. #endif
  4052. auto service = std::to_string(port);
  4053. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  4054. timeout_sec)) {
  4055. #if defined __linux__ && !defined __ANDROID__
  4056. res_init();
  4057. #endif
  4058. return INVALID_SOCKET;
  4059. }
  4060. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4061. for (auto rp = result; rp; rp = rp->ai_next) {
  4062. // Create a socket
  4063. #ifdef _WIN32
  4064. auto sock =
  4065. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  4066. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  4067. /**
  4068. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  4069. * and above the socket creation fails on older Windows Systems.
  4070. *
  4071. * Let's try to create a socket the old way in this case.
  4072. *
  4073. * Reference:
  4074. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  4075. *
  4076. * WSA_FLAG_NO_HANDLE_INHERIT:
  4077. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  4078. * SP1, and later
  4079. *
  4080. */
  4081. if (sock == INVALID_SOCKET) {
  4082. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4083. }
  4084. #else
  4085. #ifdef SOCK_CLOEXEC
  4086. auto sock =
  4087. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  4088. #else
  4089. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4090. #endif
  4091. #endif
  4092. if (sock == INVALID_SOCKET) { continue; }
  4093. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  4094. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  4095. close_socket(sock);
  4096. continue;
  4097. }
  4098. #endif
  4099. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  4100. if (rp->ai_family == AF_INET6) {
  4101. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  4102. }
  4103. if (socket_options) { socket_options(sock); }
  4104. // bind or connect
  4105. auto quit = false;
  4106. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  4107. close_socket(sock);
  4108. if (quit) { break; }
  4109. }
  4110. return INVALID_SOCKET;
  4111. }
  4112. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  4113. #ifdef _WIN32
  4114. auto flags = nonblocking ? 1UL : 0UL;
  4115. ioctlsocket(sock, FIONBIO, &flags);
  4116. #else
  4117. auto flags = fcntl(sock, F_GETFL, 0);
  4118. fcntl(sock, F_SETFL,
  4119. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  4120. #endif
  4121. }
  4122. inline bool is_connection_error() {
  4123. #ifdef _WIN32
  4124. return WSAGetLastError() != WSAEWOULDBLOCK;
  4125. #else
  4126. return errno != EINPROGRESS;
  4127. #endif
  4128. }
  4129. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  4130. struct addrinfo hints;
  4131. struct addrinfo *result;
  4132. memset(&hints, 0, sizeof(struct addrinfo));
  4133. hints.ai_family = AF_UNSPEC;
  4134. hints.ai_socktype = SOCK_STREAM;
  4135. hints.ai_protocol = 0;
  4136. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  4137. return false;
  4138. }
  4139. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4140. auto ret = false;
  4141. for (auto rp = result; rp; rp = rp->ai_next) {
  4142. const auto &ai = *rp;
  4143. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4144. ret = true;
  4145. break;
  4146. }
  4147. }
  4148. return ret;
  4149. }
  4150. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  4151. #define USE_IF2IP
  4152. #endif
  4153. #ifdef USE_IF2IP
  4154. inline std::string if2ip(int address_family, const std::string &ifn) {
  4155. struct ifaddrs *ifap;
  4156. getifaddrs(&ifap);
  4157. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  4158. std::string addr_candidate;
  4159. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  4160. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  4161. (AF_UNSPEC == address_family ||
  4162. ifa->ifa_addr->sa_family == address_family)) {
  4163. if (ifa->ifa_addr->sa_family == AF_INET) {
  4164. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  4165. char buf[INET_ADDRSTRLEN];
  4166. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  4167. return std::string(buf, INET_ADDRSTRLEN);
  4168. }
  4169. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  4170. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  4171. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  4172. char buf[INET6_ADDRSTRLEN] = {};
  4173. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  4174. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  4175. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  4176. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  4177. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  4178. } else {
  4179. return std::string(buf, INET6_ADDRSTRLEN);
  4180. }
  4181. }
  4182. }
  4183. }
  4184. }
  4185. }
  4186. return addr_candidate;
  4187. }
  4188. #endif
  4189. inline socket_t create_client_socket(
  4190. const std::string &host, const std::string &ip, int port,
  4191. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  4192. SocketOptions socket_options, time_t connection_timeout_sec,
  4193. time_t connection_timeout_usec, time_t read_timeout_sec,
  4194. time_t read_timeout_usec, time_t write_timeout_sec,
  4195. time_t write_timeout_usec, const std::string &intf, Error &error) {
  4196. auto sock = create_socket(
  4197. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  4198. std::move(socket_options),
  4199. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  4200. if (!intf.empty()) {
  4201. #ifdef USE_IF2IP
  4202. auto ip_from_if = if2ip(address_family, intf);
  4203. if (ip_from_if.empty()) { ip_from_if = intf; }
  4204. if (!bind_ip_address(sock2, ip_from_if)) {
  4205. error = Error::BindIPAddress;
  4206. return false;
  4207. }
  4208. #endif
  4209. }
  4210. set_nonblocking(sock2, true);
  4211. auto ret =
  4212. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  4213. if (ret < 0) {
  4214. if (is_connection_error()) {
  4215. error = Error::Connection;
  4216. return false;
  4217. }
  4218. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  4219. connection_timeout_usec);
  4220. if (error != Error::Success) {
  4221. if (error == Error::ConnectionTimeout) { quit = true; }
  4222. return false;
  4223. }
  4224. }
  4225. set_nonblocking(sock2, false);
  4226. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  4227. read_timeout_usec);
  4228. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  4229. write_timeout_usec);
  4230. error = Error::Success;
  4231. return true;
  4232. },
  4233. connection_timeout_sec); // Pass DNS timeout
  4234. if (sock != INVALID_SOCKET) {
  4235. error = Error::Success;
  4236. } else {
  4237. if (error == Error::Success) { error = Error::Connection; }
  4238. }
  4239. return sock;
  4240. }
  4241. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  4242. socklen_t addr_len, std::string &ip, int &port) {
  4243. if (addr.ss_family == AF_INET) {
  4244. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  4245. } else if (addr.ss_family == AF_INET6) {
  4246. port =
  4247. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  4248. } else {
  4249. return false;
  4250. }
  4251. std::array<char, NI_MAXHOST> ipstr{};
  4252. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  4253. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  4254. 0, NI_NUMERICHOST)) {
  4255. return false;
  4256. }
  4257. ip = ipstr.data();
  4258. return true;
  4259. }
  4260. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4261. struct sockaddr_storage addr;
  4262. socklen_t addr_len = sizeof(addr);
  4263. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4264. &addr_len)) {
  4265. get_ip_and_port(addr, addr_len, ip, port);
  4266. }
  4267. }
  4268. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4269. struct sockaddr_storage addr;
  4270. socklen_t addr_len = sizeof(addr);
  4271. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4272. &addr_len)) {
  4273. #ifndef _WIN32
  4274. if (addr.ss_family == AF_UNIX) {
  4275. #if defined(__linux__)
  4276. struct ucred ucred;
  4277. socklen_t len = sizeof(ucred);
  4278. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  4279. port = ucred.pid;
  4280. }
  4281. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  4282. pid_t pid;
  4283. socklen_t len = sizeof(pid);
  4284. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  4285. port = pid;
  4286. }
  4287. #endif
  4288. return;
  4289. }
  4290. #endif
  4291. get_ip_and_port(addr, addr_len, ip, port);
  4292. }
  4293. }
  4294. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  4295. unsigned int h) {
  4296. return (l == 0)
  4297. ? h
  4298. : str2tag_core(
  4299. s + 1, l - 1,
  4300. // Unsets the 6 high bits of h, therefore no overflow happens
  4301. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  4302. h * 33) ^
  4303. static_cast<unsigned char>(*s));
  4304. }
  4305. inline unsigned int str2tag(const std::string &s) {
  4306. return str2tag_core(s.data(), s.size(), 0);
  4307. }
  4308. namespace udl {
  4309. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  4310. return str2tag_core(s, l, 0);
  4311. }
  4312. } // namespace udl
  4313. inline std::string
  4314. find_content_type(const std::string &path,
  4315. const std::map<std::string, std::string> &user_data,
  4316. const std::string &default_content_type) {
  4317. auto ext = file_extension(path);
  4318. auto it = user_data.find(ext);
  4319. if (it != user_data.end()) { return it->second; }
  4320. using udl::operator""_t;
  4321. switch (str2tag(ext)) {
  4322. default: return default_content_type;
  4323. case "css"_t: return "text/css";
  4324. case "csv"_t: return "text/csv";
  4325. case "htm"_t:
  4326. case "html"_t: return "text/html";
  4327. case "js"_t:
  4328. case "mjs"_t: return "text/javascript";
  4329. case "txt"_t: return "text/plain";
  4330. case "vtt"_t: return "text/vtt";
  4331. case "apng"_t: return "image/apng";
  4332. case "avif"_t: return "image/avif";
  4333. case "bmp"_t: return "image/bmp";
  4334. case "gif"_t: return "image/gif";
  4335. case "png"_t: return "image/png";
  4336. case "svg"_t: return "image/svg+xml";
  4337. case "webp"_t: return "image/webp";
  4338. case "ico"_t: return "image/x-icon";
  4339. case "tif"_t: return "image/tiff";
  4340. case "tiff"_t: return "image/tiff";
  4341. case "jpg"_t:
  4342. case "jpeg"_t: return "image/jpeg";
  4343. case "mp4"_t: return "video/mp4";
  4344. case "mpeg"_t: return "video/mpeg";
  4345. case "webm"_t: return "video/webm";
  4346. case "mp3"_t: return "audio/mp3";
  4347. case "mpga"_t: return "audio/mpeg";
  4348. case "weba"_t: return "audio/webm";
  4349. case "wav"_t: return "audio/wave";
  4350. case "otf"_t: return "font/otf";
  4351. case "ttf"_t: return "font/ttf";
  4352. case "woff"_t: return "font/woff";
  4353. case "woff2"_t: return "font/woff2";
  4354. case "7z"_t: return "application/x-7z-compressed";
  4355. case "atom"_t: return "application/atom+xml";
  4356. case "pdf"_t: return "application/pdf";
  4357. case "json"_t: return "application/json";
  4358. case "rss"_t: return "application/rss+xml";
  4359. case "tar"_t: return "application/x-tar";
  4360. case "xht"_t:
  4361. case "xhtml"_t: return "application/xhtml+xml";
  4362. case "xslt"_t: return "application/xslt+xml";
  4363. case "xml"_t: return "application/xml";
  4364. case "gz"_t: return "application/gzip";
  4365. case "zip"_t: return "application/zip";
  4366. case "wasm"_t: return "application/wasm";
  4367. }
  4368. }
  4369. inline bool can_compress_content_type(const std::string &content_type) {
  4370. using udl::operator""_t;
  4371. auto tag = str2tag(content_type);
  4372. switch (tag) {
  4373. case "image/svg+xml"_t:
  4374. case "application/javascript"_t:
  4375. case "application/json"_t:
  4376. case "application/xml"_t:
  4377. case "application/protobuf"_t:
  4378. case "application/xhtml+xml"_t: return true;
  4379. case "text/event-stream"_t: return false;
  4380. default: return !content_type.rfind("text/", 0);
  4381. }
  4382. }
  4383. inline EncodingType encoding_type(const Request &req, const Response &res) {
  4384. auto ret =
  4385. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  4386. if (!ret) { return EncodingType::None; }
  4387. const auto &s = req.get_header_value("Accept-Encoding");
  4388. (void)(s);
  4389. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4390. // TODO: 'Accept-Encoding' has br, not br;q=0
  4391. ret = s.find("br") != std::string::npos;
  4392. if (ret) { return EncodingType::Brotli; }
  4393. #endif
  4394. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4395. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  4396. ret = s.find("gzip") != std::string::npos;
  4397. if (ret) { return EncodingType::Gzip; }
  4398. #endif
  4399. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4400. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  4401. ret = s.find("zstd") != std::string::npos;
  4402. if (ret) { return EncodingType::Zstd; }
  4403. #endif
  4404. return EncodingType::None;
  4405. }
  4406. inline bool nocompressor::compress(const char *data, size_t data_length,
  4407. bool /*last*/, Callback callback) {
  4408. if (!data_length) { return true; }
  4409. return callback(data, data_length);
  4410. }
  4411. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4412. inline gzip_compressor::gzip_compressor() {
  4413. std::memset(&strm_, 0, sizeof(strm_));
  4414. strm_.zalloc = Z_NULL;
  4415. strm_.zfree = Z_NULL;
  4416. strm_.opaque = Z_NULL;
  4417. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  4418. Z_DEFAULT_STRATEGY) == Z_OK;
  4419. }
  4420. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  4421. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  4422. bool last, Callback callback) {
  4423. assert(is_valid_);
  4424. do {
  4425. constexpr size_t max_avail_in =
  4426. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4427. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4428. (std::min)(data_length, max_avail_in));
  4429. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4430. data_length -= strm_.avail_in;
  4431. data += strm_.avail_in;
  4432. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  4433. auto ret = Z_OK;
  4434. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4435. do {
  4436. strm_.avail_out = static_cast<uInt>(buff.size());
  4437. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4438. ret = deflate(&strm_, flush);
  4439. if (ret == Z_STREAM_ERROR) { return false; }
  4440. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4441. return false;
  4442. }
  4443. } while (strm_.avail_out == 0);
  4444. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  4445. (flush == Z_NO_FLUSH && ret == Z_OK));
  4446. assert(strm_.avail_in == 0);
  4447. } while (data_length > 0);
  4448. return true;
  4449. }
  4450. inline gzip_decompressor::gzip_decompressor() {
  4451. std::memset(&strm_, 0, sizeof(strm_));
  4452. strm_.zalloc = Z_NULL;
  4453. strm_.zfree = Z_NULL;
  4454. strm_.opaque = Z_NULL;
  4455. // 15 is the value of wbits, which should be at the maximum possible value
  4456. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  4457. // that the stream type should be automatically detected either gzip or
  4458. // deflate.
  4459. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  4460. }
  4461. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  4462. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  4463. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  4464. Callback callback) {
  4465. assert(is_valid_);
  4466. auto ret = Z_OK;
  4467. do {
  4468. constexpr size_t max_avail_in =
  4469. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4470. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4471. (std::min)(data_length, max_avail_in));
  4472. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4473. data_length -= strm_.avail_in;
  4474. data += strm_.avail_in;
  4475. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4476. while (strm_.avail_in > 0 && ret == Z_OK) {
  4477. strm_.avail_out = static_cast<uInt>(buff.size());
  4478. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4479. ret = inflate(&strm_, Z_NO_FLUSH);
  4480. assert(ret != Z_STREAM_ERROR);
  4481. switch (ret) {
  4482. case Z_NEED_DICT:
  4483. case Z_DATA_ERROR:
  4484. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  4485. }
  4486. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4487. return false;
  4488. }
  4489. }
  4490. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  4491. } while (data_length > 0);
  4492. return true;
  4493. }
  4494. #endif
  4495. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4496. inline brotli_compressor::brotli_compressor() {
  4497. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  4498. }
  4499. inline brotli_compressor::~brotli_compressor() {
  4500. BrotliEncoderDestroyInstance(state_);
  4501. }
  4502. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  4503. bool last, Callback callback) {
  4504. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4505. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  4506. auto available_in = data_length;
  4507. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4508. for (;;) {
  4509. if (last) {
  4510. if (BrotliEncoderIsFinished(state_)) { break; }
  4511. } else {
  4512. if (!available_in) { break; }
  4513. }
  4514. auto available_out = buff.size();
  4515. auto next_out = buff.data();
  4516. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  4517. &available_out, &next_out, nullptr)) {
  4518. return false;
  4519. }
  4520. auto output_bytes = buff.size() - available_out;
  4521. if (output_bytes) {
  4522. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  4523. }
  4524. }
  4525. return true;
  4526. }
  4527. inline brotli_decompressor::brotli_decompressor() {
  4528. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  4529. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  4530. : BROTLI_DECODER_RESULT_ERROR;
  4531. }
  4532. inline brotli_decompressor::~brotli_decompressor() {
  4533. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  4534. }
  4535. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  4536. inline bool brotli_decompressor::decompress(const char *data,
  4537. size_t data_length,
  4538. Callback callback) {
  4539. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4540. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  4541. return 0;
  4542. }
  4543. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4544. size_t avail_in = data_length;
  4545. size_t total_out;
  4546. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  4547. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4548. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  4549. char *next_out = buff.data();
  4550. size_t avail_out = buff.size();
  4551. decoder_r = BrotliDecoderDecompressStream(
  4552. decoder_s, &avail_in, &next_in, &avail_out,
  4553. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  4554. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  4555. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  4556. }
  4557. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4558. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  4559. }
  4560. #endif
  4561. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4562. inline zstd_compressor::zstd_compressor() {
  4563. ctx_ = ZSTD_createCCtx();
  4564. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  4565. }
  4566. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  4567. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  4568. bool last, Callback callback) {
  4569. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4570. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  4571. ZSTD_inBuffer input = {data, data_length, 0};
  4572. bool finished;
  4573. do {
  4574. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4575. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  4576. if (ZSTD_isError(remaining)) { return false; }
  4577. if (!callback(buff.data(), output.pos)) { return false; }
  4578. finished = last ? (remaining == 0) : (input.pos == input.size);
  4579. } while (!finished);
  4580. return true;
  4581. }
  4582. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  4583. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  4584. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  4585. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  4586. Callback callback) {
  4587. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4588. ZSTD_inBuffer input = {data, data_length, 0};
  4589. while (input.pos < input.size) {
  4590. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4591. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  4592. if (ZSTD_isError(remaining)) { return false; }
  4593. if (!callback(buff.data(), output.pos)) { return false; }
  4594. }
  4595. return true;
  4596. }
  4597. #endif
  4598. inline std::unique_ptr<decompressor>
  4599. create_decompressor(const std::string &encoding) {
  4600. std::unique_ptr<decompressor> decompressor;
  4601. if (encoding == "gzip" || encoding == "deflate") {
  4602. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4603. decompressor = detail::make_unique<gzip_decompressor>();
  4604. #endif
  4605. } else if (encoding.find("br") != std::string::npos) {
  4606. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4607. decompressor = detail::make_unique<brotli_decompressor>();
  4608. #endif
  4609. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  4610. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4611. decompressor = detail::make_unique<zstd_decompressor>();
  4612. #endif
  4613. }
  4614. return decompressor;
  4615. }
  4616. inline bool is_prohibited_header_name(const std::string &name) {
  4617. using udl::operator""_t;
  4618. switch (str2tag(name)) {
  4619. case "REMOTE_ADDR"_t:
  4620. case "REMOTE_PORT"_t:
  4621. case "LOCAL_ADDR"_t:
  4622. case "LOCAL_PORT"_t: return true;
  4623. default: return false;
  4624. }
  4625. }
  4626. inline bool has_header(const Headers &headers, const std::string &key) {
  4627. if (is_prohibited_header_name(key)) { return false; }
  4628. return headers.find(key) != headers.end();
  4629. }
  4630. inline const char *get_header_value(const Headers &headers,
  4631. const std::string &key, const char *def,
  4632. size_t id) {
  4633. if (is_prohibited_header_name(key)) {
  4634. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4635. std::string msg = "Prohibited header name '" + key + "' is specified.";
  4636. throw std::invalid_argument(msg);
  4637. #else
  4638. return "";
  4639. #endif
  4640. }
  4641. auto rng = headers.equal_range(key);
  4642. auto it = rng.first;
  4643. std::advance(it, static_cast<ssize_t>(id));
  4644. if (it != rng.second) { return it->second.c_str(); }
  4645. return def;
  4646. }
  4647. inline bool read_headers(Stream &strm, Headers &headers) {
  4648. const auto bufsiz = 2048;
  4649. char buf[bufsiz];
  4650. stream_line_reader line_reader(strm, buf, bufsiz);
  4651. size_t header_count = 0;
  4652. for (;;) {
  4653. if (!line_reader.getline()) { return false; }
  4654. // Check if the line ends with CRLF.
  4655. auto line_terminator_len = 2;
  4656. if (line_reader.end_with_crlf()) {
  4657. // Blank line indicates end of headers.
  4658. if (line_reader.size() == 2) { break; }
  4659. } else {
  4660. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4661. // Blank line indicates end of headers.
  4662. if (line_reader.size() == 1) { break; }
  4663. line_terminator_len = 1;
  4664. #else
  4665. continue; // Skip invalid line.
  4666. #endif
  4667. }
  4668. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4669. // Check header count limit
  4670. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4671. // Exclude line terminator
  4672. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  4673. if (!parse_header(line_reader.ptr(), end,
  4674. [&](const std::string &key, const std::string &val) {
  4675. headers.emplace(key, val);
  4676. })) {
  4677. return false;
  4678. }
  4679. header_count++;
  4680. }
  4681. return true;
  4682. }
  4683. inline bool read_content_with_length(Stream &strm, size_t len,
  4684. DownloadProgress progress,
  4685. ContentReceiverWithProgress out) {
  4686. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4687. detail::BodyReader br;
  4688. br.stream = &strm;
  4689. br.content_length = len;
  4690. br.chunked = false;
  4691. br.bytes_read = 0;
  4692. br.last_error = Error::Success;
  4693. size_t r = 0;
  4694. while (r < len) {
  4695. auto read_len = static_cast<size_t>(len - r);
  4696. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  4697. auto n = detail::read_body_content(&strm, br, buf, to_read);
  4698. if (n <= 0) { return false; }
  4699. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  4700. r += static_cast<size_t>(n);
  4701. if (progress) {
  4702. if (!progress(r, len)) { return false; }
  4703. }
  4704. }
  4705. return true;
  4706. }
  4707. inline void skip_content_with_length(Stream &strm, size_t len) {
  4708. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4709. size_t r = 0;
  4710. while (r < len) {
  4711. auto read_len = static_cast<size_t>(len - r);
  4712. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  4713. if (n <= 0) { return; }
  4714. r += static_cast<size_t>(n);
  4715. }
  4716. }
  4717. enum class ReadContentResult {
  4718. Success, // Successfully read the content
  4719. PayloadTooLarge, // The content exceeds the specified payload limit
  4720. Error // An error occurred while reading the content
  4721. };
  4722. inline ReadContentResult
  4723. read_content_without_length(Stream &strm, size_t payload_max_length,
  4724. ContentReceiverWithProgress out) {
  4725. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4726. size_t r = 0;
  4727. for (;;) {
  4728. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  4729. if (n == 0) { return ReadContentResult::Success; }
  4730. if (n < 0) { return ReadContentResult::Error; }
  4731. // Check if adding this data would exceed the payload limit
  4732. if (r > payload_max_length ||
  4733. payload_max_length - r < static_cast<size_t>(n)) {
  4734. return ReadContentResult::PayloadTooLarge;
  4735. }
  4736. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  4737. return ReadContentResult::Error;
  4738. }
  4739. r += static_cast<size_t>(n);
  4740. }
  4741. return ReadContentResult::Success;
  4742. }
  4743. template <typename T>
  4744. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  4745. size_t payload_max_length,
  4746. ContentReceiverWithProgress out) {
  4747. detail::ChunkedDecoder dec(strm);
  4748. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4749. size_t total_len = 0;
  4750. for (;;) {
  4751. size_t chunk_offset = 0;
  4752. size_t chunk_total = 0;
  4753. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  4754. if (n < 0) { return ReadContentResult::Error; }
  4755. if (n == 0) {
  4756. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  4757. return ReadContentResult::Error;
  4758. }
  4759. return ReadContentResult::Success;
  4760. }
  4761. if (total_len > payload_max_length ||
  4762. payload_max_length - total_len < static_cast<size_t>(n)) {
  4763. return ReadContentResult::PayloadTooLarge;
  4764. }
  4765. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  4766. return ReadContentResult::Error;
  4767. }
  4768. total_len += static_cast<size_t>(n);
  4769. }
  4770. }
  4771. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  4772. return case_ignore::equal(
  4773. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  4774. }
  4775. template <typename T, typename U>
  4776. bool prepare_content_receiver(T &x, int &status,
  4777. ContentReceiverWithProgress receiver,
  4778. bool decompress, U callback) {
  4779. if (decompress) {
  4780. std::string encoding = x.get_header_value("Content-Encoding");
  4781. std::unique_ptr<decompressor> decompressor;
  4782. if (!encoding.empty()) {
  4783. decompressor = detail::create_decompressor(encoding);
  4784. if (!decompressor) {
  4785. // Unsupported encoding or no support compiled in
  4786. status = StatusCode::UnsupportedMediaType_415;
  4787. return false;
  4788. }
  4789. }
  4790. if (decompressor) {
  4791. if (decompressor->is_valid()) {
  4792. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  4793. size_t off, size_t len) {
  4794. return decompressor->decompress(buf, n,
  4795. [&](const char *buf2, size_t n2) {
  4796. return receiver(buf2, n2, off, len);
  4797. });
  4798. };
  4799. return callback(std::move(out));
  4800. } else {
  4801. status = StatusCode::InternalServerError_500;
  4802. return false;
  4803. }
  4804. }
  4805. }
  4806. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  4807. size_t len) {
  4808. return receiver(buf, n, off, len);
  4809. };
  4810. return callback(std::move(out));
  4811. }
  4812. template <typename T>
  4813. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  4814. DownloadProgress progress,
  4815. ContentReceiverWithProgress receiver, bool decompress) {
  4816. return prepare_content_receiver(
  4817. x, status, std::move(receiver), decompress,
  4818. [&](const ContentReceiverWithProgress &out) {
  4819. auto ret = true;
  4820. auto exceed_payload_max_length = false;
  4821. if (is_chunked_transfer_encoding(x.headers)) {
  4822. auto result = read_content_chunked(strm, x, payload_max_length, out);
  4823. if (result == ReadContentResult::Success) {
  4824. ret = true;
  4825. } else if (result == ReadContentResult::PayloadTooLarge) {
  4826. exceed_payload_max_length = true;
  4827. ret = false;
  4828. } else {
  4829. ret = false;
  4830. }
  4831. } else if (!has_header(x.headers, "Content-Length")) {
  4832. auto result =
  4833. read_content_without_length(strm, payload_max_length, out);
  4834. if (result == ReadContentResult::Success) {
  4835. ret = true;
  4836. } else if (result == ReadContentResult::PayloadTooLarge) {
  4837. exceed_payload_max_length = true;
  4838. ret = false;
  4839. } else {
  4840. ret = false;
  4841. }
  4842. } else {
  4843. auto is_invalid_value = false;
  4844. auto len = get_header_value_u64(x.headers, "Content-Length",
  4845. (std::numeric_limits<size_t>::max)(),
  4846. 0, is_invalid_value);
  4847. if (is_invalid_value) {
  4848. ret = false;
  4849. } else if (len > payload_max_length) {
  4850. exceed_payload_max_length = true;
  4851. skip_content_with_length(strm, len);
  4852. ret = false;
  4853. } else if (len > 0) {
  4854. ret = read_content_with_length(strm, len, std::move(progress), out);
  4855. }
  4856. }
  4857. if (!ret) {
  4858. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  4859. : StatusCode::BadRequest_400;
  4860. }
  4861. return ret;
  4862. });
  4863. }
  4864. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  4865. const std::string &path) {
  4866. std::string s = method;
  4867. s += ' ';
  4868. s += path;
  4869. s += " HTTP/1.1\r\n";
  4870. return strm.write(s.data(), s.size());
  4871. }
  4872. inline ssize_t write_response_line(Stream &strm, int status) {
  4873. std::string s = "HTTP/1.1 ";
  4874. s += std::to_string(status);
  4875. s += ' ';
  4876. s += httplib::status_message(status);
  4877. s += "\r\n";
  4878. return strm.write(s.data(), s.size());
  4879. }
  4880. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  4881. ssize_t write_len = 0;
  4882. for (const auto &x : headers) {
  4883. std::string s;
  4884. s = x.first;
  4885. s += ": ";
  4886. s += x.second;
  4887. s += "\r\n";
  4888. auto len = strm.write(s.data(), s.size());
  4889. if (len < 0) { return len; }
  4890. write_len += len;
  4891. }
  4892. auto len = strm.write("\r\n");
  4893. if (len < 0) { return len; }
  4894. write_len += len;
  4895. return write_len;
  4896. }
  4897. inline bool write_data(Stream &strm, const char *d, size_t l) {
  4898. size_t offset = 0;
  4899. while (offset < l) {
  4900. auto length = strm.write(d + offset, l - offset);
  4901. if (length < 0) { return false; }
  4902. offset += static_cast<size_t>(length);
  4903. }
  4904. return true;
  4905. }
  4906. template <typename T>
  4907. inline bool write_content_with_progress(Stream &strm,
  4908. const ContentProvider &content_provider,
  4909. size_t offset, size_t length,
  4910. T is_shutting_down,
  4911. const UploadProgress &upload_progress,
  4912. Error &error) {
  4913. size_t end_offset = offset + length;
  4914. size_t start_offset = offset;
  4915. auto ok = true;
  4916. DataSink data_sink;
  4917. data_sink.write = [&](const char *d, size_t l) -> bool {
  4918. if (ok) {
  4919. if (write_data(strm, d, l)) {
  4920. offset += l;
  4921. if (upload_progress && length > 0) {
  4922. size_t current_written = offset - start_offset;
  4923. if (!upload_progress(current_written, length)) {
  4924. ok = false;
  4925. return false;
  4926. }
  4927. }
  4928. } else {
  4929. ok = false;
  4930. }
  4931. }
  4932. return ok;
  4933. };
  4934. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4935. while (offset < end_offset && !is_shutting_down()) {
  4936. if (!strm.wait_writable()) {
  4937. error = Error::Write;
  4938. return false;
  4939. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  4940. error = Error::Canceled;
  4941. return false;
  4942. } else if (!ok) {
  4943. error = Error::Write;
  4944. return false;
  4945. }
  4946. }
  4947. error = Error::Success;
  4948. return true;
  4949. }
  4950. template <typename T>
  4951. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4952. size_t offset, size_t length, T is_shutting_down,
  4953. Error &error) {
  4954. return write_content_with_progress<T>(strm, content_provider, offset, length,
  4955. is_shutting_down, nullptr, error);
  4956. }
  4957. template <typename T>
  4958. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4959. size_t offset, size_t length,
  4960. const T &is_shutting_down) {
  4961. auto error = Error::Success;
  4962. return write_content(strm, content_provider, offset, length, is_shutting_down,
  4963. error);
  4964. }
  4965. template <typename T>
  4966. inline bool
  4967. write_content_without_length(Stream &strm,
  4968. const ContentProvider &content_provider,
  4969. const T &is_shutting_down) {
  4970. size_t offset = 0;
  4971. auto data_available = true;
  4972. auto ok = true;
  4973. DataSink data_sink;
  4974. data_sink.write = [&](const char *d, size_t l) -> bool {
  4975. if (ok) {
  4976. offset += l;
  4977. if (!write_data(strm, d, l)) { ok = false; }
  4978. }
  4979. return ok;
  4980. };
  4981. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4982. data_sink.done = [&](void) { data_available = false; };
  4983. while (data_available && !is_shutting_down()) {
  4984. if (!strm.wait_writable()) {
  4985. return false;
  4986. } else if (!content_provider(offset, 0, data_sink)) {
  4987. return false;
  4988. } else if (!ok) {
  4989. return false;
  4990. }
  4991. }
  4992. return true;
  4993. }
  4994. template <typename T, typename U>
  4995. inline bool
  4996. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  4997. const T &is_shutting_down, U &compressor, Error &error) {
  4998. size_t offset = 0;
  4999. auto data_available = true;
  5000. auto ok = true;
  5001. DataSink data_sink;
  5002. data_sink.write = [&](const char *d, size_t l) -> bool {
  5003. if (ok) {
  5004. data_available = l > 0;
  5005. offset += l;
  5006. std::string payload;
  5007. if (compressor.compress(d, l, false,
  5008. [&](const char *data, size_t data_len) {
  5009. payload.append(data, data_len);
  5010. return true;
  5011. })) {
  5012. if (!payload.empty()) {
  5013. // Emit chunked response header and footer for each chunk
  5014. auto chunk =
  5015. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5016. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  5017. }
  5018. } else {
  5019. ok = false;
  5020. }
  5021. }
  5022. return ok;
  5023. };
  5024. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5025. auto done_with_trailer = [&](const Headers *trailer) {
  5026. if (!ok) { return; }
  5027. data_available = false;
  5028. std::string payload;
  5029. if (!compressor.compress(nullptr, 0, true,
  5030. [&](const char *data, size_t data_len) {
  5031. payload.append(data, data_len);
  5032. return true;
  5033. })) {
  5034. ok = false;
  5035. return;
  5036. }
  5037. if (!payload.empty()) {
  5038. // Emit chunked response header and footer for each chunk
  5039. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5040. if (!write_data(strm, chunk.data(), chunk.size())) {
  5041. ok = false;
  5042. return;
  5043. }
  5044. }
  5045. constexpr const char done_marker[] = "0\r\n";
  5046. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  5047. // Trailer
  5048. if (trailer) {
  5049. for (const auto &kv : *trailer) {
  5050. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  5051. if (!write_data(strm, field_line.data(), field_line.size())) {
  5052. ok = false;
  5053. }
  5054. }
  5055. }
  5056. constexpr const char crlf[] = "\r\n";
  5057. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  5058. };
  5059. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  5060. data_sink.done_with_trailer = [&](const Headers &trailer) {
  5061. done_with_trailer(&trailer);
  5062. };
  5063. while (data_available && !is_shutting_down()) {
  5064. if (!strm.wait_writable()) {
  5065. error = Error::Write;
  5066. return false;
  5067. } else if (!content_provider(offset, 0, data_sink)) {
  5068. error = Error::Canceled;
  5069. return false;
  5070. } else if (!ok) {
  5071. error = Error::Write;
  5072. return false;
  5073. }
  5074. }
  5075. error = Error::Success;
  5076. return true;
  5077. }
  5078. template <typename T, typename U>
  5079. inline bool write_content_chunked(Stream &strm,
  5080. const ContentProvider &content_provider,
  5081. const T &is_shutting_down, U &compressor) {
  5082. auto error = Error::Success;
  5083. return write_content_chunked(strm, content_provider, is_shutting_down,
  5084. compressor, error);
  5085. }
  5086. template <typename T>
  5087. inline bool redirect(T &cli, Request &req, Response &res,
  5088. const std::string &path, const std::string &location,
  5089. Error &error) {
  5090. Request new_req = req;
  5091. new_req.path = path;
  5092. new_req.redirect_count_ -= 1;
  5093. if (res.status == StatusCode::SeeOther_303 &&
  5094. (req.method != "GET" && req.method != "HEAD")) {
  5095. new_req.method = "GET";
  5096. new_req.body.clear();
  5097. new_req.headers.clear();
  5098. }
  5099. Response new_res;
  5100. auto ret = cli.send(new_req, new_res, error);
  5101. if (ret) {
  5102. req = std::move(new_req);
  5103. res = std::move(new_res);
  5104. if (res.location.empty()) { res.location = location; }
  5105. }
  5106. return ret;
  5107. }
  5108. inline std::string params_to_query_str(const Params &params) {
  5109. std::string query;
  5110. for (auto it = params.begin(); it != params.end(); ++it) {
  5111. if (it != params.begin()) { query += '&'; }
  5112. query += encode_query_component(it->first);
  5113. query += '=';
  5114. query += encode_query_component(it->second);
  5115. }
  5116. return query;
  5117. }
  5118. inline void parse_query_text(const char *data, std::size_t size,
  5119. Params &params) {
  5120. std::set<std::string> cache;
  5121. split(data, data + size, '&', [&](const char *b, const char *e) {
  5122. std::string kv(b, e);
  5123. if (cache.find(kv) != cache.end()) { return; }
  5124. cache.insert(std::move(kv));
  5125. std::string key;
  5126. std::string val;
  5127. divide(b, static_cast<std::size_t>(e - b), '=',
  5128. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  5129. std::size_t rhs_size) {
  5130. key.assign(lhs_data, lhs_size);
  5131. val.assign(rhs_data, rhs_size);
  5132. });
  5133. if (!key.empty()) {
  5134. params.emplace(decode_query_component(key), decode_query_component(val));
  5135. }
  5136. });
  5137. }
  5138. inline void parse_query_text(const std::string &s, Params &params) {
  5139. parse_query_text(s.data(), s.size(), params);
  5140. }
  5141. // Normalize a query string by decoding and re-encoding each key/value pair
  5142. // while preserving the original parameter order. This avoids double-encoding
  5143. // and ensures consistent encoding without reordering (unlike Params which
  5144. // uses std::multimap and sorts keys).
  5145. inline std::string normalize_query_string(const std::string &query) {
  5146. std::string result;
  5147. split(query.data(), query.data() + query.size(), '&',
  5148. [&](const char *b, const char *e) {
  5149. std::string key;
  5150. std::string val;
  5151. divide(b, static_cast<std::size_t>(e - b), '=',
  5152. [&](const char *lhs_data, std::size_t lhs_size,
  5153. const char *rhs_data, std::size_t rhs_size) {
  5154. key.assign(lhs_data, lhs_size);
  5155. val.assign(rhs_data, rhs_size);
  5156. });
  5157. if (!key.empty()) {
  5158. auto dec_key = decode_query_component(key);
  5159. auto dec_val = decode_query_component(val);
  5160. if (!result.empty()) { result += '&'; }
  5161. result += encode_query_component(dec_key);
  5162. if (!val.empty() || std::find(b, e, '=') != e) {
  5163. result += '=';
  5164. result += encode_query_component(dec_val);
  5165. }
  5166. }
  5167. });
  5168. return result;
  5169. }
  5170. inline bool parse_multipart_boundary(const std::string &content_type,
  5171. std::string &boundary) {
  5172. auto boundary_keyword = "boundary=";
  5173. auto pos = content_type.find(boundary_keyword);
  5174. if (pos == std::string::npos) { return false; }
  5175. auto end = content_type.find(';', pos);
  5176. auto beg = pos + strlen(boundary_keyword);
  5177. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  5178. return !boundary.empty();
  5179. }
  5180. inline void parse_disposition_params(const std::string &s, Params &params) {
  5181. std::set<std::string> cache;
  5182. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  5183. std::string kv(b, e);
  5184. if (cache.find(kv) != cache.end()) { return; }
  5185. cache.insert(kv);
  5186. std::string key;
  5187. std::string val;
  5188. split(b, e, '=', [&](const char *b2, const char *e2) {
  5189. if (key.empty()) {
  5190. key.assign(b2, e2);
  5191. } else {
  5192. val.assign(b2, e2);
  5193. }
  5194. });
  5195. if (!key.empty()) {
  5196. params.emplace(trim_double_quotes_copy((key)),
  5197. trim_double_quotes_copy((val)));
  5198. }
  5199. });
  5200. }
  5201. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5202. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  5203. #else
  5204. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  5205. #endif
  5206. auto is_valid = [](const std::string &str) {
  5207. return std::all_of(str.cbegin(), str.cend(),
  5208. [](unsigned char c) { return std::isdigit(c); });
  5209. };
  5210. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  5211. const auto pos = static_cast<size_t>(6);
  5212. const auto len = static_cast<size_t>(s.size() - 6);
  5213. auto all_valid_ranges = true;
  5214. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  5215. if (!all_valid_ranges) { return; }
  5216. const auto it = std::find(b, e, '-');
  5217. if (it == e) {
  5218. all_valid_ranges = false;
  5219. return;
  5220. }
  5221. const auto lhs = std::string(b, it);
  5222. const auto rhs = std::string(it + 1, e);
  5223. if (!is_valid(lhs) || !is_valid(rhs)) {
  5224. all_valid_ranges = false;
  5225. return;
  5226. }
  5227. const auto first =
  5228. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  5229. const auto last =
  5230. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  5231. if ((first == -1 && last == -1) ||
  5232. (first != -1 && last != -1 && first > last)) {
  5233. all_valid_ranges = false;
  5234. return;
  5235. }
  5236. ranges.emplace_back(first, last);
  5237. });
  5238. return all_valid_ranges && !ranges.empty();
  5239. }
  5240. return false;
  5241. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5242. }
  5243. #else
  5244. } catch (...) { return false; }
  5245. #endif
  5246. inline bool parse_accept_header(const std::string &s,
  5247. std::vector<std::string> &content_types) {
  5248. content_types.clear();
  5249. // Empty string is considered valid (no preference)
  5250. if (s.empty()) { return true; }
  5251. // Check for invalid patterns: leading/trailing commas or consecutive commas
  5252. if (s.front() == ',' || s.back() == ',' ||
  5253. s.find(",,") != std::string::npos) {
  5254. return false;
  5255. }
  5256. struct AcceptEntry {
  5257. std::string media_type;
  5258. double quality;
  5259. int order; // Original order in header
  5260. };
  5261. std::vector<AcceptEntry> entries;
  5262. int order = 0;
  5263. bool has_invalid_entry = false;
  5264. // Split by comma and parse each entry
  5265. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5266. std::string entry(b, e);
  5267. entry = trim_copy(entry);
  5268. if (entry.empty()) {
  5269. has_invalid_entry = true;
  5270. return;
  5271. }
  5272. AcceptEntry accept_entry;
  5273. accept_entry.quality = 1.0; // Default quality
  5274. accept_entry.order = order++;
  5275. // Find q= parameter
  5276. auto q_pos = entry.find(";q=");
  5277. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  5278. if (q_pos != std::string::npos) {
  5279. // Extract media type (before q parameter)
  5280. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  5281. // Extract quality value
  5282. auto q_start = entry.find('=', q_pos) + 1;
  5283. auto q_end = entry.find(';', q_start);
  5284. if (q_end == std::string::npos) { q_end = entry.length(); }
  5285. std::string quality_str =
  5286. trim_copy(entry.substr(q_start, q_end - q_start));
  5287. if (quality_str.empty()) {
  5288. has_invalid_entry = true;
  5289. return;
  5290. }
  5291. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5292. {
  5293. std::istringstream iss(quality_str);
  5294. iss >> accept_entry.quality;
  5295. // Check if conversion was successful and entire string was consumed
  5296. if (iss.fail() || !iss.eof()) {
  5297. has_invalid_entry = true;
  5298. return;
  5299. }
  5300. }
  5301. #else
  5302. try {
  5303. accept_entry.quality = std::stod(quality_str);
  5304. } catch (...) {
  5305. has_invalid_entry = true;
  5306. return;
  5307. }
  5308. #endif
  5309. // Check if quality is in valid range [0.0, 1.0]
  5310. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  5311. has_invalid_entry = true;
  5312. return;
  5313. }
  5314. } else {
  5315. // No quality parameter, use entire entry as media type
  5316. accept_entry.media_type = entry;
  5317. }
  5318. // Remove additional parameters from media type
  5319. auto param_pos = accept_entry.media_type.find(';');
  5320. if (param_pos != std::string::npos) {
  5321. accept_entry.media_type =
  5322. trim_copy(accept_entry.media_type.substr(0, param_pos));
  5323. }
  5324. // Basic validation of media type format
  5325. if (accept_entry.media_type.empty()) {
  5326. has_invalid_entry = true;
  5327. return;
  5328. }
  5329. // Check for basic media type format (should contain '/' or be '*')
  5330. if (accept_entry.media_type != "*" &&
  5331. accept_entry.media_type.find('/') == std::string::npos) {
  5332. has_invalid_entry = true;
  5333. return;
  5334. }
  5335. entries.push_back(std::move(accept_entry));
  5336. });
  5337. // Return false if any invalid entry was found
  5338. if (has_invalid_entry) { return false; }
  5339. // Sort by quality (descending), then by original order (ascending)
  5340. std::sort(entries.begin(), entries.end(),
  5341. [](const AcceptEntry &a, const AcceptEntry &b) {
  5342. if (a.quality != b.quality) {
  5343. return a.quality > b.quality; // Higher quality first
  5344. }
  5345. return a.order < b.order; // Earlier order first for same quality
  5346. });
  5347. // Extract sorted media types
  5348. content_types.reserve(entries.size());
  5349. for (auto &entry : entries) {
  5350. content_types.push_back(std::move(entry.media_type));
  5351. }
  5352. return true;
  5353. }
  5354. class FormDataParser {
  5355. public:
  5356. FormDataParser() = default;
  5357. void set_boundary(std::string &&boundary) {
  5358. boundary_ = std::move(boundary);
  5359. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  5360. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  5361. }
  5362. bool is_valid() const { return is_valid_; }
  5363. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  5364. const ContentReceiver &content_callback) {
  5365. buf_append(buf, n);
  5366. while (buf_size() > 0) {
  5367. switch (state_) {
  5368. case 0: { // Initial boundary
  5369. auto pos = buf_find(dash_boundary_crlf_);
  5370. if (pos == buf_size()) { return true; }
  5371. buf_erase(pos + dash_boundary_crlf_.size());
  5372. state_ = 1;
  5373. break;
  5374. }
  5375. case 1: { // New entry
  5376. clear_file_info();
  5377. state_ = 2;
  5378. break;
  5379. }
  5380. case 2: { // Headers
  5381. auto pos = buf_find(crlf_);
  5382. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5383. while (pos < buf_size()) {
  5384. // Empty line
  5385. if (pos == 0) {
  5386. if (!header_callback(file_)) {
  5387. is_valid_ = false;
  5388. return false;
  5389. }
  5390. buf_erase(crlf_.size());
  5391. state_ = 3;
  5392. break;
  5393. }
  5394. const auto header = buf_head(pos);
  5395. if (!parse_header(header.data(), header.data() + header.size(),
  5396. [&](const std::string &, const std::string &) {})) {
  5397. is_valid_ = false;
  5398. return false;
  5399. }
  5400. // Parse and emplace space trimmed headers into a map
  5401. if (!parse_header(
  5402. header.data(), header.data() + header.size(),
  5403. [&](const std::string &key, const std::string &val) {
  5404. file_.headers.emplace(key, val);
  5405. })) {
  5406. is_valid_ = false;
  5407. return false;
  5408. }
  5409. constexpr const char header_content_type[] = "Content-Type:";
  5410. if (start_with_case_ignore(header, header_content_type)) {
  5411. file_.content_type =
  5412. trim_copy(header.substr(str_len(header_content_type)));
  5413. } else {
  5414. thread_local const std::regex re_content_disposition(
  5415. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  5416. std::regex_constants::icase);
  5417. std::smatch m;
  5418. if (std::regex_match(header, m, re_content_disposition)) {
  5419. Params params;
  5420. parse_disposition_params(m[1], params);
  5421. auto it = params.find("name");
  5422. if (it != params.end()) {
  5423. file_.name = it->second;
  5424. } else {
  5425. is_valid_ = false;
  5426. return false;
  5427. }
  5428. it = params.find("filename");
  5429. if (it != params.end()) { file_.filename = it->second; }
  5430. it = params.find("filename*");
  5431. if (it != params.end()) {
  5432. // Only allow UTF-8 encoding...
  5433. thread_local const std::regex re_rfc5987_encoding(
  5434. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  5435. std::smatch m2;
  5436. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  5437. file_.filename = decode_path_component(m2[1]); // override...
  5438. } else {
  5439. is_valid_ = false;
  5440. return false;
  5441. }
  5442. }
  5443. }
  5444. }
  5445. buf_erase(pos + crlf_.size());
  5446. pos = buf_find(crlf_);
  5447. }
  5448. if (state_ != 3) { return true; }
  5449. break;
  5450. }
  5451. case 3: { // Body
  5452. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  5453. auto pos = buf_find(crlf_dash_boundary_);
  5454. if (pos < buf_size()) {
  5455. if (!content_callback(buf_data(), pos)) {
  5456. is_valid_ = false;
  5457. return false;
  5458. }
  5459. buf_erase(pos + crlf_dash_boundary_.size());
  5460. state_ = 4;
  5461. } else {
  5462. auto len = buf_size() - crlf_dash_boundary_.size();
  5463. if (len > 0) {
  5464. if (!content_callback(buf_data(), len)) {
  5465. is_valid_ = false;
  5466. return false;
  5467. }
  5468. buf_erase(len);
  5469. }
  5470. return true;
  5471. }
  5472. break;
  5473. }
  5474. case 4: { // Boundary
  5475. if (crlf_.size() > buf_size()) { return true; }
  5476. if (buf_start_with(crlf_)) {
  5477. buf_erase(crlf_.size());
  5478. state_ = 1;
  5479. } else {
  5480. if (dash_.size() > buf_size()) { return true; }
  5481. if (buf_start_with(dash_)) {
  5482. buf_erase(dash_.size());
  5483. is_valid_ = true;
  5484. buf_erase(buf_size()); // Remove epilogue
  5485. } else {
  5486. return true;
  5487. }
  5488. }
  5489. break;
  5490. }
  5491. }
  5492. }
  5493. return true;
  5494. }
  5495. private:
  5496. void clear_file_info() {
  5497. file_.name.clear();
  5498. file_.filename.clear();
  5499. file_.content_type.clear();
  5500. file_.headers.clear();
  5501. }
  5502. bool start_with_case_ignore(const std::string &a, const char *b) const {
  5503. const auto b_len = strlen(b);
  5504. if (a.size() < b_len) { return false; }
  5505. for (size_t i = 0; i < b_len; i++) {
  5506. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  5507. return false;
  5508. }
  5509. }
  5510. return true;
  5511. }
  5512. const std::string dash_ = "--";
  5513. const std::string crlf_ = "\r\n";
  5514. std::string boundary_;
  5515. std::string dash_boundary_crlf_;
  5516. std::string crlf_dash_boundary_;
  5517. size_t state_ = 0;
  5518. bool is_valid_ = false;
  5519. FormData file_;
  5520. // Buffer
  5521. bool start_with(const std::string &a, size_t spos, size_t epos,
  5522. const std::string &b) const {
  5523. if (epos - spos < b.size()) { return false; }
  5524. for (size_t i = 0; i < b.size(); i++) {
  5525. if (a[i + spos] != b[i]) { return false; }
  5526. }
  5527. return true;
  5528. }
  5529. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  5530. const char *buf_data() const { return &buf_[buf_spos_]; }
  5531. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  5532. bool buf_start_with(const std::string &s) const {
  5533. return start_with(buf_, buf_spos_, buf_epos_, s);
  5534. }
  5535. size_t buf_find(const std::string &s) const {
  5536. auto c = s.front();
  5537. size_t off = buf_spos_;
  5538. while (off < buf_epos_) {
  5539. auto pos = off;
  5540. while (true) {
  5541. if (pos == buf_epos_) { return buf_size(); }
  5542. if (buf_[pos] == c) { break; }
  5543. pos++;
  5544. }
  5545. auto remaining_size = buf_epos_ - pos;
  5546. if (s.size() > remaining_size) { return buf_size(); }
  5547. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  5548. off = pos + 1;
  5549. }
  5550. return buf_size();
  5551. }
  5552. void buf_append(const char *data, size_t n) {
  5553. auto remaining_size = buf_size();
  5554. if (remaining_size > 0 && buf_spos_ > 0) {
  5555. for (size_t i = 0; i < remaining_size; i++) {
  5556. buf_[i] = buf_[buf_spos_ + i];
  5557. }
  5558. }
  5559. buf_spos_ = 0;
  5560. buf_epos_ = remaining_size;
  5561. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  5562. for (size_t i = 0; i < n; i++) {
  5563. buf_[buf_epos_ + i] = data[i];
  5564. }
  5565. buf_epos_ += n;
  5566. }
  5567. void buf_erase(size_t size) { buf_spos_ += size; }
  5568. std::string buf_;
  5569. size_t buf_spos_ = 0;
  5570. size_t buf_epos_ = 0;
  5571. };
  5572. inline std::string random_string(size_t length) {
  5573. constexpr const char data[] =
  5574. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  5575. thread_local auto engine([]() {
  5576. // std::random_device might actually be deterministic on some
  5577. // platforms, but due to lack of support in the c++ standard library,
  5578. // doing better requires either some ugly hacks or breaking portability.
  5579. std::random_device seed_gen;
  5580. // Request 128 bits of entropy for initialization
  5581. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  5582. return std::mt19937(seed_sequence);
  5583. }());
  5584. std::string result;
  5585. for (size_t i = 0; i < length; i++) {
  5586. result += data[engine() % (sizeof(data) - 1)];
  5587. }
  5588. return result;
  5589. }
  5590. inline std::string make_multipart_data_boundary() {
  5591. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  5592. }
  5593. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  5594. auto valid = true;
  5595. for (size_t i = 0; i < boundary.size(); i++) {
  5596. auto c = boundary[i];
  5597. if (!std::isalnum(c) && c != '-' && c != '_') {
  5598. valid = false;
  5599. break;
  5600. }
  5601. }
  5602. return valid;
  5603. }
  5604. template <typename T>
  5605. inline std::string
  5606. serialize_multipart_formdata_item_begin(const T &item,
  5607. const std::string &boundary) {
  5608. std::string body = "--" + boundary + "\r\n";
  5609. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5610. if (!item.filename.empty()) {
  5611. body += "; filename=\"" + item.filename + "\"";
  5612. }
  5613. body += "\r\n";
  5614. if (!item.content_type.empty()) {
  5615. body += "Content-Type: " + item.content_type + "\r\n";
  5616. }
  5617. body += "\r\n";
  5618. return body;
  5619. }
  5620. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  5621. inline std::string
  5622. serialize_multipart_formdata_finish(const std::string &boundary) {
  5623. return "--" + boundary + "--\r\n";
  5624. }
  5625. inline std::string
  5626. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  5627. return "multipart/form-data; boundary=" + boundary;
  5628. }
  5629. inline std::string
  5630. serialize_multipart_formdata(const UploadFormDataItems &items,
  5631. const std::string &boundary, bool finish = true) {
  5632. std::string body;
  5633. for (const auto &item : items) {
  5634. body += serialize_multipart_formdata_item_begin(item, boundary);
  5635. body += item.content + serialize_multipart_formdata_item_end();
  5636. }
  5637. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  5638. return body;
  5639. }
  5640. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  5641. if (ranges.size() <= 1) return;
  5642. // Sort ranges by start position
  5643. std::sort(ranges.begin(), ranges.end(),
  5644. [](const Range &a, const Range &b) { return a.first < b.first; });
  5645. Ranges coalesced;
  5646. coalesced.reserve(ranges.size());
  5647. for (auto &r : ranges) {
  5648. auto first_pos = r.first;
  5649. auto last_pos = r.second;
  5650. // Handle special cases like in range_error
  5651. if (first_pos == -1 && last_pos == -1) {
  5652. first_pos = 0;
  5653. last_pos = static_cast<ssize_t>(content_length);
  5654. }
  5655. if (first_pos == -1) {
  5656. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  5657. last_pos = static_cast<ssize_t>(content_length) - 1;
  5658. }
  5659. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  5660. last_pos = static_cast<ssize_t>(content_length) - 1;
  5661. }
  5662. // Skip invalid ranges
  5663. if (!(0 <= first_pos && first_pos <= last_pos &&
  5664. last_pos < static_cast<ssize_t>(content_length))) {
  5665. continue;
  5666. }
  5667. // Coalesce with previous range if overlapping or adjacent (but not
  5668. // identical)
  5669. if (!coalesced.empty()) {
  5670. auto &prev = coalesced.back();
  5671. // Check if current range overlaps or is adjacent to previous range
  5672. // but don't coalesce identical ranges (allow duplicates)
  5673. if (first_pos <= prev.second + 1 &&
  5674. !(first_pos == prev.first && last_pos == prev.second)) {
  5675. // Extend the previous range
  5676. prev.second = (std::max)(prev.second, last_pos);
  5677. continue;
  5678. }
  5679. }
  5680. // Add new range
  5681. coalesced.emplace_back(first_pos, last_pos);
  5682. }
  5683. ranges = std::move(coalesced);
  5684. }
  5685. inline bool range_error(Request &req, Response &res) {
  5686. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  5687. ssize_t content_len = static_cast<ssize_t>(
  5688. res.content_length_ ? res.content_length_ : res.body.size());
  5689. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  5690. size_t overwrapping_count = 0;
  5691. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  5692. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  5693. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  5694. // Too many ranges
  5695. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  5696. for (auto &r : req.ranges) {
  5697. auto &first_pos = r.first;
  5698. auto &last_pos = r.second;
  5699. if (first_pos == -1 && last_pos == -1) {
  5700. first_pos = 0;
  5701. last_pos = content_len;
  5702. }
  5703. if (first_pos == -1) {
  5704. first_pos = content_len - last_pos;
  5705. last_pos = content_len - 1;
  5706. }
  5707. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  5708. // A client can limit the number of bytes requested without knowing the
  5709. // size of the selected representation. If the last-pos value is absent,
  5710. // or if the value is greater than or equal to the current length of the
  5711. // representation data, the byte range is interpreted as the remainder of
  5712. // the representation (i.e., the server replaces the value of last-pos
  5713. // with a value that is one less than the current length of the selected
  5714. // representation).
  5715. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  5716. if (last_pos == -1 || last_pos >= content_len) {
  5717. last_pos = content_len - 1;
  5718. }
  5719. // Range must be within content length
  5720. if (!(0 <= first_pos && first_pos <= last_pos &&
  5721. last_pos <= content_len - 1)) {
  5722. return true;
  5723. }
  5724. // Request must not have more than two overlapping ranges
  5725. for (const auto &processed_range : processed_ranges) {
  5726. if (!(last_pos < processed_range.first ||
  5727. first_pos > processed_range.second)) {
  5728. overwrapping_count++;
  5729. if (overwrapping_count > 2) { return true; }
  5730. break; // Only count once per range
  5731. }
  5732. }
  5733. processed_ranges.emplace_back(first_pos, last_pos);
  5734. }
  5735. // After validation, coalesce overlapping ranges as per RFC 9110
  5736. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  5737. }
  5738. return false;
  5739. }
  5740. inline std::pair<size_t, size_t>
  5741. get_range_offset_and_length(Range r, size_t content_length) {
  5742. assert(r.first != -1 && r.second != -1);
  5743. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  5744. assert(r.first <= r.second &&
  5745. r.second < static_cast<ssize_t>(content_length));
  5746. (void)(content_length);
  5747. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  5748. }
  5749. inline std::string make_content_range_header_field(
  5750. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  5751. auto st = offset_and_length.first;
  5752. auto ed = st + offset_and_length.second - 1;
  5753. std::string field = "bytes ";
  5754. field += std::to_string(st);
  5755. field += '-';
  5756. field += std::to_string(ed);
  5757. field += '/';
  5758. field += std::to_string(content_length);
  5759. return field;
  5760. }
  5761. template <typename SToken, typename CToken, typename Content>
  5762. bool process_multipart_ranges_data(const Request &req,
  5763. const std::string &boundary,
  5764. const std::string &content_type,
  5765. size_t content_length, SToken stoken,
  5766. CToken ctoken, Content content) {
  5767. for (size_t i = 0; i < req.ranges.size(); i++) {
  5768. ctoken("--");
  5769. stoken(boundary);
  5770. ctoken("\r\n");
  5771. if (!content_type.empty()) {
  5772. ctoken("Content-Type: ");
  5773. stoken(content_type);
  5774. ctoken("\r\n");
  5775. }
  5776. auto offset_and_length =
  5777. get_range_offset_and_length(req.ranges[i], content_length);
  5778. ctoken("Content-Range: ");
  5779. stoken(make_content_range_header_field(offset_and_length, content_length));
  5780. ctoken("\r\n");
  5781. ctoken("\r\n");
  5782. if (!content(offset_and_length.first, offset_and_length.second)) {
  5783. return false;
  5784. }
  5785. ctoken("\r\n");
  5786. }
  5787. ctoken("--");
  5788. stoken(boundary);
  5789. ctoken("--");
  5790. return true;
  5791. }
  5792. inline void make_multipart_ranges_data(const Request &req, Response &res,
  5793. const std::string &boundary,
  5794. const std::string &content_type,
  5795. size_t content_length,
  5796. std::string &data) {
  5797. process_multipart_ranges_data(
  5798. req, boundary, content_type, content_length,
  5799. [&](const std::string &token) { data += token; },
  5800. [&](const std::string &token) { data += token; },
  5801. [&](size_t offset, size_t length) {
  5802. assert(offset + length <= content_length);
  5803. data += res.body.substr(offset, length);
  5804. return true;
  5805. });
  5806. }
  5807. inline size_t get_multipart_ranges_data_length(const Request &req,
  5808. const std::string &boundary,
  5809. const std::string &content_type,
  5810. size_t content_length) {
  5811. size_t data_length = 0;
  5812. process_multipart_ranges_data(
  5813. req, boundary, content_type, content_length,
  5814. [&](const std::string &token) { data_length += token.size(); },
  5815. [&](const std::string &token) { data_length += token.size(); },
  5816. [&](size_t /*offset*/, size_t length) {
  5817. data_length += length;
  5818. return true;
  5819. });
  5820. return data_length;
  5821. }
  5822. template <typename T>
  5823. inline bool
  5824. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  5825. const std::string &boundary,
  5826. const std::string &content_type,
  5827. size_t content_length, const T &is_shutting_down) {
  5828. return process_multipart_ranges_data(
  5829. req, boundary, content_type, content_length,
  5830. [&](const std::string &token) { strm.write(token); },
  5831. [&](const std::string &token) { strm.write(token); },
  5832. [&](size_t offset, size_t length) {
  5833. return write_content(strm, res.content_provider_, offset, length,
  5834. is_shutting_down);
  5835. });
  5836. }
  5837. inline bool expect_content(const Request &req) {
  5838. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  5839. req.method == "DELETE") {
  5840. return true;
  5841. }
  5842. if (req.has_header("Content-Length") &&
  5843. req.get_header_value_u64("Content-Length") > 0) {
  5844. return true;
  5845. }
  5846. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  5847. return false;
  5848. }
  5849. inline bool has_crlf(const std::string &s) {
  5850. auto p = s.c_str();
  5851. while (*p) {
  5852. if (*p == '\r' || *p == '\n') { return true; }
  5853. p++;
  5854. }
  5855. return false;
  5856. }
  5857. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5858. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  5859. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  5860. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  5861. unsigned int hash_length = 0;
  5862. unsigned char hash[EVP_MAX_MD_SIZE];
  5863. EVP_DigestInit_ex(context.get(), algo, nullptr);
  5864. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  5865. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  5866. std::stringstream ss;
  5867. for (auto i = 0u; i < hash_length; ++i) {
  5868. ss << std::hex << std::setw(2) << std::setfill('0')
  5869. << static_cast<unsigned int>(hash[i]);
  5870. }
  5871. return ss.str();
  5872. }
  5873. inline std::string MD5(const std::string &s) {
  5874. return message_digest(s, EVP_md5());
  5875. }
  5876. inline std::string SHA_256(const std::string &s) {
  5877. return message_digest(s, EVP_sha256());
  5878. }
  5879. inline std::string SHA_512(const std::string &s) {
  5880. return message_digest(s, EVP_sha512());
  5881. }
  5882. inline std::pair<std::string, std::string> make_digest_authentication_header(
  5883. const Request &req, const std::map<std::string, std::string> &auth,
  5884. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  5885. const std::string &password, bool is_proxy = false) {
  5886. std::string nc;
  5887. {
  5888. std::stringstream ss;
  5889. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  5890. nc = ss.str();
  5891. }
  5892. std::string qop;
  5893. if (auth.find("qop") != auth.end()) {
  5894. qop = auth.at("qop");
  5895. if (qop.find("auth-int") != std::string::npos) {
  5896. qop = "auth-int";
  5897. } else if (qop.find("auth") != std::string::npos) {
  5898. qop = "auth";
  5899. } else {
  5900. qop.clear();
  5901. }
  5902. }
  5903. std::string algo = "MD5";
  5904. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  5905. std::string response;
  5906. {
  5907. auto H = algo == "SHA-256" ? detail::SHA_256
  5908. : algo == "SHA-512" ? detail::SHA_512
  5909. : detail::MD5;
  5910. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  5911. auto A2 = req.method + ":" + req.path;
  5912. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  5913. if (qop.empty()) {
  5914. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  5915. } else {
  5916. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  5917. ":" + qop + ":" + H(A2));
  5918. }
  5919. }
  5920. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  5921. auto field = "Digest username=\"" + username + "\", realm=\"" +
  5922. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  5923. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  5924. (qop.empty() ? ", response=\""
  5925. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  5926. cnonce + "\", response=\"") +
  5927. response + "\"" +
  5928. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  5929. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5930. return std::make_pair(key, field);
  5931. }
  5932. inline bool is_ssl_peer_could_be_closed(SSL *ssl, socket_t sock) {
  5933. detail::set_nonblocking(sock, true);
  5934. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  5935. char buf[1];
  5936. return !SSL_peek(ssl, buf, 1) &&
  5937. SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
  5938. }
  5939. #ifdef _WIN32
  5940. // NOTE: This code came up with the following stackoverflow post:
  5941. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  5942. inline bool load_system_certs_on_windows(X509_STORE *store) {
  5943. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  5944. if (!hStore) { return false; }
  5945. auto result = false;
  5946. PCCERT_CONTEXT pContext = NULL;
  5947. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  5948. nullptr) {
  5949. auto encoded_cert =
  5950. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  5951. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  5952. if (x509) {
  5953. X509_STORE_add_cert(store, x509);
  5954. X509_free(x509);
  5955. result = true;
  5956. }
  5957. }
  5958. CertFreeCertificateContext(pContext);
  5959. CertCloseStore(hStore, 0);
  5960. return result;
  5961. }
  5962. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  5963. template <typename T>
  5964. using CFObjectPtr =
  5965. std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
  5966. inline void cf_object_ptr_deleter(CFTypeRef obj) {
  5967. if (obj) { CFRelease(obj); }
  5968. }
  5969. inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5970. CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
  5971. CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,
  5972. kCFBooleanTrue};
  5973. CFObjectPtr<CFDictionaryRef> query(
  5974. CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,
  5975. sizeof(keys) / sizeof(keys[0]),
  5976. &kCFTypeDictionaryKeyCallBacks,
  5977. &kCFTypeDictionaryValueCallBacks),
  5978. cf_object_ptr_deleter);
  5979. if (!query) { return false; }
  5980. CFTypeRef security_items = nullptr;
  5981. if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
  5982. CFArrayGetTypeID() != CFGetTypeID(security_items)) {
  5983. return false;
  5984. }
  5985. certs.reset(reinterpret_cast<CFArrayRef>(security_items));
  5986. return true;
  5987. }
  5988. inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5989. CFArrayRef root_security_items = nullptr;
  5990. if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
  5991. return false;
  5992. }
  5993. certs.reset(root_security_items);
  5994. return true;
  5995. }
  5996. inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
  5997. auto result = false;
  5998. for (auto i = 0; i < CFArrayGetCount(certs); ++i) {
  5999. const auto cert = reinterpret_cast<const __SecCertificate *>(
  6000. CFArrayGetValueAtIndex(certs, i));
  6001. if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }
  6002. CFDataRef cert_data = nullptr;
  6003. if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=
  6004. errSecSuccess) {
  6005. continue;
  6006. }
  6007. CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
  6008. auto encoded_cert = static_cast<const unsigned char *>(
  6009. CFDataGetBytePtr(cert_data_ptr.get()));
  6010. auto x509 =
  6011. d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
  6012. if (x509) {
  6013. X509_STORE_add_cert(store, x509);
  6014. X509_free(x509);
  6015. result = true;
  6016. }
  6017. }
  6018. return result;
  6019. }
  6020. inline bool load_system_certs_on_macos(X509_STORE *store) {
  6021. auto result = false;
  6022. CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);
  6023. if (retrieve_certs_from_keychain(certs) && certs) {
  6024. result = add_certs_to_x509_store(certs.get(), store);
  6025. }
  6026. if (retrieve_root_certs_from_keychain(certs) && certs) {
  6027. result = add_certs_to_x509_store(certs.get(), store) || result;
  6028. }
  6029. return result;
  6030. }
  6031. #endif // _WIN32
  6032. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  6033. #ifdef _WIN32
  6034. class WSInit {
  6035. public:
  6036. WSInit() {
  6037. WSADATA wsaData;
  6038. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  6039. }
  6040. ~WSInit() {
  6041. if (is_valid_) WSACleanup();
  6042. }
  6043. bool is_valid_ = false;
  6044. };
  6045. static WSInit wsinit_;
  6046. #endif
  6047. inline bool parse_www_authenticate(const Response &res,
  6048. std::map<std::string, std::string> &auth,
  6049. bool is_proxy) {
  6050. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  6051. if (res.has_header(auth_key)) {
  6052. thread_local auto re =
  6053. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  6054. auto s = res.get_header_value(auth_key);
  6055. auto pos = s.find(' ');
  6056. if (pos != std::string::npos) {
  6057. auto type = s.substr(0, pos);
  6058. if (type == "Basic") {
  6059. return false;
  6060. } else if (type == "Digest") {
  6061. s = s.substr(pos + 1);
  6062. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  6063. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  6064. const auto &m = *i;
  6065. auto key = s.substr(static_cast<size_t>(m.position(1)),
  6066. static_cast<size_t>(m.length(1)));
  6067. auto val = m.length(2) > 0
  6068. ? s.substr(static_cast<size_t>(m.position(2)),
  6069. static_cast<size_t>(m.length(2)))
  6070. : s.substr(static_cast<size_t>(m.position(3)),
  6071. static_cast<size_t>(m.length(3)));
  6072. auth[std::move(key)] = std::move(val);
  6073. }
  6074. return true;
  6075. }
  6076. }
  6077. }
  6078. return false;
  6079. }
  6080. class ContentProviderAdapter {
  6081. public:
  6082. explicit ContentProviderAdapter(
  6083. ContentProviderWithoutLength &&content_provider)
  6084. : content_provider_(std::move(content_provider)) {}
  6085. bool operator()(size_t offset, size_t, DataSink &sink) {
  6086. return content_provider_(offset, sink);
  6087. }
  6088. private:
  6089. ContentProviderWithoutLength content_provider_;
  6090. };
  6091. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  6092. namespace fields {
  6093. inline bool is_token_char(char c) {
  6094. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  6095. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  6096. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  6097. }
  6098. inline bool is_token(const std::string &s) {
  6099. if (s.empty()) { return false; }
  6100. for (auto c : s) {
  6101. if (!is_token_char(c)) { return false; }
  6102. }
  6103. return true;
  6104. }
  6105. inline bool is_field_name(const std::string &s) { return is_token(s); }
  6106. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  6107. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  6108. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  6109. inline bool is_field_content(const std::string &s) {
  6110. if (s.empty()) { return true; }
  6111. if (s.size() == 1) {
  6112. return is_field_vchar(s[0]);
  6113. } else if (s.size() == 2) {
  6114. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  6115. } else {
  6116. size_t i = 0;
  6117. if (!is_field_vchar(s[i])) { return false; }
  6118. i++;
  6119. while (i < s.size() - 1) {
  6120. auto c = s[i++];
  6121. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  6122. } else {
  6123. return false;
  6124. }
  6125. }
  6126. return is_field_vchar(s[i]);
  6127. }
  6128. }
  6129. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  6130. } // namespace fields
  6131. } // namespace detail
  6132. inline const char *status_message(int status) {
  6133. switch (status) {
  6134. case StatusCode::Continue_100: return "Continue";
  6135. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  6136. case StatusCode::Processing_102: return "Processing";
  6137. case StatusCode::EarlyHints_103: return "Early Hints";
  6138. case StatusCode::OK_200: return "OK";
  6139. case StatusCode::Created_201: return "Created";
  6140. case StatusCode::Accepted_202: return "Accepted";
  6141. case StatusCode::NonAuthoritativeInformation_203:
  6142. return "Non-Authoritative Information";
  6143. case StatusCode::NoContent_204: return "No Content";
  6144. case StatusCode::ResetContent_205: return "Reset Content";
  6145. case StatusCode::PartialContent_206: return "Partial Content";
  6146. case StatusCode::MultiStatus_207: return "Multi-Status";
  6147. case StatusCode::AlreadyReported_208: return "Already Reported";
  6148. case StatusCode::IMUsed_226: return "IM Used";
  6149. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  6150. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  6151. case StatusCode::Found_302: return "Found";
  6152. case StatusCode::SeeOther_303: return "See Other";
  6153. case StatusCode::NotModified_304: return "Not Modified";
  6154. case StatusCode::UseProxy_305: return "Use Proxy";
  6155. case StatusCode::unused_306: return "unused";
  6156. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  6157. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  6158. case StatusCode::BadRequest_400: return "Bad Request";
  6159. case StatusCode::Unauthorized_401: return "Unauthorized";
  6160. case StatusCode::PaymentRequired_402: return "Payment Required";
  6161. case StatusCode::Forbidden_403: return "Forbidden";
  6162. case StatusCode::NotFound_404: return "Not Found";
  6163. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  6164. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  6165. case StatusCode::ProxyAuthenticationRequired_407:
  6166. return "Proxy Authentication Required";
  6167. case StatusCode::RequestTimeout_408: return "Request Timeout";
  6168. case StatusCode::Conflict_409: return "Conflict";
  6169. case StatusCode::Gone_410: return "Gone";
  6170. case StatusCode::LengthRequired_411: return "Length Required";
  6171. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  6172. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  6173. case StatusCode::UriTooLong_414: return "URI Too Long";
  6174. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  6175. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  6176. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  6177. case StatusCode::ImATeapot_418: return "I'm a teapot";
  6178. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  6179. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  6180. case StatusCode::Locked_423: return "Locked";
  6181. case StatusCode::FailedDependency_424: return "Failed Dependency";
  6182. case StatusCode::TooEarly_425: return "Too Early";
  6183. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  6184. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  6185. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  6186. case StatusCode::RequestHeaderFieldsTooLarge_431:
  6187. return "Request Header Fields Too Large";
  6188. case StatusCode::UnavailableForLegalReasons_451:
  6189. return "Unavailable For Legal Reasons";
  6190. case StatusCode::NotImplemented_501: return "Not Implemented";
  6191. case StatusCode::BadGateway_502: return "Bad Gateway";
  6192. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  6193. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  6194. case StatusCode::HttpVersionNotSupported_505:
  6195. return "HTTP Version Not Supported";
  6196. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  6197. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  6198. case StatusCode::LoopDetected_508: return "Loop Detected";
  6199. case StatusCode::NotExtended_510: return "Not Extended";
  6200. case StatusCode::NetworkAuthenticationRequired_511:
  6201. return "Network Authentication Required";
  6202. default:
  6203. case StatusCode::InternalServerError_500: return "Internal Server Error";
  6204. }
  6205. }
  6206. inline std::string to_string(const Error error) {
  6207. switch (error) {
  6208. case Error::Success: return "Success (no error)";
  6209. case Error::Unknown: return "Unknown";
  6210. case Error::Connection: return "Could not establish connection";
  6211. case Error::BindIPAddress: return "Failed to bind IP address";
  6212. case Error::Read: return "Failed to read connection";
  6213. case Error::Write: return "Failed to write connection";
  6214. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  6215. case Error::Canceled: return "Connection handling canceled";
  6216. case Error::SSLConnection: return "SSL connection failed";
  6217. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  6218. case Error::SSLServerVerification: return "SSL server verification failed";
  6219. case Error::SSLServerHostnameVerification:
  6220. return "SSL server hostname verification failed";
  6221. case Error::UnsupportedMultipartBoundaryChars:
  6222. return "Unsupported HTTP multipart boundary characters";
  6223. case Error::Compression: return "Compression failed";
  6224. case Error::ConnectionTimeout: return "Connection timed out";
  6225. case Error::ProxyConnection: return "Proxy connection failed";
  6226. case Error::ConnectionClosed: return "Connection closed by server";
  6227. case Error::Timeout: return "Read timeout";
  6228. case Error::ResourceExhaustion: return "Resource exhaustion";
  6229. case Error::TooManyFormDataFiles: return "Too many form data files";
  6230. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  6231. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  6232. case Error::ExceedMaxSocketDescriptorCount:
  6233. return "Exceeded maximum socket descriptor count";
  6234. case Error::InvalidRequestLine: return "Invalid request line";
  6235. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  6236. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  6237. case Error::InvalidHeaders: return "Invalid headers";
  6238. case Error::MultipartParsing: return "Multipart parsing failed";
  6239. case Error::OpenFile: return "Failed to open file";
  6240. case Error::Listen: return "Failed to listen on socket";
  6241. case Error::GetSockName: return "Failed to get socket name";
  6242. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  6243. case Error::HTTPParsing: return "HTTP parsing failed";
  6244. case Error::InvalidRangeHeader: return "Invalid Range header";
  6245. default: break;
  6246. }
  6247. return "Invalid";
  6248. }
  6249. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  6250. os << to_string(obj);
  6251. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  6252. return os;
  6253. }
  6254. inline std::string hosted_at(const std::string &hostname) {
  6255. std::vector<std::string> addrs;
  6256. hosted_at(hostname, addrs);
  6257. if (addrs.empty()) { return std::string(); }
  6258. return addrs[0];
  6259. }
  6260. inline void hosted_at(const std::string &hostname,
  6261. std::vector<std::string> &addrs) {
  6262. struct addrinfo hints;
  6263. struct addrinfo *result;
  6264. memset(&hints, 0, sizeof(struct addrinfo));
  6265. hints.ai_family = AF_UNSPEC;
  6266. hints.ai_socktype = SOCK_STREAM;
  6267. hints.ai_protocol = 0;
  6268. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  6269. &result, 0)) {
  6270. #if defined __linux__ && !defined __ANDROID__
  6271. res_init();
  6272. #endif
  6273. return;
  6274. }
  6275. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6276. for (auto rp = result; rp; rp = rp->ai_next) {
  6277. const auto &addr =
  6278. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  6279. std::string ip;
  6280. auto dummy = -1;
  6281. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  6282. dummy)) {
  6283. addrs.emplace_back(std::move(ip));
  6284. }
  6285. }
  6286. }
  6287. inline std::string encode_uri_component(const std::string &value) {
  6288. std::ostringstream escaped;
  6289. escaped.fill('0');
  6290. escaped << std::hex;
  6291. for (auto c : value) {
  6292. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6293. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6294. c == ')') {
  6295. escaped << c;
  6296. } else {
  6297. escaped << std::uppercase;
  6298. escaped << '%' << std::setw(2)
  6299. << static_cast<int>(static_cast<unsigned char>(c));
  6300. escaped << std::nouppercase;
  6301. }
  6302. }
  6303. return escaped.str();
  6304. }
  6305. inline std::string encode_uri(const std::string &value) {
  6306. std::ostringstream escaped;
  6307. escaped.fill('0');
  6308. escaped << std::hex;
  6309. for (auto c : value) {
  6310. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6311. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6312. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  6313. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  6314. escaped << c;
  6315. } else {
  6316. escaped << std::uppercase;
  6317. escaped << '%' << std::setw(2)
  6318. << static_cast<int>(static_cast<unsigned char>(c));
  6319. escaped << std::nouppercase;
  6320. }
  6321. }
  6322. return escaped.str();
  6323. }
  6324. inline std::string decode_uri_component(const std::string &value) {
  6325. std::string result;
  6326. for (size_t i = 0; i < value.size(); i++) {
  6327. if (value[i] == '%' && i + 2 < value.size()) {
  6328. auto val = 0;
  6329. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6330. result += static_cast<char>(val);
  6331. i += 2;
  6332. } else {
  6333. result += value[i];
  6334. }
  6335. } else {
  6336. result += value[i];
  6337. }
  6338. }
  6339. return result;
  6340. }
  6341. inline std::string decode_uri(const std::string &value) {
  6342. std::string result;
  6343. for (size_t i = 0; i < value.size(); i++) {
  6344. if (value[i] == '%' && i + 2 < value.size()) {
  6345. auto val = 0;
  6346. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6347. result += static_cast<char>(val);
  6348. i += 2;
  6349. } else {
  6350. result += value[i];
  6351. }
  6352. } else {
  6353. result += value[i];
  6354. }
  6355. }
  6356. return result;
  6357. }
  6358. inline std::string encode_path_component(const std::string &component) {
  6359. std::string result;
  6360. result.reserve(component.size() * 3);
  6361. for (size_t i = 0; i < component.size(); i++) {
  6362. auto c = static_cast<unsigned char>(component[i]);
  6363. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  6364. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6365. result += static_cast<char>(c);
  6366. }
  6367. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  6368. // "," / ";" / "="
  6369. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  6370. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  6371. c == '=') {
  6372. result += static_cast<char>(c);
  6373. }
  6374. // Colon is allowed in path segments except first segment
  6375. else if (c == ':') {
  6376. result += static_cast<char>(c);
  6377. }
  6378. // @ is allowed in path
  6379. else if (c == '@') {
  6380. result += static_cast<char>(c);
  6381. } else {
  6382. result += '%';
  6383. char hex[3];
  6384. snprintf(hex, sizeof(hex), "%02X", c);
  6385. result.append(hex, 2);
  6386. }
  6387. }
  6388. return result;
  6389. }
  6390. inline std::string decode_path_component(const std::string &component) {
  6391. std::string result;
  6392. result.reserve(component.size());
  6393. for (size_t i = 0; i < component.size(); i++) {
  6394. if (component[i] == '%' && i + 1 < component.size()) {
  6395. if (component[i + 1] == 'u') {
  6396. // Unicode %uXXXX encoding
  6397. auto val = 0;
  6398. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  6399. // 4 digits Unicode codes
  6400. char buff[4];
  6401. size_t len = detail::to_utf8(val, buff);
  6402. if (len > 0) { result.append(buff, len); }
  6403. i += 5; // 'u0000'
  6404. } else {
  6405. result += component[i];
  6406. }
  6407. } else {
  6408. // Standard %XX encoding
  6409. auto val = 0;
  6410. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  6411. // 2 digits hex codes
  6412. result += static_cast<char>(val);
  6413. i += 2; // 'XX'
  6414. } else {
  6415. result += component[i];
  6416. }
  6417. }
  6418. } else {
  6419. result += component[i];
  6420. }
  6421. }
  6422. return result;
  6423. }
  6424. inline std::string encode_query_component(const std::string &component,
  6425. bool space_as_plus) {
  6426. std::string result;
  6427. result.reserve(component.size() * 3);
  6428. for (size_t i = 0; i < component.size(); i++) {
  6429. auto c = static_cast<unsigned char>(component[i]);
  6430. // Unreserved characters per RFC 3986
  6431. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6432. result += static_cast<char>(c);
  6433. }
  6434. // Space handling
  6435. else if (c == ' ') {
  6436. if (space_as_plus) {
  6437. result += '+';
  6438. } else {
  6439. result += "%20";
  6440. }
  6441. }
  6442. // Plus sign handling
  6443. else if (c == '+') {
  6444. if (space_as_plus) {
  6445. result += "%2B";
  6446. } else {
  6447. result += static_cast<char>(c);
  6448. }
  6449. }
  6450. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  6451. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  6452. c == '*' || c == ',' || c == ';') {
  6453. result += static_cast<char>(c);
  6454. }
  6455. // Colon and @ are allowed in query
  6456. else if (c == ':' || c == '@') {
  6457. result += static_cast<char>(c);
  6458. }
  6459. // Forward slash is allowed in query values
  6460. else if (c == '/') {
  6461. result += static_cast<char>(c);
  6462. }
  6463. // Question mark is allowed in query values (after first ?)
  6464. else if (c == '?') {
  6465. result += static_cast<char>(c);
  6466. } else {
  6467. result += '%';
  6468. char hex[3];
  6469. snprintf(hex, sizeof(hex), "%02X", c);
  6470. result.append(hex, 2);
  6471. }
  6472. }
  6473. return result;
  6474. }
  6475. inline std::string decode_query_component(const std::string &component,
  6476. bool plus_as_space) {
  6477. std::string result;
  6478. result.reserve(component.size());
  6479. for (size_t i = 0; i < component.size(); i++) {
  6480. if (component[i] == '%' && i + 2 < component.size()) {
  6481. std::string hex = component.substr(i + 1, 2);
  6482. char *end;
  6483. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  6484. if (end == hex.c_str() + 2) {
  6485. result += static_cast<char>(value);
  6486. i += 2;
  6487. } else {
  6488. result += component[i];
  6489. }
  6490. } else if (component[i] == '+' && plus_as_space) {
  6491. result += ' '; // + becomes space in form-urlencoded
  6492. } else {
  6493. result += component[i];
  6494. }
  6495. }
  6496. return result;
  6497. }
  6498. inline std::string append_query_params(const std::string &path,
  6499. const Params &params) {
  6500. std::string path_with_query = path;
  6501. thread_local const std::regex re("[^?]+\\?.*");
  6502. auto delm = std::regex_match(path, re) ? '&' : '?';
  6503. path_with_query += delm + detail::params_to_query_str(params);
  6504. return path_with_query;
  6505. }
  6506. // Header utilities
  6507. inline std::pair<std::string, std::string>
  6508. make_range_header(const Ranges &ranges) {
  6509. std::string field = "bytes=";
  6510. auto i = 0;
  6511. for (const auto &r : ranges) {
  6512. if (i != 0) { field += ", "; }
  6513. if (r.first != -1) { field += std::to_string(r.first); }
  6514. field += '-';
  6515. if (r.second != -1) { field += std::to_string(r.second); }
  6516. i++;
  6517. }
  6518. return std::make_pair("Range", std::move(field));
  6519. }
  6520. inline std::pair<std::string, std::string>
  6521. make_basic_authentication_header(const std::string &username,
  6522. const std::string &password, bool is_proxy) {
  6523. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  6524. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6525. return std::make_pair(key, std::move(field));
  6526. }
  6527. inline std::pair<std::string, std::string>
  6528. make_bearer_token_authentication_header(const std::string &token,
  6529. bool is_proxy = false) {
  6530. auto field = "Bearer " + token;
  6531. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6532. return std::make_pair(key, std::move(field));
  6533. }
  6534. // Request implementation
  6535. inline bool Request::has_header(const std::string &key) const {
  6536. return detail::has_header(headers, key);
  6537. }
  6538. inline std::string Request::get_header_value(const std::string &key,
  6539. const char *def, size_t id) const {
  6540. return detail::get_header_value(headers, key, def, id);
  6541. }
  6542. inline size_t Request::get_header_value_count(const std::string &key) const {
  6543. auto r = headers.equal_range(key);
  6544. return static_cast<size_t>(std::distance(r.first, r.second));
  6545. }
  6546. inline void Request::set_header(const std::string &key,
  6547. const std::string &val) {
  6548. if (detail::fields::is_field_name(key) &&
  6549. detail::fields::is_field_value(val)) {
  6550. headers.emplace(key, val);
  6551. }
  6552. }
  6553. inline bool Request::has_trailer(const std::string &key) const {
  6554. return trailers.find(key) != trailers.end();
  6555. }
  6556. inline std::string Request::get_trailer_value(const std::string &key,
  6557. size_t id) const {
  6558. auto rng = trailers.equal_range(key);
  6559. auto it = rng.first;
  6560. std::advance(it, static_cast<ssize_t>(id));
  6561. if (it != rng.second) { return it->second; }
  6562. return std::string();
  6563. }
  6564. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  6565. auto r = trailers.equal_range(key);
  6566. return static_cast<size_t>(std::distance(r.first, r.second));
  6567. }
  6568. inline bool Request::has_param(const std::string &key) const {
  6569. return params.find(key) != params.end();
  6570. }
  6571. inline std::string Request::get_param_value(const std::string &key,
  6572. size_t id) const {
  6573. auto rng = params.equal_range(key);
  6574. auto it = rng.first;
  6575. std::advance(it, static_cast<ssize_t>(id));
  6576. if (it != rng.second) { return it->second; }
  6577. return std::string();
  6578. }
  6579. inline size_t Request::get_param_value_count(const std::string &key) const {
  6580. auto r = params.equal_range(key);
  6581. return static_cast<size_t>(std::distance(r.first, r.second));
  6582. }
  6583. inline bool Request::is_multipart_form_data() const {
  6584. const auto &content_type = get_header_value("Content-Type");
  6585. return !content_type.rfind("multipart/form-data", 0);
  6586. }
  6587. // Multipart FormData implementation
  6588. inline std::string MultipartFormData::get_field(const std::string &key,
  6589. size_t id) const {
  6590. auto rng = fields.equal_range(key);
  6591. auto it = rng.first;
  6592. std::advance(it, static_cast<ssize_t>(id));
  6593. if (it != rng.second) { return it->second.content; }
  6594. return std::string();
  6595. }
  6596. inline std::vector<std::string>
  6597. MultipartFormData::get_fields(const std::string &key) const {
  6598. std::vector<std::string> values;
  6599. auto rng = fields.equal_range(key);
  6600. for (auto it = rng.first; it != rng.second; it++) {
  6601. values.push_back(it->second.content);
  6602. }
  6603. return values;
  6604. }
  6605. inline bool MultipartFormData::has_field(const std::string &key) const {
  6606. return fields.find(key) != fields.end();
  6607. }
  6608. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  6609. auto r = fields.equal_range(key);
  6610. return static_cast<size_t>(std::distance(r.first, r.second));
  6611. }
  6612. inline FormData MultipartFormData::get_file(const std::string &key,
  6613. size_t id) const {
  6614. auto rng = files.equal_range(key);
  6615. auto it = rng.first;
  6616. std::advance(it, static_cast<ssize_t>(id));
  6617. if (it != rng.second) { return it->second; }
  6618. return FormData();
  6619. }
  6620. inline std::vector<FormData>
  6621. MultipartFormData::get_files(const std::string &key) const {
  6622. std::vector<FormData> values;
  6623. auto rng = files.equal_range(key);
  6624. for (auto it = rng.first; it != rng.second; it++) {
  6625. values.push_back(it->second);
  6626. }
  6627. return values;
  6628. }
  6629. inline bool MultipartFormData::has_file(const std::string &key) const {
  6630. return files.find(key) != files.end();
  6631. }
  6632. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  6633. auto r = files.equal_range(key);
  6634. return static_cast<size_t>(std::distance(r.first, r.second));
  6635. }
  6636. // Response implementation
  6637. inline bool Response::has_header(const std::string &key) const {
  6638. return headers.find(key) != headers.end();
  6639. }
  6640. inline std::string Response::get_header_value(const std::string &key,
  6641. const char *def,
  6642. size_t id) const {
  6643. return detail::get_header_value(headers, key, def, id);
  6644. }
  6645. inline size_t Response::get_header_value_count(const std::string &key) const {
  6646. auto r = headers.equal_range(key);
  6647. return static_cast<size_t>(std::distance(r.first, r.second));
  6648. }
  6649. inline void Response::set_header(const std::string &key,
  6650. const std::string &val) {
  6651. if (detail::fields::is_field_name(key) &&
  6652. detail::fields::is_field_value(val)) {
  6653. headers.emplace(key, val);
  6654. }
  6655. }
  6656. inline bool Response::has_trailer(const std::string &key) const {
  6657. return trailers.find(key) != trailers.end();
  6658. }
  6659. inline std::string Response::get_trailer_value(const std::string &key,
  6660. size_t id) const {
  6661. auto rng = trailers.equal_range(key);
  6662. auto it = rng.first;
  6663. std::advance(it, static_cast<ssize_t>(id));
  6664. if (it != rng.second) { return it->second; }
  6665. return std::string();
  6666. }
  6667. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  6668. auto r = trailers.equal_range(key);
  6669. return static_cast<size_t>(std::distance(r.first, r.second));
  6670. }
  6671. inline void Response::set_redirect(const std::string &url, int stat) {
  6672. if (detail::fields::is_field_value(url)) {
  6673. set_header("Location", url);
  6674. if (300 <= stat && stat < 400) {
  6675. this->status = stat;
  6676. } else {
  6677. this->status = StatusCode::Found_302;
  6678. }
  6679. }
  6680. }
  6681. inline void Response::set_content(const char *s, size_t n,
  6682. const std::string &content_type) {
  6683. body.assign(s, n);
  6684. auto rng = headers.equal_range("Content-Type");
  6685. headers.erase(rng.first, rng.second);
  6686. set_header("Content-Type", content_type);
  6687. }
  6688. inline void Response::set_content(const std::string &s,
  6689. const std::string &content_type) {
  6690. set_content(s.data(), s.size(), content_type);
  6691. }
  6692. inline void Response::set_content(std::string &&s,
  6693. const std::string &content_type) {
  6694. body = std::move(s);
  6695. auto rng = headers.equal_range("Content-Type");
  6696. headers.erase(rng.first, rng.second);
  6697. set_header("Content-Type", content_type);
  6698. }
  6699. inline void Response::set_content_provider(
  6700. size_t in_length, const std::string &content_type, ContentProvider provider,
  6701. ContentProviderResourceReleaser resource_releaser) {
  6702. set_header("Content-Type", content_type);
  6703. content_length_ = in_length;
  6704. if (in_length > 0) { content_provider_ = std::move(provider); }
  6705. content_provider_resource_releaser_ = std::move(resource_releaser);
  6706. is_chunked_content_provider_ = false;
  6707. }
  6708. inline void Response::set_content_provider(
  6709. const std::string &content_type, ContentProviderWithoutLength provider,
  6710. ContentProviderResourceReleaser resource_releaser) {
  6711. set_header("Content-Type", content_type);
  6712. content_length_ = 0;
  6713. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6714. content_provider_resource_releaser_ = std::move(resource_releaser);
  6715. is_chunked_content_provider_ = false;
  6716. }
  6717. inline void Response::set_chunked_content_provider(
  6718. const std::string &content_type, ContentProviderWithoutLength provider,
  6719. ContentProviderResourceReleaser resource_releaser) {
  6720. set_header("Content-Type", content_type);
  6721. content_length_ = 0;
  6722. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6723. content_provider_resource_releaser_ = std::move(resource_releaser);
  6724. is_chunked_content_provider_ = true;
  6725. }
  6726. inline void Response::set_file_content(const std::string &path,
  6727. const std::string &content_type) {
  6728. file_content_path_ = path;
  6729. file_content_content_type_ = content_type;
  6730. }
  6731. inline void Response::set_file_content(const std::string &path) {
  6732. file_content_path_ = path;
  6733. }
  6734. // Result implementation
  6735. inline bool Result::has_request_header(const std::string &key) const {
  6736. return request_headers_.find(key) != request_headers_.end();
  6737. }
  6738. inline std::string Result::get_request_header_value(const std::string &key,
  6739. const char *def,
  6740. size_t id) const {
  6741. return detail::get_header_value(request_headers_, key, def, id);
  6742. }
  6743. inline size_t
  6744. Result::get_request_header_value_count(const std::string &key) const {
  6745. auto r = request_headers_.equal_range(key);
  6746. return static_cast<size_t>(std::distance(r.first, r.second));
  6747. }
  6748. // Stream implementation
  6749. inline ssize_t Stream::write(const char *ptr) {
  6750. return write(ptr, strlen(ptr));
  6751. }
  6752. inline ssize_t Stream::write(const std::string &s) {
  6753. return write(s.data(), s.size());
  6754. }
  6755. // BodyReader implementation
  6756. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  6757. if (!stream) {
  6758. last_error = Error::Connection;
  6759. return -1;
  6760. }
  6761. if (eof) { return 0; }
  6762. if (!chunked) {
  6763. // Content-Length based reading
  6764. if (bytes_read >= content_length) {
  6765. eof = true;
  6766. return 0;
  6767. }
  6768. auto remaining = content_length - bytes_read;
  6769. auto to_read = (std::min)(len, remaining);
  6770. auto n = stream->read(buf, to_read);
  6771. if (n < 0) {
  6772. last_error = stream->get_error();
  6773. if (last_error == Error::Success) { last_error = Error::Read; }
  6774. eof = true;
  6775. return n;
  6776. }
  6777. if (n == 0) {
  6778. // Unexpected EOF before content_length
  6779. last_error = stream->get_error();
  6780. if (last_error == Error::Success) { last_error = Error::Read; }
  6781. eof = true;
  6782. return 0;
  6783. }
  6784. bytes_read += static_cast<size_t>(n);
  6785. if (bytes_read >= content_length) { eof = true; }
  6786. return n;
  6787. }
  6788. // Chunked transfer encoding: delegate to shared decoder instance.
  6789. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  6790. size_t chunk_offset = 0;
  6791. size_t chunk_total = 0;
  6792. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  6793. if (n < 0) {
  6794. last_error = stream->get_error();
  6795. if (last_error == Error::Success) { last_error = Error::Read; }
  6796. eof = true;
  6797. return n;
  6798. }
  6799. if (n == 0) {
  6800. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  6801. eof = true;
  6802. return 0;
  6803. }
  6804. bytes_read += static_cast<size_t>(n);
  6805. return n;
  6806. }
  6807. namespace detail {
  6808. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  6809. time_t timeout_sec, time_t timeout_usec,
  6810. time_t &actual_timeout_sec,
  6811. time_t &actual_timeout_usec) {
  6812. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  6813. auto actual_timeout_msec =
  6814. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  6815. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  6816. actual_timeout_sec = actual_timeout_msec / 1000;
  6817. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  6818. }
  6819. // Socket stream implementation
  6820. inline SocketStream::SocketStream(
  6821. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  6822. time_t write_timeout_sec, time_t write_timeout_usec,
  6823. time_t max_timeout_msec,
  6824. std::chrono::time_point<std::chrono::steady_clock> start_time)
  6825. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  6826. read_timeout_usec_(read_timeout_usec),
  6827. write_timeout_sec_(write_timeout_sec),
  6828. write_timeout_usec_(write_timeout_usec),
  6829. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  6830. read_buff_(read_buff_size_, 0) {}
  6831. inline SocketStream::~SocketStream() = default;
  6832. inline bool SocketStream::is_readable() const {
  6833. return read_buff_off_ < read_buff_content_size_;
  6834. }
  6835. inline bool SocketStream::wait_readable() const {
  6836. if (max_timeout_msec_ <= 0) {
  6837. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  6838. }
  6839. time_t read_timeout_sec;
  6840. time_t read_timeout_usec;
  6841. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  6842. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  6843. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  6844. }
  6845. inline bool SocketStream::wait_writable() const {
  6846. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  6847. is_socket_alive(sock_);
  6848. }
  6849. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  6850. #ifdef _WIN32
  6851. size =
  6852. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  6853. #else
  6854. size = (std::min)(size,
  6855. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  6856. #endif
  6857. if (read_buff_off_ < read_buff_content_size_) {
  6858. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  6859. if (size <= remaining_size) {
  6860. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  6861. read_buff_off_ += size;
  6862. return static_cast<ssize_t>(size);
  6863. } else {
  6864. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  6865. read_buff_off_ += remaining_size;
  6866. return static_cast<ssize_t>(remaining_size);
  6867. }
  6868. }
  6869. if (!wait_readable()) {
  6870. error_ = Error::Timeout;
  6871. return -1;
  6872. }
  6873. read_buff_off_ = 0;
  6874. read_buff_content_size_ = 0;
  6875. if (size < read_buff_size_) {
  6876. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  6877. CPPHTTPLIB_RECV_FLAGS);
  6878. if (n <= 0) {
  6879. if (n == 0) {
  6880. error_ = Error::ConnectionClosed;
  6881. } else {
  6882. error_ = Error::Read;
  6883. }
  6884. return n;
  6885. } else if (n <= static_cast<ssize_t>(size)) {
  6886. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  6887. return n;
  6888. } else {
  6889. memcpy(ptr, read_buff_.data(), size);
  6890. read_buff_off_ = size;
  6891. read_buff_content_size_ = static_cast<size_t>(n);
  6892. return static_cast<ssize_t>(size);
  6893. }
  6894. } else {
  6895. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  6896. if (n <= 0) {
  6897. if (n == 0) {
  6898. error_ = Error::ConnectionClosed;
  6899. } else {
  6900. error_ = Error::Read;
  6901. }
  6902. }
  6903. return n;
  6904. }
  6905. }
  6906. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  6907. if (!wait_writable()) { return -1; }
  6908. #if defined(_WIN32) && !defined(_WIN64)
  6909. size =
  6910. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  6911. #endif
  6912. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  6913. }
  6914. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  6915. int &port) const {
  6916. return detail::get_remote_ip_and_port(sock_, ip, port);
  6917. }
  6918. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  6919. int &port) const {
  6920. return detail::get_local_ip_and_port(sock_, ip, port);
  6921. }
  6922. inline socket_t SocketStream::socket() const { return sock_; }
  6923. inline time_t SocketStream::duration() const {
  6924. return std::chrono::duration_cast<std::chrono::milliseconds>(
  6925. std::chrono::steady_clock::now() - start_time_)
  6926. .count();
  6927. }
  6928. // Buffer stream implementation
  6929. inline bool BufferStream::is_readable() const { return true; }
  6930. inline bool BufferStream::wait_readable() const { return true; }
  6931. inline bool BufferStream::wait_writable() const { return true; }
  6932. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  6933. #if defined(_MSC_VER) && _MSC_VER < 1910
  6934. auto len_read = buffer._Copy_s(ptr, size, size, position);
  6935. #else
  6936. auto len_read = buffer.copy(ptr, size, position);
  6937. #endif
  6938. position += static_cast<size_t>(len_read);
  6939. return static_cast<ssize_t>(len_read);
  6940. }
  6941. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  6942. buffer.append(ptr, size);
  6943. return static_cast<ssize_t>(size);
  6944. }
  6945. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  6946. int & /*port*/) const {}
  6947. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  6948. int & /*port*/) const {}
  6949. inline socket_t BufferStream::socket() const { return 0; }
  6950. inline time_t BufferStream::duration() const { return 0; }
  6951. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  6952. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  6953. : MatcherBase(pattern) {
  6954. constexpr const char marker[] = "/:";
  6955. // One past the last ending position of a path param substring
  6956. std::size_t last_param_end = 0;
  6957. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6958. // Needed to ensure that parameter names are unique during matcher
  6959. // construction
  6960. // If exceptions are disabled, only last duplicate path
  6961. // parameter will be set
  6962. std::unordered_set<std::string> param_name_set;
  6963. #endif
  6964. while (true) {
  6965. const auto marker_pos = pattern.find(
  6966. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  6967. if (marker_pos == std::string::npos) { break; }
  6968. static_fragments_.push_back(
  6969. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  6970. const auto param_name_start = marker_pos + str_len(marker);
  6971. auto sep_pos = pattern.find(separator, param_name_start);
  6972. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  6973. auto param_name =
  6974. pattern.substr(param_name_start, sep_pos - param_name_start);
  6975. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6976. if (param_name_set.find(param_name) != param_name_set.cend()) {
  6977. std::string msg = "Encountered path parameter '" + param_name +
  6978. "' multiple times in route pattern '" + pattern + "'.";
  6979. throw std::invalid_argument(msg);
  6980. }
  6981. #endif
  6982. param_names_.push_back(std::move(param_name));
  6983. last_param_end = sep_pos + 1;
  6984. }
  6985. if (last_param_end < pattern.length()) {
  6986. static_fragments_.push_back(pattern.substr(last_param_end));
  6987. }
  6988. }
  6989. inline bool PathParamsMatcher::match(Request &request) const {
  6990. request.matches = std::smatch();
  6991. request.path_params.clear();
  6992. request.path_params.reserve(param_names_.size());
  6993. // One past the position at which the path matched the pattern last time
  6994. std::size_t starting_pos = 0;
  6995. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  6996. const auto &fragment = static_fragments_[i];
  6997. if (starting_pos + fragment.length() > request.path.length()) {
  6998. return false;
  6999. }
  7000. // Avoid unnecessary allocation by using strncmp instead of substr +
  7001. // comparison
  7002. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  7003. fragment.length()) != 0) {
  7004. return false;
  7005. }
  7006. starting_pos += fragment.length();
  7007. // Should only happen when we have a static fragment after a param
  7008. // Example: '/users/:id/subscriptions'
  7009. // The 'subscriptions' fragment here does not have a corresponding param
  7010. if (i >= param_names_.size()) { continue; }
  7011. auto sep_pos = request.path.find(separator, starting_pos);
  7012. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  7013. const auto &param_name = param_names_[i];
  7014. request.path_params.emplace(
  7015. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  7016. // Mark everything up to '/' as matched
  7017. starting_pos = sep_pos + 1;
  7018. }
  7019. // Returns false if the path is longer than the pattern
  7020. return starting_pos >= request.path.length();
  7021. }
  7022. inline bool RegexMatcher::match(Request &request) const {
  7023. request.path_params.clear();
  7024. return std::regex_match(request.path, request.matches, regex_);
  7025. }
  7026. // Enclose IPv6 address in brackets if needed
  7027. inline std::string prepare_host_string(const std::string &host) {
  7028. // Enclose IPv6 address in brackets (but not if already enclosed)
  7029. if (host.find(':') == std::string::npos ||
  7030. (!host.empty() && host[0] == '[')) {
  7031. // IPv4, hostname, or already bracketed IPv6
  7032. return host;
  7033. } else {
  7034. // IPv6 address without brackets
  7035. return "[" + host + "]";
  7036. }
  7037. }
  7038. inline std::string make_host_and_port_string(const std::string &host, int port,
  7039. bool is_ssl) {
  7040. auto result = prepare_host_string(host);
  7041. // Append port if not default
  7042. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  7043. ; // do nothing
  7044. } else {
  7045. result += ":" + std::to_string(port);
  7046. }
  7047. return result;
  7048. }
  7049. // Create "host:port" string always including port number (for CONNECT method)
  7050. inline std::string
  7051. make_host_and_port_string_always_port(const std::string &host, int port) {
  7052. return prepare_host_string(host) + ":" + std::to_string(port);
  7053. }
  7054. template <typename T>
  7055. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  7056. T header_writer, Error &error) {
  7057. for (const auto &h : headers) {
  7058. if (!detail::fields::is_field_name(h.first) ||
  7059. !detail::fields::is_field_value(h.second)) {
  7060. error = Error::InvalidHeaders;
  7061. return false;
  7062. }
  7063. }
  7064. if (header_writer(strm, headers) <= 0) {
  7065. error = Error::Write;
  7066. return false;
  7067. }
  7068. return true;
  7069. }
  7070. } // namespace detail
  7071. // HTTP server implementation
  7072. inline Server::Server()
  7073. : new_task_queue(
  7074. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  7075. #ifndef _WIN32
  7076. signal(SIGPIPE, SIG_IGN);
  7077. #endif
  7078. }
  7079. inline Server::~Server() = default;
  7080. inline std::unique_ptr<detail::MatcherBase>
  7081. Server::make_matcher(const std::string &pattern) {
  7082. if (pattern.find("/:") != std::string::npos) {
  7083. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  7084. } else {
  7085. return detail::make_unique<detail::RegexMatcher>(pattern);
  7086. }
  7087. }
  7088. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  7089. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7090. return *this;
  7091. }
  7092. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  7093. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7094. return *this;
  7095. }
  7096. inline Server &Server::Post(const std::string &pattern,
  7097. HandlerWithContentReader handler) {
  7098. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7099. std::move(handler));
  7100. return *this;
  7101. }
  7102. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  7103. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7104. return *this;
  7105. }
  7106. inline Server &Server::Put(const std::string &pattern,
  7107. HandlerWithContentReader handler) {
  7108. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7109. std::move(handler));
  7110. return *this;
  7111. }
  7112. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  7113. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7114. return *this;
  7115. }
  7116. inline Server &Server::Patch(const std::string &pattern,
  7117. HandlerWithContentReader handler) {
  7118. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7119. std::move(handler));
  7120. return *this;
  7121. }
  7122. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  7123. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7124. return *this;
  7125. }
  7126. inline Server &Server::Delete(const std::string &pattern,
  7127. HandlerWithContentReader handler) {
  7128. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7129. std::move(handler));
  7130. return *this;
  7131. }
  7132. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  7133. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7134. return *this;
  7135. }
  7136. inline bool Server::set_base_dir(const std::string &dir,
  7137. const std::string &mount_point) {
  7138. return set_mount_point(mount_point, dir);
  7139. }
  7140. inline bool Server::set_mount_point(const std::string &mount_point,
  7141. const std::string &dir, Headers headers) {
  7142. detail::FileStat stat(dir);
  7143. if (stat.is_dir()) {
  7144. std::string mnt = !mount_point.empty() ? mount_point : "/";
  7145. if (!mnt.empty() && mnt[0] == '/') {
  7146. base_dirs_.push_back({std::move(mnt), dir, std::move(headers)});
  7147. return true;
  7148. }
  7149. }
  7150. return false;
  7151. }
  7152. inline bool Server::remove_mount_point(const std::string &mount_point) {
  7153. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  7154. if (it->mount_point == mount_point) {
  7155. base_dirs_.erase(it);
  7156. return true;
  7157. }
  7158. }
  7159. return false;
  7160. }
  7161. inline Server &
  7162. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  7163. const std::string &mime) {
  7164. file_extension_and_mimetype_map_[ext] = mime;
  7165. return *this;
  7166. }
  7167. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  7168. default_file_mimetype_ = mime;
  7169. return *this;
  7170. }
  7171. inline Server &Server::set_file_request_handler(Handler handler) {
  7172. file_request_handler_ = std::move(handler);
  7173. return *this;
  7174. }
  7175. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  7176. std::true_type) {
  7177. error_handler_ = std::move(handler);
  7178. return *this;
  7179. }
  7180. inline Server &Server::set_error_handler_core(Handler handler,
  7181. std::false_type) {
  7182. error_handler_ = [handler](const Request &req, Response &res) {
  7183. handler(req, res);
  7184. return HandlerResponse::Handled;
  7185. };
  7186. return *this;
  7187. }
  7188. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  7189. exception_handler_ = std::move(handler);
  7190. return *this;
  7191. }
  7192. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  7193. pre_routing_handler_ = std::move(handler);
  7194. return *this;
  7195. }
  7196. inline Server &Server::set_post_routing_handler(Handler handler) {
  7197. post_routing_handler_ = std::move(handler);
  7198. return *this;
  7199. }
  7200. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  7201. pre_request_handler_ = std::move(handler);
  7202. return *this;
  7203. }
  7204. inline Server &Server::set_logger(Logger logger) {
  7205. logger_ = std::move(logger);
  7206. return *this;
  7207. }
  7208. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  7209. error_logger_ = std::move(error_logger);
  7210. return *this;
  7211. }
  7212. inline Server &Server::set_pre_compression_logger(Logger logger) {
  7213. pre_compression_logger_ = std::move(logger);
  7214. return *this;
  7215. }
  7216. inline Server &
  7217. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  7218. expect_100_continue_handler_ = std::move(handler);
  7219. return *this;
  7220. }
  7221. inline Server &Server::set_address_family(int family) {
  7222. address_family_ = family;
  7223. return *this;
  7224. }
  7225. inline Server &Server::set_tcp_nodelay(bool on) {
  7226. tcp_nodelay_ = on;
  7227. return *this;
  7228. }
  7229. inline Server &Server::set_ipv6_v6only(bool on) {
  7230. ipv6_v6only_ = on;
  7231. return *this;
  7232. }
  7233. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  7234. socket_options_ = std::move(socket_options);
  7235. return *this;
  7236. }
  7237. inline Server &Server::set_default_headers(Headers headers) {
  7238. default_headers_ = std::move(headers);
  7239. return *this;
  7240. }
  7241. inline Server &Server::set_header_writer(
  7242. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7243. header_writer_ = writer;
  7244. return *this;
  7245. }
  7246. inline Server &
  7247. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  7248. trusted_proxies_ = proxies;
  7249. return *this;
  7250. }
  7251. inline Server &Server::set_keep_alive_max_count(size_t count) {
  7252. keep_alive_max_count_ = count;
  7253. return *this;
  7254. }
  7255. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  7256. keep_alive_timeout_sec_ = sec;
  7257. return *this;
  7258. }
  7259. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  7260. read_timeout_sec_ = sec;
  7261. read_timeout_usec_ = usec;
  7262. return *this;
  7263. }
  7264. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  7265. write_timeout_sec_ = sec;
  7266. write_timeout_usec_ = usec;
  7267. return *this;
  7268. }
  7269. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  7270. idle_interval_sec_ = sec;
  7271. idle_interval_usec_ = usec;
  7272. return *this;
  7273. }
  7274. inline Server &Server::set_payload_max_length(size_t length) {
  7275. payload_max_length_ = length;
  7276. return *this;
  7277. }
  7278. inline bool Server::bind_to_port(const std::string &host, int port,
  7279. int socket_flags) {
  7280. auto ret = bind_internal(host, port, socket_flags);
  7281. if (ret == -1) { is_decommissioned = true; }
  7282. return ret >= 0;
  7283. }
  7284. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  7285. auto ret = bind_internal(host, 0, socket_flags);
  7286. if (ret == -1) { is_decommissioned = true; }
  7287. return ret;
  7288. }
  7289. inline bool Server::listen_after_bind() { return listen_internal(); }
  7290. inline bool Server::listen(const std::string &host, int port,
  7291. int socket_flags) {
  7292. return bind_to_port(host, port, socket_flags) && listen_internal();
  7293. }
  7294. inline bool Server::is_running() const { return is_running_; }
  7295. inline void Server::wait_until_ready() const {
  7296. while (!is_running_ && !is_decommissioned) {
  7297. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7298. }
  7299. }
  7300. inline void Server::stop() {
  7301. if (is_running_) {
  7302. assert(svr_sock_ != INVALID_SOCKET);
  7303. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  7304. detail::shutdown_socket(sock);
  7305. detail::close_socket(sock);
  7306. }
  7307. is_decommissioned = false;
  7308. }
  7309. inline void Server::decommission() { is_decommissioned = true; }
  7310. inline bool Server::parse_request_line(const char *s, Request &req) const {
  7311. auto len = strlen(s);
  7312. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  7313. len -= 2;
  7314. {
  7315. size_t count = 0;
  7316. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  7317. switch (count) {
  7318. case 0: req.method = std::string(b, e); break;
  7319. case 1: req.target = std::string(b, e); break;
  7320. case 2: req.version = std::string(b, e); break;
  7321. default: break;
  7322. }
  7323. count++;
  7324. });
  7325. if (count != 3) { return false; }
  7326. }
  7327. thread_local const std::set<std::string> methods{
  7328. "GET", "HEAD", "POST", "PUT", "DELETE",
  7329. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7330. if (methods.find(req.method) == methods.end()) {
  7331. output_error_log(Error::InvalidHTTPMethod, &req);
  7332. return false;
  7333. }
  7334. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  7335. output_error_log(Error::InvalidHTTPVersion, &req);
  7336. return false;
  7337. }
  7338. {
  7339. // Skip URL fragment
  7340. for (size_t i = 0; i < req.target.size(); i++) {
  7341. if (req.target[i] == '#') {
  7342. req.target.erase(i);
  7343. break;
  7344. }
  7345. }
  7346. detail::divide(req.target, '?',
  7347. [&](const char *lhs_data, std::size_t lhs_size,
  7348. const char *rhs_data, std::size_t rhs_size) {
  7349. req.path =
  7350. decode_path_component(std::string(lhs_data, lhs_size));
  7351. detail::parse_query_text(rhs_data, rhs_size, req.params);
  7352. });
  7353. }
  7354. return true;
  7355. }
  7356. inline bool Server::write_response(Stream &strm, bool close_connection,
  7357. Request &req, Response &res) {
  7358. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  7359. // incorrectly to the error content.
  7360. req.ranges.clear();
  7361. return write_response_core(strm, close_connection, req, res, false);
  7362. }
  7363. inline bool Server::write_response_with_content(Stream &strm,
  7364. bool close_connection,
  7365. const Request &req,
  7366. Response &res) {
  7367. return write_response_core(strm, close_connection, req, res, true);
  7368. }
  7369. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  7370. const Request &req, Response &res,
  7371. bool need_apply_ranges) {
  7372. assert(res.status != -1);
  7373. if (400 <= res.status && error_handler_ &&
  7374. error_handler_(req, res) == HandlerResponse::Handled) {
  7375. need_apply_ranges = true;
  7376. }
  7377. std::string content_type;
  7378. std::string boundary;
  7379. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  7380. // Prepare additional headers
  7381. if (close_connection || req.get_header_value("Connection") == "close" ||
  7382. 400 <= res.status) { // Don't leave connections open after errors
  7383. res.set_header("Connection", "close");
  7384. } else {
  7385. std::string s = "timeout=";
  7386. s += std::to_string(keep_alive_timeout_sec_);
  7387. s += ", max=";
  7388. s += std::to_string(keep_alive_max_count_);
  7389. res.set_header("Keep-Alive", s);
  7390. }
  7391. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  7392. !res.has_header("Content-Type")) {
  7393. res.set_header("Content-Type", "text/plain");
  7394. }
  7395. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  7396. !res.has_header("Content-Length")) {
  7397. res.set_header("Content-Length", "0");
  7398. }
  7399. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  7400. res.set_header("Accept-Ranges", "bytes");
  7401. }
  7402. if (post_routing_handler_) { post_routing_handler_(req, res); }
  7403. // Response line and headers
  7404. {
  7405. detail::BufferStream bstrm;
  7406. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  7407. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  7408. // Flush buffer
  7409. auto &data = bstrm.get_buffer();
  7410. detail::write_data(strm, data.data(), data.size());
  7411. }
  7412. // Body
  7413. auto ret = true;
  7414. if (req.method != "HEAD") {
  7415. if (!res.body.empty()) {
  7416. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  7417. ret = false;
  7418. }
  7419. } else if (res.content_provider_) {
  7420. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  7421. res.content_provider_success_ = true;
  7422. } else {
  7423. ret = false;
  7424. }
  7425. }
  7426. }
  7427. // Log
  7428. output_log(req, res);
  7429. return ret;
  7430. }
  7431. inline bool
  7432. Server::write_content_with_provider(Stream &strm, const Request &req,
  7433. Response &res, const std::string &boundary,
  7434. const std::string &content_type) {
  7435. auto is_shutting_down = [this]() {
  7436. return this->svr_sock_ == INVALID_SOCKET;
  7437. };
  7438. if (res.content_length_ > 0) {
  7439. if (req.ranges.empty()) {
  7440. return detail::write_content(strm, res.content_provider_, 0,
  7441. res.content_length_, is_shutting_down);
  7442. } else if (req.ranges.size() == 1) {
  7443. auto offset_and_length = detail::get_range_offset_and_length(
  7444. req.ranges[0], res.content_length_);
  7445. return detail::write_content(strm, res.content_provider_,
  7446. offset_and_length.first,
  7447. offset_and_length.second, is_shutting_down);
  7448. } else {
  7449. return detail::write_multipart_ranges_data(
  7450. strm, req, res, boundary, content_type, res.content_length_,
  7451. is_shutting_down);
  7452. }
  7453. } else {
  7454. if (res.is_chunked_content_provider_) {
  7455. auto type = detail::encoding_type(req, res);
  7456. std::unique_ptr<detail::compressor> compressor;
  7457. if (type == detail::EncodingType::Gzip) {
  7458. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7459. compressor = detail::make_unique<detail::gzip_compressor>();
  7460. #endif
  7461. } else if (type == detail::EncodingType::Brotli) {
  7462. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7463. compressor = detail::make_unique<detail::brotli_compressor>();
  7464. #endif
  7465. } else if (type == detail::EncodingType::Zstd) {
  7466. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7467. compressor = detail::make_unique<detail::zstd_compressor>();
  7468. #endif
  7469. } else {
  7470. compressor = detail::make_unique<detail::nocompressor>();
  7471. }
  7472. assert(compressor != nullptr);
  7473. return detail::write_content_chunked(strm, res.content_provider_,
  7474. is_shutting_down, *compressor);
  7475. } else {
  7476. return detail::write_content_without_length(strm, res.content_provider_,
  7477. is_shutting_down);
  7478. }
  7479. }
  7480. }
  7481. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  7482. FormFields::iterator cur_field;
  7483. FormFiles::iterator cur_file;
  7484. auto is_text_field = false;
  7485. size_t count = 0;
  7486. if (read_content_core(
  7487. strm, req, res,
  7488. // Regular
  7489. [&](const char *buf, size_t n) {
  7490. // Prevent arithmetic overflow when checking sizes.
  7491. // Avoid computing (req.body.size() + n) directly because
  7492. // adding two unsigned `size_t` values can wrap around and
  7493. // produce a small result instead of indicating overflow.
  7494. // Instead, check using subtraction: ensure `n` does not
  7495. // exceed the remaining capacity `max_size() - size()`.
  7496. if (req.body.size() >= req.body.max_size() ||
  7497. n > req.body.max_size() - req.body.size()) {
  7498. return false;
  7499. }
  7500. // Limit decompressed body size to payload_max_length_ to protect
  7501. // against "zip bomb" attacks where a small compressed payload
  7502. // decompresses to a massive size.
  7503. if (payload_max_length_ > 0 &&
  7504. (req.body.size() >= payload_max_length_ ||
  7505. n > payload_max_length_ - req.body.size())) {
  7506. return false;
  7507. }
  7508. req.body.append(buf, n);
  7509. return true;
  7510. },
  7511. // Multipart FormData
  7512. [&](const FormData &file) {
  7513. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  7514. output_error_log(Error::TooManyFormDataFiles, &req);
  7515. return false;
  7516. }
  7517. if (file.filename.empty()) {
  7518. cur_field = req.form.fields.emplace(
  7519. file.name, FormField{file.name, file.content, file.headers});
  7520. is_text_field = true;
  7521. } else {
  7522. cur_file = req.form.files.emplace(file.name, file);
  7523. is_text_field = false;
  7524. }
  7525. return true;
  7526. },
  7527. [&](const char *buf, size_t n) {
  7528. if (is_text_field) {
  7529. auto &content = cur_field->second.content;
  7530. if (content.size() + n > content.max_size()) { return false; }
  7531. content.append(buf, n);
  7532. } else {
  7533. auto &content = cur_file->second.content;
  7534. if (content.size() + n > content.max_size()) { return false; }
  7535. content.append(buf, n);
  7536. }
  7537. return true;
  7538. })) {
  7539. const auto &content_type = req.get_header_value("Content-Type");
  7540. if (!content_type.find("application/x-www-form-urlencoded")) {
  7541. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  7542. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  7543. output_error_log(Error::ExceedMaxPayloadSize, &req);
  7544. return false;
  7545. }
  7546. detail::parse_query_text(req.body, req.params);
  7547. }
  7548. return true;
  7549. }
  7550. return false;
  7551. }
  7552. inline bool Server::read_content_with_content_receiver(
  7553. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7554. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  7555. return read_content_core(strm, req, res, std::move(receiver),
  7556. std::move(multipart_header),
  7557. std::move(multipart_receiver));
  7558. }
  7559. inline bool Server::read_content_core(
  7560. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7561. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  7562. detail::FormDataParser multipart_form_data_parser;
  7563. ContentReceiverWithProgress out;
  7564. if (req.is_multipart_form_data()) {
  7565. const auto &content_type = req.get_header_value("Content-Type");
  7566. std::string boundary;
  7567. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  7568. res.status = StatusCode::BadRequest_400;
  7569. output_error_log(Error::MultipartParsing, &req);
  7570. return false;
  7571. }
  7572. multipart_form_data_parser.set_boundary(std::move(boundary));
  7573. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  7574. return multipart_form_data_parser.parse(buf, n, multipart_header,
  7575. multipart_receiver);
  7576. };
  7577. } else {
  7578. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  7579. size_t /*len*/) { return receiver(buf, n); };
  7580. }
  7581. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  7582. // are true (no Transfer-Encoding and no Content-Length), then the message
  7583. // body length is zero (no message body is present).
  7584. //
  7585. // For non-SSL builds, peek into the socket to detect clients that send a
  7586. // body without a Content-Length header (raw HTTP over TCP). If there is
  7587. // pending data that exceeds the configured payload limit, treat this as an
  7588. // oversized request and fail early (causing connection close). For SSL
  7589. // builds we cannot reliably peek the decrypted application bytes, so keep
  7590. // the original behaviour.
  7591. #if !defined(CPPHTTPLIB_OPENSSL_SUPPORT)
  7592. if (!req.has_header("Content-Length") &&
  7593. !detail::is_chunked_transfer_encoding(req.headers)) {
  7594. // Only peek if payload_max_length is set to a finite value
  7595. if (payload_max_length_ > 0 &&
  7596. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  7597. socket_t s = strm.socket();
  7598. if (s != INVALID_SOCKET) {
  7599. // Peek to check if there is any pending data
  7600. char peekbuf[1];
  7601. ssize_t n = ::recv(s, peekbuf, 1, MSG_PEEK);
  7602. if (n > 0) {
  7603. // There is data, so read it with payload limit enforcement
  7604. auto result = detail::read_content_without_length(
  7605. strm, payload_max_length_, out);
  7606. if (result == detail::ReadContentResult::PayloadTooLarge) {
  7607. res.status = StatusCode::PayloadTooLarge_413;
  7608. return false;
  7609. } else if (result != detail::ReadContentResult::Success) {
  7610. return false;
  7611. }
  7612. return true;
  7613. }
  7614. }
  7615. }
  7616. return true;
  7617. }
  7618. #else
  7619. if (!req.has_header("Content-Length") &&
  7620. !detail::is_chunked_transfer_encoding(req.headers)) {
  7621. return true;
  7622. }
  7623. #endif
  7624. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  7625. out, true)) {
  7626. return false;
  7627. }
  7628. if (req.is_multipart_form_data()) {
  7629. if (!multipart_form_data_parser.is_valid()) {
  7630. res.status = StatusCode::BadRequest_400;
  7631. output_error_log(Error::MultipartParsing, &req);
  7632. return false;
  7633. }
  7634. }
  7635. return true;
  7636. }
  7637. inline bool Server::handle_file_request(Request &req, Response &res) {
  7638. for (const auto &entry : base_dirs_) {
  7639. // Prefix match
  7640. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  7641. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  7642. if (detail::is_valid_path(sub_path)) {
  7643. auto path = entry.base_dir + sub_path;
  7644. if (path.back() == '/') { path += "index.html"; }
  7645. detail::FileStat stat(path);
  7646. if (stat.is_dir()) {
  7647. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  7648. return true;
  7649. }
  7650. if (stat.is_file()) {
  7651. for (const auto &kv : entry.headers) {
  7652. res.set_header(kv.first, kv.second);
  7653. }
  7654. auto etag = detail::compute_etag(stat);
  7655. if (!etag.empty()) { res.set_header("ETag", etag); }
  7656. auto mtime = stat.mtime();
  7657. auto last_modified = detail::file_mtime_to_http_date(mtime);
  7658. if (!last_modified.empty()) {
  7659. res.set_header("Last-Modified", last_modified);
  7660. }
  7661. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  7662. check_if_range(req, etag, mtime);
  7663. auto mm = std::make_shared<detail::mmap>(path.c_str());
  7664. if (!mm->is_open()) {
  7665. output_error_log(Error::OpenFile, &req);
  7666. return false;
  7667. }
  7668. res.set_content_provider(
  7669. mm->size(),
  7670. detail::find_content_type(path, file_extension_and_mimetype_map_,
  7671. default_file_mimetype_),
  7672. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  7673. sink.write(mm->data() + offset, length);
  7674. return true;
  7675. });
  7676. if (req.method != "HEAD" && file_request_handler_) {
  7677. file_request_handler_(req, res);
  7678. }
  7679. return true;
  7680. } else {
  7681. output_error_log(Error::OpenFile, &req);
  7682. }
  7683. }
  7684. }
  7685. }
  7686. return false;
  7687. }
  7688. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  7689. const std::string &etag,
  7690. time_t mtime) const {
  7691. // Handle conditional GET:
  7692. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  7693. // 2. If-Modified-Since is checked only when If-None-Match is absent
  7694. if (req.has_header("If-None-Match")) {
  7695. if (!etag.empty()) {
  7696. auto val = req.get_header_value("If-None-Match");
  7697. // NOTE: We use exact string matching here. This works correctly
  7698. // because our server always generates weak ETags (W/"..."), and
  7699. // clients typically send back the same ETag they received.
  7700. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  7701. // If-None-Match, where W/"x" and "x" would match, but this
  7702. // simplified implementation requires exact matches.
  7703. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  7704. [&](const char *b, const char *e) {
  7705. return std::equal(b, e, "*") ||
  7706. std::equal(b, e, etag.begin());
  7707. });
  7708. if (ret) {
  7709. res.status = StatusCode::NotModified_304;
  7710. return true;
  7711. }
  7712. }
  7713. } else if (req.has_header("If-Modified-Since")) {
  7714. auto val = req.get_header_value("If-Modified-Since");
  7715. auto t = detail::parse_http_date(val);
  7716. if (t != static_cast<time_t>(-1) && mtime <= t) {
  7717. res.status = StatusCode::NotModified_304;
  7718. return true;
  7719. }
  7720. }
  7721. return false;
  7722. }
  7723. inline bool Server::check_if_range(Request &req, const std::string &etag,
  7724. time_t mtime) const {
  7725. // Handle If-Range for partial content requests (RFC 9110
  7726. // Section 13.1.5). If-Range is only evaluated when Range header is
  7727. // present. If the validator matches, serve partial content; otherwise
  7728. // serve full content.
  7729. if (!req.ranges.empty() && req.has_header("If-Range")) {
  7730. auto val = req.get_header_value("If-Range");
  7731. auto is_valid_range = [&]() {
  7732. if (detail::is_strong_etag(val)) {
  7733. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  7734. // comparison.
  7735. return (!etag.empty() && val == etag);
  7736. } else if (detail::is_weak_etag(val)) {
  7737. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  7738. return false;
  7739. } else {
  7740. // HTTP-date comparison
  7741. auto t = detail::parse_http_date(val);
  7742. return (t != static_cast<time_t>(-1) && mtime <= t);
  7743. }
  7744. };
  7745. if (!is_valid_range()) {
  7746. // Validator doesn't match: ignore Range and serve full content
  7747. req.ranges.clear();
  7748. return false;
  7749. }
  7750. }
  7751. return true;
  7752. }
  7753. inline socket_t
  7754. Server::create_server_socket(const std::string &host, int port,
  7755. int socket_flags,
  7756. SocketOptions socket_options) const {
  7757. return detail::create_socket(
  7758. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  7759. ipv6_v6only_, std::move(socket_options),
  7760. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  7761. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  7762. output_error_log(Error::BindIPAddress, nullptr);
  7763. return false;
  7764. }
  7765. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  7766. output_error_log(Error::Listen, nullptr);
  7767. return false;
  7768. }
  7769. return true;
  7770. });
  7771. }
  7772. inline int Server::bind_internal(const std::string &host, int port,
  7773. int socket_flags) {
  7774. if (is_decommissioned) { return -1; }
  7775. if (!is_valid()) { return -1; }
  7776. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  7777. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  7778. if (port == 0) {
  7779. struct sockaddr_storage addr;
  7780. socklen_t addr_len = sizeof(addr);
  7781. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  7782. &addr_len) == -1) {
  7783. output_error_log(Error::GetSockName, nullptr);
  7784. return -1;
  7785. }
  7786. if (addr.ss_family == AF_INET) {
  7787. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  7788. } else if (addr.ss_family == AF_INET6) {
  7789. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  7790. } else {
  7791. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  7792. return -1;
  7793. }
  7794. } else {
  7795. return port;
  7796. }
  7797. }
  7798. inline bool Server::listen_internal() {
  7799. if (is_decommissioned) { return false; }
  7800. auto ret = true;
  7801. is_running_ = true;
  7802. auto se = detail::scope_exit([&]() { is_running_ = false; });
  7803. {
  7804. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  7805. while (svr_sock_ != INVALID_SOCKET) {
  7806. #ifndef _WIN32
  7807. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  7808. #endif
  7809. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  7810. idle_interval_usec_);
  7811. if (val == 0) { // Timeout
  7812. task_queue->on_idle();
  7813. continue;
  7814. }
  7815. #ifndef _WIN32
  7816. }
  7817. #endif
  7818. #if defined _WIN32
  7819. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  7820. // OVERLAPPED
  7821. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  7822. #elif defined SOCK_CLOEXEC
  7823. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  7824. #else
  7825. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  7826. #endif
  7827. if (sock == INVALID_SOCKET) {
  7828. if (errno == EMFILE) {
  7829. // The per-process limit of open file descriptors has been reached.
  7830. // Try to accept new connections after a short sleep.
  7831. std::this_thread::sleep_for(std::chrono::microseconds{1});
  7832. continue;
  7833. } else if (errno == EINTR || errno == EAGAIN) {
  7834. continue;
  7835. }
  7836. if (svr_sock_ != INVALID_SOCKET) {
  7837. detail::close_socket(svr_sock_);
  7838. ret = false;
  7839. output_error_log(Error::Connection, nullptr);
  7840. } else {
  7841. ; // The server socket was closed by user.
  7842. }
  7843. break;
  7844. }
  7845. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  7846. read_timeout_sec_, read_timeout_usec_);
  7847. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  7848. write_timeout_sec_, write_timeout_usec_);
  7849. if (!task_queue->enqueue(
  7850. [this, sock]() { process_and_close_socket(sock); })) {
  7851. output_error_log(Error::ResourceExhaustion, nullptr);
  7852. detail::shutdown_socket(sock);
  7853. detail::close_socket(sock);
  7854. }
  7855. }
  7856. task_queue->shutdown();
  7857. }
  7858. is_decommissioned = !ret;
  7859. return ret;
  7860. }
  7861. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  7862. if (pre_routing_handler_ &&
  7863. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  7864. return true;
  7865. }
  7866. // File handler
  7867. if ((req.method == "GET" || req.method == "HEAD") &&
  7868. handle_file_request(req, res)) {
  7869. return true;
  7870. }
  7871. if (detail::expect_content(req)) {
  7872. // Content reader handler
  7873. {
  7874. ContentReader reader(
  7875. [&](ContentReceiver receiver) {
  7876. auto result = read_content_with_content_receiver(
  7877. strm, req, res, std::move(receiver), nullptr, nullptr);
  7878. if (!result) { output_error_log(Error::Read, &req); }
  7879. return result;
  7880. },
  7881. [&](FormDataHeader header, ContentReceiver receiver) {
  7882. auto result = read_content_with_content_receiver(
  7883. strm, req, res, nullptr, std::move(header),
  7884. std::move(receiver));
  7885. if (!result) { output_error_log(Error::Read, &req); }
  7886. return result;
  7887. });
  7888. if (req.method == "POST") {
  7889. if (dispatch_request_for_content_reader(
  7890. req, res, std::move(reader),
  7891. post_handlers_for_content_reader_)) {
  7892. return true;
  7893. }
  7894. } else if (req.method == "PUT") {
  7895. if (dispatch_request_for_content_reader(
  7896. req, res, std::move(reader),
  7897. put_handlers_for_content_reader_)) {
  7898. return true;
  7899. }
  7900. } else if (req.method == "PATCH") {
  7901. if (dispatch_request_for_content_reader(
  7902. req, res, std::move(reader),
  7903. patch_handlers_for_content_reader_)) {
  7904. return true;
  7905. }
  7906. } else if (req.method == "DELETE") {
  7907. if (dispatch_request_for_content_reader(
  7908. req, res, std::move(reader),
  7909. delete_handlers_for_content_reader_)) {
  7910. return true;
  7911. }
  7912. }
  7913. }
  7914. // Read content into `req.body`
  7915. if (!read_content(strm, req, res)) {
  7916. output_error_log(Error::Read, &req);
  7917. return false;
  7918. }
  7919. }
  7920. // Regular handler
  7921. if (req.method == "GET" || req.method == "HEAD") {
  7922. return dispatch_request(req, res, get_handlers_);
  7923. } else if (req.method == "POST") {
  7924. return dispatch_request(req, res, post_handlers_);
  7925. } else if (req.method == "PUT") {
  7926. return dispatch_request(req, res, put_handlers_);
  7927. } else if (req.method == "DELETE") {
  7928. return dispatch_request(req, res, delete_handlers_);
  7929. } else if (req.method == "OPTIONS") {
  7930. return dispatch_request(req, res, options_handlers_);
  7931. } else if (req.method == "PATCH") {
  7932. return dispatch_request(req, res, patch_handlers_);
  7933. }
  7934. res.status = StatusCode::BadRequest_400;
  7935. return false;
  7936. }
  7937. inline bool Server::dispatch_request(Request &req, Response &res,
  7938. const Handlers &handlers) const {
  7939. for (const auto &x : handlers) {
  7940. const auto &matcher = x.first;
  7941. const auto &handler = x.second;
  7942. if (matcher->match(req)) {
  7943. req.matched_route = matcher->pattern();
  7944. if (!pre_request_handler_ ||
  7945. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  7946. handler(req, res);
  7947. }
  7948. return true;
  7949. }
  7950. }
  7951. return false;
  7952. }
  7953. inline void Server::apply_ranges(const Request &req, Response &res,
  7954. std::string &content_type,
  7955. std::string &boundary) const {
  7956. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  7957. auto it = res.headers.find("Content-Type");
  7958. if (it != res.headers.end()) {
  7959. content_type = it->second;
  7960. res.headers.erase(it);
  7961. }
  7962. boundary = detail::make_multipart_data_boundary();
  7963. res.set_header("Content-Type",
  7964. "multipart/byteranges; boundary=" + boundary);
  7965. }
  7966. auto type = detail::encoding_type(req, res);
  7967. if (res.body.empty()) {
  7968. if (res.content_length_ > 0) {
  7969. size_t length = 0;
  7970. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  7971. length = res.content_length_;
  7972. } else if (req.ranges.size() == 1) {
  7973. auto offset_and_length = detail::get_range_offset_and_length(
  7974. req.ranges[0], res.content_length_);
  7975. length = offset_and_length.second;
  7976. auto content_range = detail::make_content_range_header_field(
  7977. offset_and_length, res.content_length_);
  7978. res.set_header("Content-Range", content_range);
  7979. } else {
  7980. length = detail::get_multipart_ranges_data_length(
  7981. req, boundary, content_type, res.content_length_);
  7982. }
  7983. res.set_header("Content-Length", std::to_string(length));
  7984. } else {
  7985. if (res.content_provider_) {
  7986. if (res.is_chunked_content_provider_) {
  7987. res.set_header("Transfer-Encoding", "chunked");
  7988. if (type == detail::EncodingType::Gzip) {
  7989. res.set_header("Content-Encoding", "gzip");
  7990. res.set_header("Vary", "Accept-Encoding");
  7991. } else if (type == detail::EncodingType::Brotli) {
  7992. res.set_header("Content-Encoding", "br");
  7993. res.set_header("Vary", "Accept-Encoding");
  7994. } else if (type == detail::EncodingType::Zstd) {
  7995. res.set_header("Content-Encoding", "zstd");
  7996. res.set_header("Vary", "Accept-Encoding");
  7997. }
  7998. }
  7999. }
  8000. }
  8001. } else {
  8002. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  8003. ;
  8004. } else if (req.ranges.size() == 1) {
  8005. auto offset_and_length =
  8006. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  8007. auto offset = offset_and_length.first;
  8008. auto length = offset_and_length.second;
  8009. auto content_range = detail::make_content_range_header_field(
  8010. offset_and_length, res.body.size());
  8011. res.set_header("Content-Range", content_range);
  8012. assert(offset + length <= res.body.size());
  8013. res.body = res.body.substr(offset, length);
  8014. } else {
  8015. std::string data;
  8016. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  8017. res.body.size(), data);
  8018. res.body.swap(data);
  8019. }
  8020. if (type != detail::EncodingType::None) {
  8021. output_pre_compression_log(req, res);
  8022. std::unique_ptr<detail::compressor> compressor;
  8023. std::string content_encoding;
  8024. if (type == detail::EncodingType::Gzip) {
  8025. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8026. compressor = detail::make_unique<detail::gzip_compressor>();
  8027. content_encoding = "gzip";
  8028. #endif
  8029. } else if (type == detail::EncodingType::Brotli) {
  8030. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8031. compressor = detail::make_unique<detail::brotli_compressor>();
  8032. content_encoding = "br";
  8033. #endif
  8034. } else if (type == detail::EncodingType::Zstd) {
  8035. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8036. compressor = detail::make_unique<detail::zstd_compressor>();
  8037. content_encoding = "zstd";
  8038. #endif
  8039. }
  8040. if (compressor) {
  8041. std::string compressed;
  8042. if (compressor->compress(res.body.data(), res.body.size(), true,
  8043. [&](const char *data, size_t data_len) {
  8044. compressed.append(data, data_len);
  8045. return true;
  8046. })) {
  8047. res.body.swap(compressed);
  8048. res.set_header("Content-Encoding", content_encoding);
  8049. res.set_header("Vary", "Accept-Encoding");
  8050. }
  8051. }
  8052. }
  8053. auto length = std::to_string(res.body.size());
  8054. res.set_header("Content-Length", length);
  8055. }
  8056. }
  8057. inline bool Server::dispatch_request_for_content_reader(
  8058. Request &req, Response &res, ContentReader content_reader,
  8059. const HandlersForContentReader &handlers) const {
  8060. for (const auto &x : handlers) {
  8061. const auto &matcher = x.first;
  8062. const auto &handler = x.second;
  8063. if (matcher->match(req)) {
  8064. req.matched_route = matcher->pattern();
  8065. if (!pre_request_handler_ ||
  8066. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8067. handler(req, res, content_reader);
  8068. }
  8069. return true;
  8070. }
  8071. }
  8072. return false;
  8073. }
  8074. inline std::string
  8075. get_client_ip(const std::string &x_forwarded_for,
  8076. const std::vector<std::string> &trusted_proxies) {
  8077. // X-Forwarded-For is a comma-separated list per RFC 7239
  8078. std::vector<std::string> ip_list;
  8079. detail::split(x_forwarded_for.data(),
  8080. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  8081. [&](const char *b, const char *e) {
  8082. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  8083. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  8084. });
  8085. for (size_t i = 0; i < ip_list.size(); ++i) {
  8086. auto ip = ip_list[i];
  8087. auto is_trusted_proxy =
  8088. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  8089. [&](const std::string &proxy) { return ip == proxy; });
  8090. if (is_trusted_proxy) {
  8091. if (i == 0) {
  8092. // If the trusted proxy is the first IP, there's no preceding client IP
  8093. return ip;
  8094. } else {
  8095. // Return the IP immediately before the trusted proxy
  8096. return ip_list[i - 1];
  8097. }
  8098. }
  8099. }
  8100. // If no trusted proxy is found, return the first IP in the list
  8101. return ip_list.front();
  8102. }
  8103. inline bool
  8104. Server::process_request(Stream &strm, const std::string &remote_addr,
  8105. int remote_port, const std::string &local_addr,
  8106. int local_port, bool close_connection,
  8107. bool &connection_closed,
  8108. const std::function<void(Request &)> &setup_request) {
  8109. std::array<char, 2048> buf{};
  8110. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8111. // Connection has been closed on client
  8112. if (!line_reader.getline()) { return false; }
  8113. Request req;
  8114. req.start_time_ = std::chrono::steady_clock::now();
  8115. req.remote_addr = remote_addr;
  8116. req.remote_port = remote_port;
  8117. req.local_addr = local_addr;
  8118. req.local_port = local_port;
  8119. Response res;
  8120. res.version = "HTTP/1.1";
  8121. res.headers = default_headers_;
  8122. #ifdef __APPLE__
  8123. // Socket file descriptor exceeded FD_SETSIZE...
  8124. if (strm.socket() >= FD_SETSIZE) {
  8125. Headers dummy;
  8126. detail::read_headers(strm, dummy);
  8127. res.status = StatusCode::InternalServerError_500;
  8128. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  8129. return write_response(strm, close_connection, req, res);
  8130. }
  8131. #endif
  8132. // Request line and headers
  8133. if (!parse_request_line(line_reader.ptr(), req)) {
  8134. res.status = StatusCode::BadRequest_400;
  8135. output_error_log(Error::InvalidRequestLine, &req);
  8136. return write_response(strm, close_connection, req, res);
  8137. }
  8138. // Request headers
  8139. if (!detail::read_headers(strm, req.headers)) {
  8140. res.status = StatusCode::BadRequest_400;
  8141. output_error_log(Error::InvalidHeaders, &req);
  8142. return write_response(strm, close_connection, req, res);
  8143. }
  8144. // Check if the request URI doesn't exceed the limit
  8145. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  8146. res.status = StatusCode::UriTooLong_414;
  8147. output_error_log(Error::ExceedUriMaxLength, &req);
  8148. return write_response(strm, close_connection, req, res);
  8149. }
  8150. if (req.get_header_value("Connection") == "close") {
  8151. connection_closed = true;
  8152. }
  8153. if (req.version == "HTTP/1.0" &&
  8154. req.get_header_value("Connection") != "Keep-Alive") {
  8155. connection_closed = true;
  8156. }
  8157. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  8158. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  8159. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  8160. } else {
  8161. req.remote_addr = remote_addr;
  8162. }
  8163. req.remote_port = remote_port;
  8164. req.local_addr = local_addr;
  8165. req.local_port = local_port;
  8166. if (req.has_header("Accept")) {
  8167. const auto &accept_header = req.get_header_value("Accept");
  8168. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  8169. res.status = StatusCode::BadRequest_400;
  8170. output_error_log(Error::HTTPParsing, &req);
  8171. return write_response(strm, close_connection, req, res);
  8172. }
  8173. }
  8174. if (req.has_header("Range")) {
  8175. const auto &range_header_value = req.get_header_value("Range");
  8176. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  8177. res.status = StatusCode::RangeNotSatisfiable_416;
  8178. output_error_log(Error::InvalidRangeHeader, &req);
  8179. return write_response(strm, close_connection, req, res);
  8180. }
  8181. }
  8182. if (setup_request) { setup_request(req); }
  8183. if (req.get_header_value("Expect") == "100-continue") {
  8184. int status = StatusCode::Continue_100;
  8185. if (expect_100_continue_handler_) {
  8186. status = expect_100_continue_handler_(req, res);
  8187. }
  8188. switch (status) {
  8189. case StatusCode::Continue_100:
  8190. case StatusCode::ExpectationFailed_417:
  8191. detail::write_response_line(strm, status);
  8192. strm.write("\r\n");
  8193. break;
  8194. default:
  8195. connection_closed = true;
  8196. return write_response(strm, true, req, res);
  8197. }
  8198. }
  8199. // Setup `is_connection_closed` method
  8200. auto sock = strm.socket();
  8201. req.is_connection_closed = [sock]() {
  8202. return !detail::is_socket_alive(sock);
  8203. };
  8204. // Routing
  8205. auto routed = false;
  8206. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8207. routed = routing(req, res, strm);
  8208. #else
  8209. try {
  8210. routed = routing(req, res, strm);
  8211. } catch (std::exception &e) {
  8212. if (exception_handler_) {
  8213. auto ep = std::current_exception();
  8214. exception_handler_(req, res, ep);
  8215. routed = true;
  8216. } else {
  8217. res.status = StatusCode::InternalServerError_500;
  8218. std::string val;
  8219. auto s = e.what();
  8220. for (size_t i = 0; s[i]; i++) {
  8221. switch (s[i]) {
  8222. case '\r': val += "\\r"; break;
  8223. case '\n': val += "\\n"; break;
  8224. default: val += s[i]; break;
  8225. }
  8226. }
  8227. res.set_header("EXCEPTION_WHAT", val);
  8228. }
  8229. } catch (...) {
  8230. if (exception_handler_) {
  8231. auto ep = std::current_exception();
  8232. exception_handler_(req, res, ep);
  8233. routed = true;
  8234. } else {
  8235. res.status = StatusCode::InternalServerError_500;
  8236. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  8237. }
  8238. }
  8239. #endif
  8240. if (routed) {
  8241. if (res.status == -1) {
  8242. res.status = req.ranges.empty() ? StatusCode::OK_200
  8243. : StatusCode::PartialContent_206;
  8244. }
  8245. // Serve file content by using a content provider
  8246. if (!res.file_content_path_.empty()) {
  8247. const auto &path = res.file_content_path_;
  8248. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8249. if (!mm->is_open()) {
  8250. res.body.clear();
  8251. res.content_length_ = 0;
  8252. res.content_provider_ = nullptr;
  8253. res.status = StatusCode::NotFound_404;
  8254. output_error_log(Error::OpenFile, &req);
  8255. return write_response(strm, close_connection, req, res);
  8256. }
  8257. auto content_type = res.file_content_content_type_;
  8258. if (content_type.empty()) {
  8259. content_type = detail::find_content_type(
  8260. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  8261. }
  8262. res.set_content_provider(
  8263. mm->size(), content_type,
  8264. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8265. sink.write(mm->data() + offset, length);
  8266. return true;
  8267. });
  8268. }
  8269. if (detail::range_error(req, res)) {
  8270. res.body.clear();
  8271. res.content_length_ = 0;
  8272. res.content_provider_ = nullptr;
  8273. res.status = StatusCode::RangeNotSatisfiable_416;
  8274. return write_response(strm, close_connection, req, res);
  8275. }
  8276. return write_response_with_content(strm, close_connection, req, res);
  8277. } else {
  8278. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  8279. return write_response(strm, close_connection, req, res);
  8280. }
  8281. }
  8282. inline bool Server::is_valid() const { return true; }
  8283. inline bool Server::process_and_close_socket(socket_t sock) {
  8284. std::string remote_addr;
  8285. int remote_port = 0;
  8286. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8287. std::string local_addr;
  8288. int local_port = 0;
  8289. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8290. auto ret = detail::process_server_socket(
  8291. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8292. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8293. write_timeout_usec_,
  8294. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8295. return process_request(strm, remote_addr, remote_port, local_addr,
  8296. local_port, close_connection, connection_closed,
  8297. nullptr);
  8298. });
  8299. detail::shutdown_socket(sock);
  8300. detail::close_socket(sock);
  8301. return ret;
  8302. }
  8303. inline void Server::output_log(const Request &req, const Response &res) const {
  8304. if (logger_) {
  8305. std::lock_guard<std::mutex> guard(logger_mutex_);
  8306. logger_(req, res);
  8307. }
  8308. }
  8309. inline void Server::output_pre_compression_log(const Request &req,
  8310. const Response &res) const {
  8311. if (pre_compression_logger_) {
  8312. std::lock_guard<std::mutex> guard(logger_mutex_);
  8313. pre_compression_logger_(req, res);
  8314. }
  8315. }
  8316. inline void Server::output_error_log(const Error &err,
  8317. const Request *req) const {
  8318. if (error_logger_) {
  8319. std::lock_guard<std::mutex> guard(logger_mutex_);
  8320. error_logger_(err, req);
  8321. }
  8322. }
  8323. // HTTP client implementation
  8324. inline ClientImpl::ClientImpl(const std::string &host)
  8325. : ClientImpl(host, 80, std::string(), std::string()) {}
  8326. inline ClientImpl::ClientImpl(const std::string &host, int port)
  8327. : ClientImpl(host, port, std::string(), std::string()) {}
  8328. inline ClientImpl::ClientImpl(const std::string &host, int port,
  8329. const std::string &client_cert_path,
  8330. const std::string &client_key_path)
  8331. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  8332. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  8333. inline ClientImpl::~ClientImpl() {
  8334. // Wait until all the requests in flight are handled.
  8335. size_t retry_count = 10;
  8336. while (retry_count-- > 0) {
  8337. {
  8338. std::lock_guard<std::mutex> guard(socket_mutex_);
  8339. if (socket_requests_in_flight_ == 0) { break; }
  8340. }
  8341. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  8342. }
  8343. std::lock_guard<std::mutex> guard(socket_mutex_);
  8344. shutdown_socket(socket_);
  8345. close_socket(socket_);
  8346. }
  8347. inline bool ClientImpl::is_valid() const { return true; }
  8348. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  8349. client_cert_path_ = rhs.client_cert_path_;
  8350. client_key_path_ = rhs.client_key_path_;
  8351. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  8352. read_timeout_sec_ = rhs.read_timeout_sec_;
  8353. read_timeout_usec_ = rhs.read_timeout_usec_;
  8354. write_timeout_sec_ = rhs.write_timeout_sec_;
  8355. write_timeout_usec_ = rhs.write_timeout_usec_;
  8356. max_timeout_msec_ = rhs.max_timeout_msec_;
  8357. basic_auth_username_ = rhs.basic_auth_username_;
  8358. basic_auth_password_ = rhs.basic_auth_password_;
  8359. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  8360. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8361. digest_auth_username_ = rhs.digest_auth_username_;
  8362. digest_auth_password_ = rhs.digest_auth_password_;
  8363. #endif
  8364. keep_alive_ = rhs.keep_alive_;
  8365. follow_location_ = rhs.follow_location_;
  8366. path_encode_ = rhs.path_encode_;
  8367. address_family_ = rhs.address_family_;
  8368. tcp_nodelay_ = rhs.tcp_nodelay_;
  8369. ipv6_v6only_ = rhs.ipv6_v6only_;
  8370. socket_options_ = rhs.socket_options_;
  8371. compress_ = rhs.compress_;
  8372. decompress_ = rhs.decompress_;
  8373. interface_ = rhs.interface_;
  8374. proxy_host_ = rhs.proxy_host_;
  8375. proxy_port_ = rhs.proxy_port_;
  8376. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  8377. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  8378. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  8379. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8380. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  8381. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  8382. #endif
  8383. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8384. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  8385. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  8386. ca_cert_store_ = rhs.ca_cert_store_;
  8387. #endif
  8388. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8389. server_certificate_verification_ = rhs.server_certificate_verification_;
  8390. server_hostname_verification_ = rhs.server_hostname_verification_;
  8391. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  8392. #endif
  8393. logger_ = rhs.logger_;
  8394. error_logger_ = rhs.error_logger_;
  8395. }
  8396. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  8397. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8398. return detail::create_client_socket(
  8399. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  8400. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  8401. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  8402. write_timeout_sec_, write_timeout_usec_, interface_, error);
  8403. }
  8404. // Check is custom IP specified for host_
  8405. std::string ip;
  8406. auto it = addr_map_.find(host_);
  8407. if (it != addr_map_.end()) { ip = it->second; }
  8408. return detail::create_client_socket(
  8409. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  8410. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  8411. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8412. write_timeout_usec_, interface_, error);
  8413. }
  8414. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  8415. Error &error) {
  8416. auto sock = create_client_socket(error);
  8417. if (sock == INVALID_SOCKET) { return false; }
  8418. socket.sock = sock;
  8419. return true;
  8420. }
  8421. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  8422. return create_and_connect_socket(socket, error);
  8423. }
  8424. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8425. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  8426. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  8427. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  8428. if (!initialize_ssl(socket, error)) {
  8429. shutdown_socket(socket);
  8430. close_socket(socket);
  8431. return false;
  8432. }
  8433. return true;
  8434. }
  8435. #endif
  8436. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  8437. bool /*shutdown_gracefully*/) {
  8438. // If there are any requests in flight from threads other than us, then it's
  8439. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  8440. assert(socket_requests_in_flight_ == 0 ||
  8441. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8442. }
  8443. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  8444. if (socket.sock == INVALID_SOCKET) { return; }
  8445. detail::shutdown_socket(socket.sock);
  8446. }
  8447. inline void ClientImpl::close_socket(Socket &socket) {
  8448. // If there are requests in flight in another thread, usually closing
  8449. // the socket will be fine and they will simply receive an error when
  8450. // using the closed socket, but it is still a bug since rarely the OS
  8451. // may reassign the socket id to be used for a new socket, and then
  8452. // suddenly they will be operating on a live socket that is different
  8453. // than the one they intended!
  8454. assert(socket_requests_in_flight_ == 0 ||
  8455. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8456. // It is also a bug if this happens while SSL is still active
  8457. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8458. assert(socket.ssl == nullptr);
  8459. #endif
  8460. if (socket.sock == INVALID_SOCKET) { return; }
  8461. detail::close_socket(socket.sock);
  8462. socket.sock = INVALID_SOCKET;
  8463. }
  8464. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  8465. Response &res,
  8466. bool skip_100_continue) const {
  8467. std::array<char, 2048> buf{};
  8468. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8469. if (!line_reader.getline()) { return false; }
  8470. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  8471. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  8472. #else
  8473. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  8474. #endif
  8475. std::cmatch m;
  8476. if (!std::regex_match(line_reader.ptr(), m, re)) {
  8477. return req.method == "CONNECT";
  8478. }
  8479. res.version = std::string(m[1]);
  8480. res.status = std::stoi(std::string(m[2]));
  8481. res.reason = std::string(m[3]);
  8482. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  8483. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  8484. if (!line_reader.getline()) { return false; } // CRLF
  8485. if (!line_reader.getline()) { return false; } // next response line
  8486. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  8487. res.version = std::string(m[1]);
  8488. res.status = std::stoi(std::string(m[2]));
  8489. res.reason = std::string(m[3]);
  8490. }
  8491. return true;
  8492. }
  8493. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  8494. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  8495. auto ret = send_(req, res, error);
  8496. if (error == Error::SSLPeerCouldBeClosed_) {
  8497. assert(!ret);
  8498. ret = send_(req, res, error);
  8499. }
  8500. return ret;
  8501. }
  8502. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  8503. {
  8504. std::lock_guard<std::mutex> guard(socket_mutex_);
  8505. // Set this to false immediately - if it ever gets set to true by the end
  8506. // of the request, we know another thread instructed us to close the
  8507. // socket.
  8508. socket_should_be_closed_when_request_is_done_ = false;
  8509. auto is_alive = false;
  8510. if (socket_.is_open()) {
  8511. is_alive = detail::is_socket_alive(socket_.sock);
  8512. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8513. if (is_alive && is_ssl()) {
  8514. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  8515. is_alive = false;
  8516. }
  8517. }
  8518. #endif
  8519. if (!is_alive) {
  8520. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  8521. // seems like the other side has already closed the connection Also,
  8522. // there cannot be any requests in flight from other threads since we
  8523. // locked request_mutex_, so safe to close everything immediately
  8524. const bool shutdown_gracefully = false;
  8525. shutdown_ssl(socket_, shutdown_gracefully);
  8526. shutdown_socket(socket_);
  8527. close_socket(socket_);
  8528. }
  8529. }
  8530. if (!is_alive) {
  8531. if (!ensure_socket_connection(socket_, error)) {
  8532. output_error_log(error, &req);
  8533. return false;
  8534. }
  8535. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8536. // TODO: refactoring
  8537. if (is_ssl()) {
  8538. auto &scli = static_cast<SSLClient &>(*this);
  8539. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8540. auto success = false;
  8541. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  8542. error)) {
  8543. if (!success) { output_error_log(error, &req); }
  8544. return success;
  8545. }
  8546. }
  8547. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8548. if (!scli.initialize_ssl(socket_, error)) {
  8549. output_error_log(error, &req);
  8550. return false;
  8551. }
  8552. }
  8553. }
  8554. #endif
  8555. }
  8556. // Mark the current socket as being in use so that it cannot be closed by
  8557. // anyone else while this request is ongoing, even though we will be
  8558. // releasing the mutex.
  8559. if (socket_requests_in_flight_ > 1) {
  8560. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  8561. }
  8562. socket_requests_in_flight_ += 1;
  8563. socket_requests_are_from_thread_ = std::this_thread::get_id();
  8564. }
  8565. for (const auto &header : default_headers_) {
  8566. if (req.headers.find(header.first) == req.headers.end()) {
  8567. req.headers.insert(header);
  8568. }
  8569. }
  8570. auto ret = false;
  8571. auto close_connection = !keep_alive_;
  8572. auto se = detail::scope_exit([&]() {
  8573. // Briefly lock mutex in order to mark that a request is no longer ongoing
  8574. std::lock_guard<std::mutex> guard(socket_mutex_);
  8575. socket_requests_in_flight_ -= 1;
  8576. if (socket_requests_in_flight_ <= 0) {
  8577. assert(socket_requests_in_flight_ == 0);
  8578. socket_requests_are_from_thread_ = std::thread::id();
  8579. }
  8580. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  8581. !ret) {
  8582. shutdown_ssl(socket_, true);
  8583. shutdown_socket(socket_);
  8584. close_socket(socket_);
  8585. }
  8586. });
  8587. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  8588. return handle_request(strm, req, res, close_connection, error);
  8589. });
  8590. if (!ret) {
  8591. if (error == Error::Success) {
  8592. error = Error::Unknown;
  8593. output_error_log(error, &req);
  8594. }
  8595. }
  8596. return ret;
  8597. }
  8598. inline Result ClientImpl::send(const Request &req) {
  8599. auto req2 = req;
  8600. return send_(std::move(req2));
  8601. }
  8602. inline Result ClientImpl::send_(Request &&req) {
  8603. auto res = detail::make_unique<Response>();
  8604. auto error = Error::Success;
  8605. auto ret = send(req, *res, error);
  8606. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8607. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  8608. last_ssl_error_, last_openssl_error_};
  8609. #else
  8610. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  8611. #endif
  8612. }
  8613. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  8614. const std::string &ct) {
  8615. (void)for_stream;
  8616. for (const auto &header : default_headers_) {
  8617. if (!r.has_header(header.first)) { r.headers.insert(header); }
  8618. }
  8619. if (!r.has_header("Host")) {
  8620. if (address_family_ == AF_UNIX) {
  8621. r.headers.emplace("Host", "localhost");
  8622. } else {
  8623. r.headers.emplace(
  8624. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  8625. }
  8626. }
  8627. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  8628. if (!r.content_receiver) {
  8629. if (!r.has_header("Accept-Encoding")) {
  8630. std::string accept_encoding;
  8631. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8632. accept_encoding = "br";
  8633. #endif
  8634. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8635. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8636. accept_encoding += "gzip, deflate";
  8637. #endif
  8638. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8639. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8640. accept_encoding += "zstd";
  8641. #endif
  8642. r.set_header("Accept-Encoding", accept_encoding);
  8643. }
  8644. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  8645. if (!r.has_header("User-Agent")) {
  8646. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  8647. r.set_header("User-Agent", agent);
  8648. }
  8649. #endif
  8650. }
  8651. if (!r.body.empty()) {
  8652. if (!ct.empty() && !r.has_header("Content-Type")) {
  8653. r.headers.emplace("Content-Type", ct);
  8654. }
  8655. if (!r.has_header("Content-Length")) {
  8656. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  8657. }
  8658. }
  8659. }
  8660. inline ClientImpl::StreamHandle
  8661. ClientImpl::open_stream(const std::string &method, const std::string &path,
  8662. const Params &params, const Headers &headers,
  8663. const std::string &body,
  8664. const std::string &content_type) {
  8665. StreamHandle handle;
  8666. handle.response = detail::make_unique<Response>();
  8667. handle.error = Error::Success;
  8668. auto query_path = params.empty() ? path : append_query_params(path, params);
  8669. handle.connection_ = detail::make_unique<ClientConnection>();
  8670. {
  8671. std::lock_guard<std::mutex> guard(socket_mutex_);
  8672. auto is_alive = false;
  8673. if (socket_.is_open()) {
  8674. is_alive = detail::is_socket_alive(socket_.sock);
  8675. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8676. if (is_alive && is_ssl()) {
  8677. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  8678. is_alive = false;
  8679. }
  8680. }
  8681. #endif
  8682. if (!is_alive) {
  8683. shutdown_ssl(socket_, false);
  8684. shutdown_socket(socket_);
  8685. close_socket(socket_);
  8686. }
  8687. }
  8688. if (!is_alive) {
  8689. if (!ensure_socket_connection(socket_, handle.error)) {
  8690. handle.response.reset();
  8691. return handle;
  8692. }
  8693. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8694. if (is_ssl()) {
  8695. auto &scli = static_cast<SSLClient &>(*this);
  8696. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8697. if (!scli.initialize_ssl(socket_, handle.error)) {
  8698. handle.response.reset();
  8699. return handle;
  8700. }
  8701. }
  8702. }
  8703. #endif
  8704. }
  8705. transfer_socket_ownership_to_handle(handle);
  8706. }
  8707. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8708. if (is_ssl() && handle.connection_->ssl) {
  8709. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  8710. handle.connection_->sock, handle.connection_->ssl, read_timeout_sec_,
  8711. read_timeout_usec_, write_timeout_sec_, write_timeout_usec_);
  8712. } else {
  8713. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8714. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8715. write_timeout_sec_, write_timeout_usec_);
  8716. }
  8717. #else
  8718. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8719. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8720. write_timeout_sec_, write_timeout_usec_);
  8721. #endif
  8722. handle.stream_ = handle.socket_stream_.get();
  8723. Request req;
  8724. req.method = method;
  8725. req.path = query_path;
  8726. req.headers = headers;
  8727. req.body = body;
  8728. prepare_default_headers(req, true, content_type);
  8729. auto &strm = *handle.stream_;
  8730. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  8731. handle.error = Error::Write;
  8732. handle.response.reset();
  8733. return handle;
  8734. }
  8735. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  8736. handle.error)) {
  8737. handle.response.reset();
  8738. return handle;
  8739. }
  8740. if (!body.empty()) {
  8741. if (strm.write(body.data(), body.size()) < 0) {
  8742. handle.error = Error::Write;
  8743. handle.response.reset();
  8744. return handle;
  8745. }
  8746. }
  8747. if (!read_response_line(strm, req, *handle.response) ||
  8748. !detail::read_headers(strm, handle.response->headers)) {
  8749. handle.error = Error::Read;
  8750. handle.response.reset();
  8751. return handle;
  8752. }
  8753. handle.body_reader_.stream = handle.stream_;
  8754. auto content_length_str = handle.response->get_header_value("Content-Length");
  8755. if (!content_length_str.empty()) {
  8756. handle.body_reader_.content_length =
  8757. static_cast<size_t>(std::stoull(content_length_str));
  8758. }
  8759. auto transfer_encoding =
  8760. handle.response->get_header_value("Transfer-Encoding");
  8761. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  8762. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  8763. if (!content_encoding.empty()) {
  8764. handle.decompressor_ = detail::create_decompressor(content_encoding);
  8765. }
  8766. return handle;
  8767. }
  8768. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  8769. if (!is_valid() || !response) { return -1; }
  8770. if (decompressor_) { return read_with_decompression(buf, len); }
  8771. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  8772. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  8773. trailers_parsed_ = true;
  8774. if (body_reader_.chunked_decoder) {
  8775. if (!body_reader_.chunked_decoder->parse_trailers_into(
  8776. response->trailers, response->headers)) {
  8777. return n;
  8778. }
  8779. } else {
  8780. detail::ChunkedDecoder dec(*stream_);
  8781. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  8782. return n;
  8783. }
  8784. }
  8785. }
  8786. return n;
  8787. }
  8788. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  8789. size_t len) {
  8790. if (decompress_offset_ < decompress_buffer_.size()) {
  8791. auto available = decompress_buffer_.size() - decompress_offset_;
  8792. auto to_copy = (std::min)(len, available);
  8793. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  8794. decompress_offset_ += to_copy;
  8795. return static_cast<ssize_t>(to_copy);
  8796. }
  8797. decompress_buffer_.clear();
  8798. decompress_offset_ = 0;
  8799. constexpr size_t kDecompressionBufferSize = 8192;
  8800. char compressed_buf[kDecompressionBufferSize];
  8801. while (true) {
  8802. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  8803. sizeof(compressed_buf));
  8804. if (n <= 0) { return n; }
  8805. bool decompress_ok =
  8806. decompressor_->decompress(compressed_buf, static_cast<size_t>(n),
  8807. [this](const char *data, size_t data_len) {
  8808. decompress_buffer_.append(data, data_len);
  8809. return true;
  8810. });
  8811. if (!decompress_ok) {
  8812. body_reader_.last_error = Error::Read;
  8813. return -1;
  8814. }
  8815. if (!decompress_buffer_.empty()) { break; }
  8816. }
  8817. auto to_copy = (std::min)(len, decompress_buffer_.size());
  8818. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  8819. decompress_offset_ = to_copy;
  8820. return static_cast<ssize_t>(to_copy);
  8821. }
  8822. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  8823. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  8824. return;
  8825. }
  8826. trailers_parsed_ = true;
  8827. const auto bufsiz = 128;
  8828. char line_buf[bufsiz];
  8829. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  8830. if (!line_reader.getline()) { return; }
  8831. if (!detail::parse_trailers(line_reader, response->trailers,
  8832. response->headers)) {
  8833. return;
  8834. }
  8835. }
  8836. // Inline method implementations for `ChunkedDecoder`.
  8837. namespace detail {
  8838. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  8839. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  8840. size_t &out_chunk_offset,
  8841. size_t &out_chunk_total) {
  8842. if (finished) { return 0; }
  8843. if (chunk_remaining == 0) {
  8844. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  8845. if (!lr.getline()) { return -1; }
  8846. char *endptr = nullptr;
  8847. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  8848. if (endptr == lr.ptr()) { return -1; }
  8849. if (chunk_len == ULONG_MAX) { return -1; }
  8850. if (chunk_len == 0) {
  8851. chunk_remaining = 0;
  8852. finished = true;
  8853. out_chunk_offset = 0;
  8854. out_chunk_total = 0;
  8855. return 0;
  8856. }
  8857. chunk_remaining = static_cast<size_t>(chunk_len);
  8858. last_chunk_total = chunk_remaining;
  8859. last_chunk_offset = 0;
  8860. }
  8861. auto to_read = (std::min)(chunk_remaining, len);
  8862. auto n = strm.read(buf, to_read);
  8863. if (n <= 0) { return -1; }
  8864. auto offset_before = last_chunk_offset;
  8865. last_chunk_offset += static_cast<size_t>(n);
  8866. chunk_remaining -= static_cast<size_t>(n);
  8867. out_chunk_offset = offset_before;
  8868. out_chunk_total = last_chunk_total;
  8869. if (chunk_remaining == 0) {
  8870. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  8871. if (!lr.getline()) { return -1; }
  8872. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  8873. }
  8874. return n;
  8875. }
  8876. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  8877. const Headers &src_headers) {
  8878. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  8879. if (!lr.getline()) { return false; }
  8880. return parse_trailers(lr, dest, src_headers);
  8881. }
  8882. } // namespace detail
  8883. inline void
  8884. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  8885. handle.connection_->sock = socket_.sock;
  8886. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8887. handle.connection_->ssl = socket_.ssl;
  8888. socket_.ssl = nullptr;
  8889. #endif
  8890. socket_.sock = INVALID_SOCKET;
  8891. }
  8892. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  8893. Response &res, bool close_connection,
  8894. Error &error) {
  8895. if (req.path.empty()) {
  8896. error = Error::Connection;
  8897. output_error_log(error, &req);
  8898. return false;
  8899. }
  8900. auto req_save = req;
  8901. bool ret;
  8902. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  8903. auto req2 = req;
  8904. req2.path = "http://" +
  8905. detail::make_host_and_port_string(host_, port_, false) +
  8906. req.path;
  8907. ret = process_request(strm, req2, res, close_connection, error);
  8908. req = std::move(req2);
  8909. req.path = req_save.path;
  8910. } else {
  8911. ret = process_request(strm, req, res, close_connection, error);
  8912. }
  8913. if (!ret) { return false; }
  8914. if (res.get_header_value("Connection") == "close" ||
  8915. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  8916. // TODO this requires a not-entirely-obvious chain of calls to be correct
  8917. // for this to be safe.
  8918. // This is safe to call because handle_request is only called by send_
  8919. // which locks the request mutex during the process. It would be a bug
  8920. // to call it from a different thread since it's a thread-safety issue
  8921. // to do these things to the socket if another thread is using the socket.
  8922. std::lock_guard<std::mutex> guard(socket_mutex_);
  8923. shutdown_ssl(socket_, true);
  8924. shutdown_socket(socket_);
  8925. close_socket(socket_);
  8926. }
  8927. if (300 < res.status && res.status < 400 && follow_location_) {
  8928. req = std::move(req_save);
  8929. ret = redirect(req, res, error);
  8930. }
  8931. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8932. if ((res.status == StatusCode::Unauthorized_401 ||
  8933. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  8934. req.authorization_count_ < 5) {
  8935. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  8936. const auto &username =
  8937. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  8938. const auto &password =
  8939. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  8940. if (!username.empty() && !password.empty()) {
  8941. std::map<std::string, std::string> auth;
  8942. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  8943. Request new_req = req;
  8944. new_req.authorization_count_ += 1;
  8945. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  8946. : "Authorization");
  8947. new_req.headers.insert(detail::make_digest_authentication_header(
  8948. req, auth, new_req.authorization_count_, detail::random_string(10),
  8949. username, password, is_proxy));
  8950. Response new_res;
  8951. ret = send(new_req, new_res, error);
  8952. if (ret) { res = std::move(new_res); }
  8953. }
  8954. }
  8955. }
  8956. #endif
  8957. return ret;
  8958. }
  8959. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  8960. if (req.redirect_count_ == 0) {
  8961. error = Error::ExceedRedirectCount;
  8962. output_error_log(error, &req);
  8963. return false;
  8964. }
  8965. auto location = res.get_header_value("location");
  8966. if (location.empty()) { return false; }
  8967. thread_local const std::regex re(
  8968. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  8969. std::smatch m;
  8970. if (!std::regex_match(location, m, re)) { return false; }
  8971. auto scheme = is_ssl() ? "https" : "http";
  8972. auto next_scheme = m[1].str();
  8973. auto next_host = m[2].str();
  8974. if (next_host.empty()) { next_host = m[3].str(); }
  8975. auto port_str = m[4].str();
  8976. auto next_path = m[5].str();
  8977. auto next_query = m[6].str();
  8978. auto next_port = port_;
  8979. if (!port_str.empty()) {
  8980. next_port = std::stoi(port_str);
  8981. } else if (!next_scheme.empty()) {
  8982. next_port = next_scheme == "https" ? 443 : 80;
  8983. }
  8984. if (next_scheme.empty()) { next_scheme = scheme; }
  8985. if (next_host.empty()) { next_host = host_; }
  8986. if (next_path.empty()) { next_path = "/"; }
  8987. auto path = decode_query_component(next_path, true) + next_query;
  8988. // Same host redirect - use current client
  8989. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  8990. return detail::redirect(*this, req, res, path, location, error);
  8991. }
  8992. // Cross-host/scheme redirect - create new client with robust setup
  8993. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  8994. path, location, error);
  8995. }
  8996. // New method for robust redirect client creation
  8997. inline bool ClientImpl::create_redirect_client(
  8998. const std::string &scheme, const std::string &host, int port, Request &req,
  8999. Response &res, const std::string &path, const std::string &location,
  9000. Error &error) {
  9001. // Determine if we need SSL
  9002. auto need_ssl = (scheme == "https");
  9003. // Clean up request headers that are host/client specific
  9004. // Remove headers that should not be carried over to new host
  9005. auto headers_to_remove =
  9006. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  9007. for (const auto &header_name : headers_to_remove) {
  9008. auto it = req.headers.find(header_name);
  9009. while (it != req.headers.end()) {
  9010. it = req.headers.erase(it);
  9011. it = req.headers.find(header_name);
  9012. }
  9013. }
  9014. // Create appropriate client type and handle redirect
  9015. if (need_ssl) {
  9016. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9017. // Create SSL client for HTTPS redirect
  9018. SSLClient redirect_client(host, port);
  9019. // Setup basic client configuration first
  9020. setup_redirect_client(redirect_client);
  9021. // SSL-specific configuration for proxy environments
  9022. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9023. // Critical: Disable SSL verification for proxy environments
  9024. redirect_client.enable_server_certificate_verification(false);
  9025. redirect_client.enable_server_hostname_verification(false);
  9026. } else {
  9027. // For direct SSL connections, copy SSL verification settings
  9028. redirect_client.enable_server_certificate_verification(
  9029. server_certificate_verification_);
  9030. redirect_client.enable_server_hostname_verification(
  9031. server_hostname_verification_);
  9032. }
  9033. // Handle CA certificate store and paths if available
  9034. if (ca_cert_store_ && X509_STORE_up_ref(ca_cert_store_)) {
  9035. redirect_client.set_ca_cert_store(ca_cert_store_);
  9036. }
  9037. if (!ca_cert_file_path_.empty()) {
  9038. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  9039. }
  9040. // Client certificates are set through constructor for SSLClient
  9041. // NOTE: SSLClient constructor already takes client_cert_path and
  9042. // client_key_path so we need to create it properly if client certs are
  9043. // needed
  9044. // Execute the redirect
  9045. return detail::redirect(redirect_client, req, res, path, location, error);
  9046. #else
  9047. // SSL not supported - set appropriate error
  9048. error = Error::SSLConnection;
  9049. output_error_log(error, &req);
  9050. return false;
  9051. #endif
  9052. } else {
  9053. // HTTP redirect
  9054. ClientImpl redirect_client(host, port);
  9055. // Setup client with robust configuration
  9056. setup_redirect_client(redirect_client);
  9057. // Execute the redirect
  9058. return detail::redirect(redirect_client, req, res, path, location, error);
  9059. }
  9060. }
  9061. // New method for robust client setup (based on basic_manual_redirect.cpp
  9062. // logic)
  9063. template <typename ClientType>
  9064. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  9065. // Copy basic settings first
  9066. client.set_connection_timeout(connection_timeout_sec_);
  9067. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  9068. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  9069. client.set_keep_alive(keep_alive_);
  9070. client.set_follow_location(
  9071. true); // Enable redirects to handle multi-step redirects
  9072. client.set_path_encode(path_encode_);
  9073. client.set_compress(compress_);
  9074. client.set_decompress(decompress_);
  9075. // Copy authentication settings BEFORE proxy setup
  9076. if (!basic_auth_username_.empty()) {
  9077. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  9078. }
  9079. if (!bearer_token_auth_token_.empty()) {
  9080. client.set_bearer_token_auth(bearer_token_auth_token_);
  9081. }
  9082. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9083. if (!digest_auth_username_.empty()) {
  9084. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  9085. }
  9086. #endif
  9087. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  9088. // before proxy auth)
  9089. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9090. // First set proxy host and port
  9091. client.set_proxy(proxy_host_, proxy_port_);
  9092. // Then set proxy authentication (order matters!)
  9093. if (!proxy_basic_auth_username_.empty()) {
  9094. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  9095. proxy_basic_auth_password_);
  9096. }
  9097. if (!proxy_bearer_token_auth_token_.empty()) {
  9098. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  9099. }
  9100. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9101. if (!proxy_digest_auth_username_.empty()) {
  9102. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  9103. proxy_digest_auth_password_);
  9104. }
  9105. #endif
  9106. }
  9107. // Copy network and socket settings
  9108. client.set_address_family(address_family_);
  9109. client.set_tcp_nodelay(tcp_nodelay_);
  9110. client.set_ipv6_v6only(ipv6_v6only_);
  9111. if (socket_options_) { client.set_socket_options(socket_options_); }
  9112. if (!interface_.empty()) { client.set_interface(interface_); }
  9113. // Copy logging and headers
  9114. if (logger_) { client.set_logger(logger_); }
  9115. if (error_logger_) { client.set_error_logger(error_logger_); }
  9116. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  9117. // Each new client should generate its own headers based on its target host
  9118. }
  9119. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  9120. const Request &req,
  9121. Error &error) const {
  9122. auto is_shutting_down = []() { return false; };
  9123. if (req.is_chunked_content_provider_) {
  9124. // TODO: Brotli support
  9125. std::unique_ptr<detail::compressor> compressor;
  9126. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9127. if (compress_) {
  9128. compressor = detail::make_unique<detail::gzip_compressor>();
  9129. } else
  9130. #endif
  9131. {
  9132. compressor = detail::make_unique<detail::nocompressor>();
  9133. }
  9134. return detail::write_content_chunked(strm, req.content_provider_,
  9135. is_shutting_down, *compressor, error);
  9136. } else {
  9137. return detail::write_content_with_progress(
  9138. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  9139. req.upload_progress, error);
  9140. }
  9141. }
  9142. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  9143. bool close_connection, Error &error,
  9144. bool skip_body) {
  9145. // Prepare additional headers
  9146. if (close_connection) {
  9147. if (!req.has_header("Connection")) {
  9148. req.set_header("Connection", "close");
  9149. }
  9150. }
  9151. std::string ct_for_defaults;
  9152. if (!req.has_header("Content-Type") && !req.body.empty()) {
  9153. ct_for_defaults = "text/plain";
  9154. }
  9155. prepare_default_headers(req, false, ct_for_defaults);
  9156. if (req.body.empty()) {
  9157. if (req.content_provider_) {
  9158. if (!req.is_chunked_content_provider_) {
  9159. if (!req.has_header("Content-Length")) {
  9160. auto length = std::to_string(req.content_length_);
  9161. req.set_header("Content-Length", length);
  9162. }
  9163. }
  9164. } else {
  9165. if (req.method == "POST" || req.method == "PUT" ||
  9166. req.method == "PATCH") {
  9167. req.set_header("Content-Length", "0");
  9168. }
  9169. }
  9170. }
  9171. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  9172. if (!req.has_header("Authorization")) {
  9173. req.headers.insert(make_basic_authentication_header(
  9174. basic_auth_username_, basic_auth_password_, false));
  9175. }
  9176. }
  9177. if (!proxy_basic_auth_username_.empty() &&
  9178. !proxy_basic_auth_password_.empty()) {
  9179. if (!req.has_header("Proxy-Authorization")) {
  9180. req.headers.insert(make_basic_authentication_header(
  9181. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  9182. }
  9183. }
  9184. if (!bearer_token_auth_token_.empty()) {
  9185. if (!req.has_header("Authorization")) {
  9186. req.headers.insert(make_bearer_token_authentication_header(
  9187. bearer_token_auth_token_, false));
  9188. }
  9189. }
  9190. if (!proxy_bearer_token_auth_token_.empty()) {
  9191. if (!req.has_header("Proxy-Authorization")) {
  9192. req.headers.insert(make_bearer_token_authentication_header(
  9193. proxy_bearer_token_auth_token_, true));
  9194. }
  9195. }
  9196. // Request line and headers
  9197. {
  9198. detail::BufferStream bstrm;
  9199. // Extract path and query from req.path
  9200. std::string path_part, query_part;
  9201. auto query_pos = req.path.find('?');
  9202. if (query_pos != std::string::npos) {
  9203. path_part = req.path.substr(0, query_pos);
  9204. query_part = req.path.substr(query_pos + 1);
  9205. } else {
  9206. path_part = req.path;
  9207. query_part = "";
  9208. }
  9209. // Encode path part. If the original `req.path` already contained a
  9210. // query component, preserve its raw query string (including parameter
  9211. // order) instead of reparsing and reassembling it which may reorder
  9212. // parameters due to container ordering (e.g. `Params` uses
  9213. // `std::multimap`). When there is no query in `req.path`, fall back to
  9214. // building a query from `req.params` so existing callers that pass
  9215. // `Params` continue to work.
  9216. auto path_with_query =
  9217. path_encode_ ? detail::encode_path(path_part) : path_part;
  9218. if (!query_part.empty()) {
  9219. // Normalize the query string (decode then re-encode) while preserving
  9220. // the original parameter order.
  9221. auto normalized = detail::normalize_query_string(query_part);
  9222. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  9223. // Still populate req.params for handlers/users who read them.
  9224. detail::parse_query_text(query_part, req.params);
  9225. } else {
  9226. // No query in path; parse any query_part (empty) and append params
  9227. // from `req.params` when present (preserves prior behavior for
  9228. // callers who provide Params separately).
  9229. detail::parse_query_text(query_part, req.params);
  9230. if (!req.params.empty()) {
  9231. path_with_query = append_query_params(path_with_query, req.params);
  9232. }
  9233. }
  9234. // Write request line and headers
  9235. detail::write_request_line(bstrm, req.method, path_with_query);
  9236. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  9237. error)) {
  9238. output_error_log(error, &req);
  9239. return false;
  9240. }
  9241. // Flush buffer
  9242. auto &data = bstrm.get_buffer();
  9243. if (!detail::write_data(strm, data.data(), data.size())) {
  9244. error = Error::Write;
  9245. output_error_log(error, &req);
  9246. return false;
  9247. }
  9248. }
  9249. // After sending request line and headers, wait briefly for an early server
  9250. // response (e.g. 4xx) and avoid sending a potentially large request body
  9251. // unnecessarily. This workaround is only enabled on Windows because Unix
  9252. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  9253. // buffering can accept large writes even when the peer already responded.
  9254. // Check the stream first (which covers SSL via `is_readable()`), then
  9255. // fall back to select on the socket. Only perform the wait for very large
  9256. // request bodies to avoid interfering with normal small requests and
  9257. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  9258. // response. Skip this check when using Expect: 100-continue, as the protocol
  9259. // handles early responses properly.
  9260. #if defined(_WIN32)
  9261. if (!skip_body &&
  9262. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  9263. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  9264. auto start = std::chrono::high_resolution_clock::now();
  9265. for (;;) {
  9266. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  9267. // from SSL internals. If the underlying socket is readable, assume an
  9268. // early response may be present.
  9269. auto sock = strm.socket();
  9270. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  9271. return false;
  9272. }
  9273. // Fallback to stream-level check for non-socket streams or when the
  9274. // socket isn't reporting readable. Avoid using `is_readable()` for
  9275. // SSL, since `SSL_pending()` may report buffered records that do not
  9276. // indicate a complete application-level response yet.
  9277. if (!is_ssl() && strm.is_readable()) { return false; }
  9278. auto now = std::chrono::high_resolution_clock::now();
  9279. auto elapsed =
  9280. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  9281. .count();
  9282. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  9283. break;
  9284. }
  9285. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  9286. }
  9287. }
  9288. #endif
  9289. // Body
  9290. if (skip_body) { return true; }
  9291. return write_request_body(strm, req, error);
  9292. }
  9293. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  9294. Error &error) {
  9295. if (req.body.empty()) {
  9296. return write_content_with_provider(strm, req, error);
  9297. }
  9298. if (req.upload_progress) {
  9299. auto body_size = req.body.size();
  9300. size_t written = 0;
  9301. auto data = req.body.data();
  9302. while (written < body_size) {
  9303. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  9304. if (!detail::write_data(strm, data + written, to_write)) {
  9305. error = Error::Write;
  9306. output_error_log(error, &req);
  9307. return false;
  9308. }
  9309. written += to_write;
  9310. if (!req.upload_progress(written, body_size)) {
  9311. error = Error::Canceled;
  9312. output_error_log(error, &req);
  9313. return false;
  9314. }
  9315. }
  9316. } else {
  9317. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  9318. error = Error::Write;
  9319. output_error_log(error, &req);
  9320. return false;
  9321. }
  9322. }
  9323. return true;
  9324. }
  9325. inline std::unique_ptr<Response>
  9326. ClientImpl::send_with_content_provider_and_receiver(
  9327. Request &req, const char *body, size_t content_length,
  9328. ContentProvider content_provider,
  9329. ContentProviderWithoutLength content_provider_without_length,
  9330. const std::string &content_type, ContentReceiver content_receiver,
  9331. Error &error) {
  9332. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9333. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9334. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  9335. #endif
  9336. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9337. if (compress_ && !content_provider_without_length) {
  9338. // TODO: Brotli support
  9339. detail::gzip_compressor compressor;
  9340. if (content_provider) {
  9341. auto ok = true;
  9342. size_t offset = 0;
  9343. DataSink data_sink;
  9344. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  9345. if (ok) {
  9346. auto last = offset + data_len == content_length;
  9347. auto ret = compressor.compress(
  9348. data, data_len, last,
  9349. [&](const char *compressed_data, size_t compressed_data_len) {
  9350. req.body.append(compressed_data, compressed_data_len);
  9351. return true;
  9352. });
  9353. if (ret) {
  9354. offset += data_len;
  9355. } else {
  9356. ok = false;
  9357. }
  9358. }
  9359. return ok;
  9360. };
  9361. while (ok && offset < content_length) {
  9362. if (!content_provider(offset, content_length - offset, data_sink)) {
  9363. error = Error::Canceled;
  9364. output_error_log(error, &req);
  9365. return nullptr;
  9366. }
  9367. }
  9368. } else {
  9369. if (!compressor.compress(body, content_length, true,
  9370. [&](const char *data, size_t data_len) {
  9371. req.body.append(data, data_len);
  9372. return true;
  9373. })) {
  9374. error = Error::Compression;
  9375. output_error_log(error, &req);
  9376. return nullptr;
  9377. }
  9378. }
  9379. } else
  9380. #endif
  9381. {
  9382. if (content_provider) {
  9383. req.content_length_ = content_length;
  9384. req.content_provider_ = std::move(content_provider);
  9385. req.is_chunked_content_provider_ = false;
  9386. } else if (content_provider_without_length) {
  9387. req.content_length_ = 0;
  9388. req.content_provider_ = detail::ContentProviderAdapter(
  9389. std::move(content_provider_without_length));
  9390. req.is_chunked_content_provider_ = true;
  9391. req.set_header("Transfer-Encoding", "chunked");
  9392. } else {
  9393. req.body.assign(body, content_length);
  9394. }
  9395. }
  9396. if (content_receiver) {
  9397. req.content_receiver =
  9398. [content_receiver](const char *data, size_t data_length,
  9399. size_t /*offset*/, size_t /*total_length*/) {
  9400. return content_receiver(data, data_length);
  9401. };
  9402. }
  9403. auto res = detail::make_unique<Response>();
  9404. return send(req, *res, error) ? std::move(res) : nullptr;
  9405. }
  9406. inline Result ClientImpl::send_with_content_provider_and_receiver(
  9407. const std::string &method, const std::string &path, const Headers &headers,
  9408. const char *body, size_t content_length, ContentProvider content_provider,
  9409. ContentProviderWithoutLength content_provider_without_length,
  9410. const std::string &content_type, ContentReceiver content_receiver,
  9411. UploadProgress progress) {
  9412. Request req;
  9413. req.method = method;
  9414. req.headers = headers;
  9415. req.path = path;
  9416. req.upload_progress = std::move(progress);
  9417. if (max_timeout_msec_ > 0) {
  9418. req.start_time_ = std::chrono::steady_clock::now();
  9419. }
  9420. auto error = Error::Success;
  9421. auto res = send_with_content_provider_and_receiver(
  9422. req, body, content_length, std::move(content_provider),
  9423. std::move(content_provider_without_length), content_type,
  9424. std::move(content_receiver), error);
  9425. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9426. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  9427. last_openssl_error_};
  9428. #else
  9429. return Result{std::move(res), error, std::move(req.headers)};
  9430. #endif
  9431. }
  9432. inline void ClientImpl::output_log(const Request &req,
  9433. const Response &res) const {
  9434. if (logger_) {
  9435. std::lock_guard<std::mutex> guard(logger_mutex_);
  9436. logger_(req, res);
  9437. }
  9438. }
  9439. inline void ClientImpl::output_error_log(const Error &err,
  9440. const Request *req) const {
  9441. if (error_logger_) {
  9442. std::lock_guard<std::mutex> guard(logger_mutex_);
  9443. error_logger_(err, req);
  9444. }
  9445. }
  9446. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  9447. Response &res, bool close_connection,
  9448. Error &error) {
  9449. // Auto-add Expect: 100-continue for large bodies
  9450. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  9451. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  9452. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  9453. req.set_header("Expect", "100-continue");
  9454. }
  9455. }
  9456. // Check for Expect: 100-continue
  9457. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  9458. // Send request (skip body if using Expect: 100-continue)
  9459. auto write_request_success =
  9460. write_request(strm, req, close_connection, error, expect_100_continue);
  9461. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9462. if (is_ssl()) {
  9463. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  9464. if (!is_proxy_enabled) {
  9465. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  9466. error = Error::SSLPeerCouldBeClosed_;
  9467. output_error_log(error, &req);
  9468. return false;
  9469. }
  9470. }
  9471. }
  9472. #endif
  9473. // Handle Expect: 100-continue with timeout
  9474. if (expect_100_continue && CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  9475. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  9476. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  9477. auto ret = detail::select_read(strm.socket(), sec, usec);
  9478. if (ret <= 0) {
  9479. // Timeout or error: send body anyway (server didn't respond in time)
  9480. if (!write_request_body(strm, req, error)) { return false; }
  9481. expect_100_continue = false; // Switch to normal response handling
  9482. }
  9483. }
  9484. // Receive response and headers
  9485. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  9486. if (!read_response_line(strm, req, res, !expect_100_continue) ||
  9487. !detail::read_headers(strm, res.headers)) {
  9488. if (write_request_success) { error = Error::Read; }
  9489. output_error_log(error, &req);
  9490. return false;
  9491. }
  9492. if (!write_request_success) { return false; }
  9493. // Handle Expect: 100-continue response
  9494. if (expect_100_continue) {
  9495. if (res.status == StatusCode::Continue_100) {
  9496. // Server accepted, send the body
  9497. if (!write_request_body(strm, req, error)) { return false; }
  9498. // Read the actual response
  9499. res.headers.clear();
  9500. res.body.clear();
  9501. if (!read_response_line(strm, req, res) ||
  9502. !detail::read_headers(strm, res.headers)) {
  9503. error = Error::Read;
  9504. output_error_log(error, &req);
  9505. return false;
  9506. }
  9507. }
  9508. // If not 100 Continue, server returned an error; proceed with that response
  9509. }
  9510. // Body
  9511. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  9512. req.method != "CONNECT") {
  9513. auto redirect = 300 < res.status && res.status < 400 &&
  9514. res.status != StatusCode::NotModified_304 &&
  9515. follow_location_;
  9516. if (req.response_handler && !redirect) {
  9517. if (!req.response_handler(res)) {
  9518. error = Error::Canceled;
  9519. output_error_log(error, &req);
  9520. return false;
  9521. }
  9522. }
  9523. auto out =
  9524. req.content_receiver
  9525. ? static_cast<ContentReceiverWithProgress>(
  9526. [&](const char *buf, size_t n, size_t off, size_t len) {
  9527. if (redirect) { return true; }
  9528. auto ret = req.content_receiver(buf, n, off, len);
  9529. if (!ret) {
  9530. error = Error::Canceled;
  9531. output_error_log(error, &req);
  9532. }
  9533. return ret;
  9534. })
  9535. : static_cast<ContentReceiverWithProgress>(
  9536. [&](const char *buf, size_t n, size_t /*off*/,
  9537. size_t /*len*/) {
  9538. assert(res.body.size() + n <= res.body.max_size());
  9539. res.body.append(buf, n);
  9540. return true;
  9541. });
  9542. auto progress = [&](size_t current, size_t total) {
  9543. if (!req.download_progress || redirect) { return true; }
  9544. auto ret = req.download_progress(current, total);
  9545. if (!ret) {
  9546. error = Error::Canceled;
  9547. output_error_log(error, &req);
  9548. }
  9549. return ret;
  9550. };
  9551. if (res.has_header("Content-Length")) {
  9552. if (!req.content_receiver) {
  9553. auto len = res.get_header_value_u64("Content-Length");
  9554. if (len > res.body.max_size()) {
  9555. error = Error::Read;
  9556. output_error_log(error, &req);
  9557. return false;
  9558. }
  9559. res.body.reserve(static_cast<size_t>(len));
  9560. }
  9561. }
  9562. if (res.status != StatusCode::NotModified_304) {
  9563. int dummy_status;
  9564. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  9565. dummy_status, std::move(progress),
  9566. std::move(out), decompress_)) {
  9567. if (error != Error::Canceled) { error = Error::Read; }
  9568. output_error_log(error, &req);
  9569. return false;
  9570. }
  9571. }
  9572. }
  9573. // Log
  9574. output_log(req, res);
  9575. return true;
  9576. }
  9577. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  9578. const std::string &boundary, const UploadFormDataItems &items,
  9579. const FormDataProviderItems &provider_items) const {
  9580. size_t cur_item = 0;
  9581. size_t cur_start = 0;
  9582. // cur_item and cur_start are copied to within the std::function and
  9583. // maintain state between successive calls
  9584. return [&, cur_item, cur_start](size_t offset,
  9585. DataSink &sink) mutable -> bool {
  9586. if (!offset && !items.empty()) {
  9587. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  9588. return true;
  9589. } else if (cur_item < provider_items.size()) {
  9590. if (!cur_start) {
  9591. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  9592. provider_items[cur_item], boundary);
  9593. offset += begin.size();
  9594. cur_start = offset;
  9595. sink.os << begin;
  9596. }
  9597. DataSink cur_sink;
  9598. auto has_data = true;
  9599. cur_sink.write = sink.write;
  9600. cur_sink.done = [&]() { has_data = false; };
  9601. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  9602. return false;
  9603. }
  9604. if (!has_data) {
  9605. sink.os << detail::serialize_multipart_formdata_item_end();
  9606. cur_item++;
  9607. cur_start = 0;
  9608. }
  9609. return true;
  9610. } else {
  9611. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  9612. sink.done();
  9613. return true;
  9614. }
  9615. };
  9616. }
  9617. inline bool ClientImpl::process_socket(
  9618. const Socket &socket,
  9619. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9620. std::function<bool(Stream &strm)> callback) {
  9621. return detail::process_client_socket(
  9622. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9623. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  9624. }
  9625. inline bool ClientImpl::is_ssl() const { return false; }
  9626. inline Result ClientImpl::Get(const std::string &path,
  9627. DownloadProgress progress) {
  9628. return Get(path, Headers(), std::move(progress));
  9629. }
  9630. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9631. const Headers &headers,
  9632. DownloadProgress progress) {
  9633. if (params.empty()) { return Get(path, headers); }
  9634. std::string path_with_query = append_query_params(path, params);
  9635. return Get(path_with_query, headers, std::move(progress));
  9636. }
  9637. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9638. DownloadProgress progress) {
  9639. Request req;
  9640. req.method = "GET";
  9641. req.path = path;
  9642. req.headers = headers;
  9643. req.download_progress = std::move(progress);
  9644. if (max_timeout_msec_ > 0) {
  9645. req.start_time_ = std::chrono::steady_clock::now();
  9646. }
  9647. return send_(std::move(req));
  9648. }
  9649. inline Result ClientImpl::Get(const std::string &path,
  9650. ContentReceiver content_receiver,
  9651. DownloadProgress progress) {
  9652. return Get(path, Headers(), nullptr, std::move(content_receiver),
  9653. std::move(progress));
  9654. }
  9655. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9656. ContentReceiver content_receiver,
  9657. DownloadProgress progress) {
  9658. return Get(path, headers, nullptr, std::move(content_receiver),
  9659. std::move(progress));
  9660. }
  9661. inline Result ClientImpl::Get(const std::string &path,
  9662. ResponseHandler response_handler,
  9663. ContentReceiver content_receiver,
  9664. DownloadProgress progress) {
  9665. return Get(path, Headers(), std::move(response_handler),
  9666. std::move(content_receiver), std::move(progress));
  9667. }
  9668. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9669. ResponseHandler response_handler,
  9670. ContentReceiver content_receiver,
  9671. DownloadProgress progress) {
  9672. Request req;
  9673. req.method = "GET";
  9674. req.path = path;
  9675. req.headers = headers;
  9676. req.response_handler = std::move(response_handler);
  9677. req.content_receiver =
  9678. [content_receiver](const char *data, size_t data_length,
  9679. size_t /*offset*/, size_t /*total_length*/) {
  9680. return content_receiver(data, data_length);
  9681. };
  9682. req.download_progress = std::move(progress);
  9683. if (max_timeout_msec_ > 0) {
  9684. req.start_time_ = std::chrono::steady_clock::now();
  9685. }
  9686. return send_(std::move(req));
  9687. }
  9688. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9689. const Headers &headers,
  9690. ContentReceiver content_receiver,
  9691. DownloadProgress progress) {
  9692. return Get(path, params, headers, nullptr, std::move(content_receiver),
  9693. std::move(progress));
  9694. }
  9695. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9696. const Headers &headers,
  9697. ResponseHandler response_handler,
  9698. ContentReceiver content_receiver,
  9699. DownloadProgress progress) {
  9700. if (params.empty()) {
  9701. return Get(path, headers, std::move(response_handler),
  9702. std::move(content_receiver), std::move(progress));
  9703. }
  9704. std::string path_with_query = append_query_params(path, params);
  9705. return Get(path_with_query, headers, std::move(response_handler),
  9706. std::move(content_receiver), std::move(progress));
  9707. }
  9708. inline Result ClientImpl::Head(const std::string &path) {
  9709. return Head(path, Headers());
  9710. }
  9711. inline Result ClientImpl::Head(const std::string &path,
  9712. const Headers &headers) {
  9713. Request req;
  9714. req.method = "HEAD";
  9715. req.headers = headers;
  9716. req.path = path;
  9717. if (max_timeout_msec_ > 0) {
  9718. req.start_time_ = std::chrono::steady_clock::now();
  9719. }
  9720. return send_(std::move(req));
  9721. }
  9722. inline Result ClientImpl::Post(const std::string &path) {
  9723. return Post(path, std::string(), std::string());
  9724. }
  9725. inline Result ClientImpl::Post(const std::string &path,
  9726. const Headers &headers) {
  9727. return Post(path, headers, nullptr, 0, std::string());
  9728. }
  9729. inline Result ClientImpl::Post(const std::string &path, const char *body,
  9730. size_t content_length,
  9731. const std::string &content_type,
  9732. UploadProgress progress) {
  9733. return Post(path, Headers(), body, content_length, content_type, progress);
  9734. }
  9735. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  9736. const std::string &content_type,
  9737. UploadProgress progress) {
  9738. return Post(path, Headers(), body, content_type, progress);
  9739. }
  9740. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  9741. return Post(path, Headers(), params);
  9742. }
  9743. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9744. ContentProvider content_provider,
  9745. const std::string &content_type,
  9746. UploadProgress progress) {
  9747. return Post(path, Headers(), content_length, std::move(content_provider),
  9748. content_type, progress);
  9749. }
  9750. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9751. ContentProvider content_provider,
  9752. const std::string &content_type,
  9753. ContentReceiver content_receiver,
  9754. UploadProgress progress) {
  9755. return Post(path, Headers(), content_length, std::move(content_provider),
  9756. content_type, std::move(content_receiver), progress);
  9757. }
  9758. inline Result ClientImpl::Post(const std::string &path,
  9759. ContentProviderWithoutLength content_provider,
  9760. const std::string &content_type,
  9761. UploadProgress progress) {
  9762. return Post(path, Headers(), std::move(content_provider), content_type,
  9763. progress);
  9764. }
  9765. inline Result ClientImpl::Post(const std::string &path,
  9766. ContentProviderWithoutLength content_provider,
  9767. const std::string &content_type,
  9768. ContentReceiver content_receiver,
  9769. UploadProgress progress) {
  9770. return Post(path, Headers(), std::move(content_provider), content_type,
  9771. std::move(content_receiver), progress);
  9772. }
  9773. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9774. const Params &params) {
  9775. auto query = detail::params_to_query_str(params);
  9776. return Post(path, headers, query, "application/x-www-form-urlencoded");
  9777. }
  9778. inline Result ClientImpl::Post(const std::string &path,
  9779. const UploadFormDataItems &items,
  9780. UploadProgress progress) {
  9781. return Post(path, Headers(), items, progress);
  9782. }
  9783. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9784. const UploadFormDataItems &items,
  9785. UploadProgress progress) {
  9786. const auto &boundary = detail::make_multipart_data_boundary();
  9787. const auto &content_type =
  9788. detail::serialize_multipart_formdata_get_content_type(boundary);
  9789. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9790. return Post(path, headers, body, content_type, progress);
  9791. }
  9792. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9793. const UploadFormDataItems &items,
  9794. const std::string &boundary,
  9795. UploadProgress progress) {
  9796. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  9797. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  9798. }
  9799. const auto &content_type =
  9800. detail::serialize_multipart_formdata_get_content_type(boundary);
  9801. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9802. return Post(path, headers, body, content_type, progress);
  9803. }
  9804. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9805. const char *body, size_t content_length,
  9806. const std::string &content_type,
  9807. UploadProgress progress) {
  9808. return send_with_content_provider_and_receiver(
  9809. "POST", path, headers, body, content_length, nullptr, nullptr,
  9810. content_type, nullptr, progress);
  9811. }
  9812. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9813. const std::string &body,
  9814. const std::string &content_type,
  9815. UploadProgress progress) {
  9816. return send_with_content_provider_and_receiver(
  9817. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  9818. content_type, nullptr, progress);
  9819. }
  9820. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9821. size_t content_length,
  9822. ContentProvider content_provider,
  9823. const std::string &content_type,
  9824. UploadProgress progress) {
  9825. return send_with_content_provider_and_receiver(
  9826. "POST", path, headers, nullptr, content_length,
  9827. std::move(content_provider), nullptr, content_type, nullptr, progress);
  9828. }
  9829. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9830. size_t content_length,
  9831. ContentProvider content_provider,
  9832. const std::string &content_type,
  9833. ContentReceiver content_receiver,
  9834. DownloadProgress progress) {
  9835. return send_with_content_provider_and_receiver(
  9836. "POST", path, headers, nullptr, content_length,
  9837. std::move(content_provider), nullptr, content_type,
  9838. std::move(content_receiver), std::move(progress));
  9839. }
  9840. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9841. ContentProviderWithoutLength content_provider,
  9842. const std::string &content_type,
  9843. UploadProgress progress) {
  9844. return send_with_content_provider_and_receiver(
  9845. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  9846. content_type, nullptr, progress);
  9847. }
  9848. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9849. ContentProviderWithoutLength content_provider,
  9850. const std::string &content_type,
  9851. ContentReceiver content_receiver,
  9852. DownloadProgress progress) {
  9853. return send_with_content_provider_and_receiver(
  9854. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  9855. content_type, std::move(content_receiver), std::move(progress));
  9856. }
  9857. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9858. const UploadFormDataItems &items,
  9859. const FormDataProviderItems &provider_items,
  9860. UploadProgress progress) {
  9861. const auto &boundary = detail::make_multipart_data_boundary();
  9862. const auto &content_type =
  9863. detail::serialize_multipart_formdata_get_content_type(boundary);
  9864. return send_with_content_provider_and_receiver(
  9865. "POST", path, headers, nullptr, 0, nullptr,
  9866. get_multipart_content_provider(boundary, items, provider_items),
  9867. content_type, nullptr, progress);
  9868. }
  9869. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9870. const std::string &body,
  9871. const std::string &content_type,
  9872. ContentReceiver content_receiver,
  9873. DownloadProgress progress) {
  9874. Request req;
  9875. req.method = "POST";
  9876. req.path = path;
  9877. req.headers = headers;
  9878. req.body = body;
  9879. req.content_receiver =
  9880. [content_receiver](const char *data, size_t data_length,
  9881. size_t /*offset*/, size_t /*total_length*/) {
  9882. return content_receiver(data, data_length);
  9883. };
  9884. req.download_progress = std::move(progress);
  9885. if (max_timeout_msec_ > 0) {
  9886. req.start_time_ = std::chrono::steady_clock::now();
  9887. }
  9888. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9889. return send_(std::move(req));
  9890. }
  9891. inline Result ClientImpl::Put(const std::string &path) {
  9892. return Put(path, std::string(), std::string());
  9893. }
  9894. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  9895. return Put(path, headers, nullptr, 0, std::string());
  9896. }
  9897. inline Result ClientImpl::Put(const std::string &path, const char *body,
  9898. size_t content_length,
  9899. const std::string &content_type,
  9900. UploadProgress progress) {
  9901. return Put(path, Headers(), body, content_length, content_type, progress);
  9902. }
  9903. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  9904. const std::string &content_type,
  9905. UploadProgress progress) {
  9906. return Put(path, Headers(), body, content_type, progress);
  9907. }
  9908. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  9909. return Put(path, Headers(), params);
  9910. }
  9911. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  9912. ContentProvider content_provider,
  9913. const std::string &content_type,
  9914. UploadProgress progress) {
  9915. return Put(path, Headers(), content_length, std::move(content_provider),
  9916. content_type, progress);
  9917. }
  9918. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  9919. ContentProvider content_provider,
  9920. const std::string &content_type,
  9921. ContentReceiver content_receiver,
  9922. UploadProgress progress) {
  9923. return Put(path, Headers(), content_length, std::move(content_provider),
  9924. content_type, std::move(content_receiver), progress);
  9925. }
  9926. inline Result ClientImpl::Put(const std::string &path,
  9927. ContentProviderWithoutLength content_provider,
  9928. const std::string &content_type,
  9929. UploadProgress progress) {
  9930. return Put(path, Headers(), std::move(content_provider), content_type,
  9931. progress);
  9932. }
  9933. inline Result ClientImpl::Put(const std::string &path,
  9934. ContentProviderWithoutLength content_provider,
  9935. const std::string &content_type,
  9936. ContentReceiver content_receiver,
  9937. UploadProgress progress) {
  9938. return Put(path, Headers(), std::move(content_provider), content_type,
  9939. std::move(content_receiver), progress);
  9940. }
  9941. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9942. const Params &params) {
  9943. auto query = detail::params_to_query_str(params);
  9944. return Put(path, headers, query, "application/x-www-form-urlencoded");
  9945. }
  9946. inline Result ClientImpl::Put(const std::string &path,
  9947. const UploadFormDataItems &items,
  9948. UploadProgress progress) {
  9949. return Put(path, Headers(), items, progress);
  9950. }
  9951. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9952. const UploadFormDataItems &items,
  9953. UploadProgress progress) {
  9954. const auto &boundary = detail::make_multipart_data_boundary();
  9955. const auto &content_type =
  9956. detail::serialize_multipart_formdata_get_content_type(boundary);
  9957. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9958. return Put(path, headers, body, content_type, progress);
  9959. }
  9960. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9961. const UploadFormDataItems &items,
  9962. const std::string &boundary,
  9963. UploadProgress progress) {
  9964. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  9965. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  9966. }
  9967. const auto &content_type =
  9968. detail::serialize_multipart_formdata_get_content_type(boundary);
  9969. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9970. return Put(path, headers, body, content_type, progress);
  9971. }
  9972. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9973. const char *body, size_t content_length,
  9974. const std::string &content_type,
  9975. UploadProgress progress) {
  9976. return send_with_content_provider_and_receiver(
  9977. "PUT", path, headers, body, content_length, nullptr, nullptr,
  9978. content_type, nullptr, progress);
  9979. }
  9980. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9981. const std::string &body,
  9982. const std::string &content_type,
  9983. UploadProgress progress) {
  9984. return send_with_content_provider_and_receiver(
  9985. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  9986. content_type, nullptr, progress);
  9987. }
  9988. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9989. size_t content_length,
  9990. ContentProvider content_provider,
  9991. const std::string &content_type,
  9992. UploadProgress progress) {
  9993. return send_with_content_provider_and_receiver(
  9994. "PUT", path, headers, nullptr, content_length,
  9995. std::move(content_provider), nullptr, content_type, nullptr, progress);
  9996. }
  9997. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9998. size_t content_length,
  9999. ContentProvider content_provider,
  10000. const std::string &content_type,
  10001. ContentReceiver content_receiver,
  10002. UploadProgress progress) {
  10003. return send_with_content_provider_and_receiver(
  10004. "PUT", path, headers, nullptr, content_length,
  10005. std::move(content_provider), nullptr, content_type,
  10006. std::move(content_receiver), progress);
  10007. }
  10008. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10009. ContentProviderWithoutLength content_provider,
  10010. const std::string &content_type,
  10011. UploadProgress progress) {
  10012. return send_with_content_provider_and_receiver(
  10013. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10014. content_type, nullptr, progress);
  10015. }
  10016. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10017. ContentProviderWithoutLength content_provider,
  10018. const std::string &content_type,
  10019. ContentReceiver content_receiver,
  10020. UploadProgress progress) {
  10021. return send_with_content_provider_and_receiver(
  10022. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10023. content_type, std::move(content_receiver), progress);
  10024. }
  10025. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10026. const UploadFormDataItems &items,
  10027. const FormDataProviderItems &provider_items,
  10028. UploadProgress progress) {
  10029. const auto &boundary = detail::make_multipart_data_boundary();
  10030. const auto &content_type =
  10031. detail::serialize_multipart_formdata_get_content_type(boundary);
  10032. return send_with_content_provider_and_receiver(
  10033. "PUT", path, headers, nullptr, 0, nullptr,
  10034. get_multipart_content_provider(boundary, items, provider_items),
  10035. content_type, nullptr, progress);
  10036. }
  10037. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  10038. const std::string &body,
  10039. const std::string &content_type,
  10040. ContentReceiver content_receiver,
  10041. DownloadProgress progress) {
  10042. Request req;
  10043. req.method = "PUT";
  10044. req.path = path;
  10045. req.headers = headers;
  10046. req.body = body;
  10047. req.content_receiver =
  10048. [content_receiver](const char *data, size_t data_length,
  10049. size_t /*offset*/, size_t /*total_length*/) {
  10050. return content_receiver(data, data_length);
  10051. };
  10052. req.download_progress = std::move(progress);
  10053. if (max_timeout_msec_ > 0) {
  10054. req.start_time_ = std::chrono::steady_clock::now();
  10055. }
  10056. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10057. return send_(std::move(req));
  10058. }
  10059. inline Result ClientImpl::Patch(const std::string &path) {
  10060. return Patch(path, std::string(), std::string());
  10061. }
  10062. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10063. UploadProgress progress) {
  10064. return Patch(path, headers, nullptr, 0, std::string(), progress);
  10065. }
  10066. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  10067. size_t content_length,
  10068. const std::string &content_type,
  10069. UploadProgress progress) {
  10070. return Patch(path, Headers(), body, content_length, content_type, progress);
  10071. }
  10072. inline Result ClientImpl::Patch(const std::string &path,
  10073. const std::string &body,
  10074. const std::string &content_type,
  10075. UploadProgress progress) {
  10076. return Patch(path, Headers(), body, content_type, progress);
  10077. }
  10078. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  10079. return Patch(path, Headers(), params);
  10080. }
  10081. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10082. ContentProvider content_provider,
  10083. const std::string &content_type,
  10084. UploadProgress progress) {
  10085. return Patch(path, Headers(), content_length, std::move(content_provider),
  10086. content_type, progress);
  10087. }
  10088. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10089. ContentProvider content_provider,
  10090. const std::string &content_type,
  10091. ContentReceiver content_receiver,
  10092. UploadProgress progress) {
  10093. return Patch(path, Headers(), content_length, std::move(content_provider),
  10094. content_type, std::move(content_receiver), progress);
  10095. }
  10096. inline Result ClientImpl::Patch(const std::string &path,
  10097. ContentProviderWithoutLength content_provider,
  10098. const std::string &content_type,
  10099. UploadProgress progress) {
  10100. return Patch(path, Headers(), std::move(content_provider), content_type,
  10101. progress);
  10102. }
  10103. inline Result ClientImpl::Patch(const std::string &path,
  10104. ContentProviderWithoutLength content_provider,
  10105. const std::string &content_type,
  10106. ContentReceiver content_receiver,
  10107. UploadProgress progress) {
  10108. return Patch(path, Headers(), std::move(content_provider), content_type,
  10109. std::move(content_receiver), progress);
  10110. }
  10111. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10112. const Params &params) {
  10113. auto query = detail::params_to_query_str(params);
  10114. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  10115. }
  10116. inline Result ClientImpl::Patch(const std::string &path,
  10117. const UploadFormDataItems &items,
  10118. UploadProgress progress) {
  10119. return Patch(path, Headers(), items, progress);
  10120. }
  10121. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10122. const UploadFormDataItems &items,
  10123. UploadProgress progress) {
  10124. const auto &boundary = detail::make_multipart_data_boundary();
  10125. const auto &content_type =
  10126. detail::serialize_multipart_formdata_get_content_type(boundary);
  10127. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10128. return Patch(path, headers, body, content_type, progress);
  10129. }
  10130. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10131. const UploadFormDataItems &items,
  10132. const std::string &boundary,
  10133. UploadProgress progress) {
  10134. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10135. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10136. }
  10137. const auto &content_type =
  10138. detail::serialize_multipart_formdata_get_content_type(boundary);
  10139. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10140. return Patch(path, headers, body, content_type, progress);
  10141. }
  10142. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10143. const char *body, size_t content_length,
  10144. const std::string &content_type,
  10145. UploadProgress progress) {
  10146. return send_with_content_provider_and_receiver(
  10147. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  10148. content_type, nullptr, progress);
  10149. }
  10150. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10151. const std::string &body,
  10152. const std::string &content_type,
  10153. UploadProgress progress) {
  10154. return send_with_content_provider_and_receiver(
  10155. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  10156. content_type, nullptr, progress);
  10157. }
  10158. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10159. size_t content_length,
  10160. ContentProvider content_provider,
  10161. const std::string &content_type,
  10162. UploadProgress progress) {
  10163. return send_with_content_provider_and_receiver(
  10164. "PATCH", path, headers, nullptr, content_length,
  10165. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10166. }
  10167. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10168. size_t content_length,
  10169. ContentProvider content_provider,
  10170. const std::string &content_type,
  10171. ContentReceiver content_receiver,
  10172. UploadProgress progress) {
  10173. return send_with_content_provider_and_receiver(
  10174. "PATCH", path, headers, nullptr, content_length,
  10175. std::move(content_provider), nullptr, content_type,
  10176. std::move(content_receiver), progress);
  10177. }
  10178. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10179. ContentProviderWithoutLength content_provider,
  10180. const std::string &content_type,
  10181. UploadProgress progress) {
  10182. return send_with_content_provider_and_receiver(
  10183. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10184. content_type, nullptr, progress);
  10185. }
  10186. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10187. ContentProviderWithoutLength content_provider,
  10188. const std::string &content_type,
  10189. ContentReceiver content_receiver,
  10190. UploadProgress progress) {
  10191. return send_with_content_provider_and_receiver(
  10192. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10193. content_type, std::move(content_receiver), progress);
  10194. }
  10195. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10196. const UploadFormDataItems &items,
  10197. const FormDataProviderItems &provider_items,
  10198. UploadProgress progress) {
  10199. const auto &boundary = detail::make_multipart_data_boundary();
  10200. const auto &content_type =
  10201. detail::serialize_multipart_formdata_get_content_type(boundary);
  10202. return send_with_content_provider_and_receiver(
  10203. "PATCH", path, headers, nullptr, 0, nullptr,
  10204. get_multipart_content_provider(boundary, items, provider_items),
  10205. content_type, nullptr, progress);
  10206. }
  10207. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10208. const std::string &body,
  10209. const std::string &content_type,
  10210. ContentReceiver content_receiver,
  10211. DownloadProgress progress) {
  10212. Request req;
  10213. req.method = "PATCH";
  10214. req.path = path;
  10215. req.headers = headers;
  10216. req.body = body;
  10217. req.content_receiver =
  10218. [content_receiver](const char *data, size_t data_length,
  10219. size_t /*offset*/, size_t /*total_length*/) {
  10220. return content_receiver(data, data_length);
  10221. };
  10222. req.download_progress = std::move(progress);
  10223. if (max_timeout_msec_ > 0) {
  10224. req.start_time_ = std::chrono::steady_clock::now();
  10225. }
  10226. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10227. return send_(std::move(req));
  10228. }
  10229. inline Result ClientImpl::Delete(const std::string &path,
  10230. DownloadProgress progress) {
  10231. return Delete(path, Headers(), std::string(), std::string(), progress);
  10232. }
  10233. inline Result ClientImpl::Delete(const std::string &path,
  10234. const Headers &headers,
  10235. DownloadProgress progress) {
  10236. return Delete(path, headers, std::string(), std::string(), progress);
  10237. }
  10238. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  10239. size_t content_length,
  10240. const std::string &content_type,
  10241. DownloadProgress progress) {
  10242. return Delete(path, Headers(), body, content_length, content_type, progress);
  10243. }
  10244. inline Result ClientImpl::Delete(const std::string &path,
  10245. const std::string &body,
  10246. const std::string &content_type,
  10247. DownloadProgress progress) {
  10248. return Delete(path, Headers(), body.data(), body.size(), content_type,
  10249. progress);
  10250. }
  10251. inline Result ClientImpl::Delete(const std::string &path,
  10252. const Headers &headers,
  10253. const std::string &body,
  10254. const std::string &content_type,
  10255. DownloadProgress progress) {
  10256. return Delete(path, headers, body.data(), body.size(), content_type,
  10257. progress);
  10258. }
  10259. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  10260. DownloadProgress progress) {
  10261. return Delete(path, Headers(), params, progress);
  10262. }
  10263. inline Result ClientImpl::Delete(const std::string &path,
  10264. const Headers &headers, const Params &params,
  10265. DownloadProgress progress) {
  10266. auto query = detail::params_to_query_str(params);
  10267. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  10268. progress);
  10269. }
  10270. inline Result ClientImpl::Delete(const std::string &path,
  10271. const Headers &headers, const char *body,
  10272. size_t content_length,
  10273. const std::string &content_type,
  10274. DownloadProgress progress) {
  10275. Request req;
  10276. req.method = "DELETE";
  10277. req.headers = headers;
  10278. req.path = path;
  10279. req.download_progress = std::move(progress);
  10280. if (max_timeout_msec_ > 0) {
  10281. req.start_time_ = std::chrono::steady_clock::now();
  10282. }
  10283. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10284. req.body.assign(body, content_length);
  10285. return send_(std::move(req));
  10286. }
  10287. inline Result ClientImpl::Options(const std::string &path) {
  10288. return Options(path, Headers());
  10289. }
  10290. inline Result ClientImpl::Options(const std::string &path,
  10291. const Headers &headers) {
  10292. Request req;
  10293. req.method = "OPTIONS";
  10294. req.headers = headers;
  10295. req.path = path;
  10296. if (max_timeout_msec_ > 0) {
  10297. req.start_time_ = std::chrono::steady_clock::now();
  10298. }
  10299. return send_(std::move(req));
  10300. }
  10301. inline void ClientImpl::stop() {
  10302. std::lock_guard<std::mutex> guard(socket_mutex_);
  10303. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  10304. // do is to shutdown_socket, so that threads using this socket suddenly
  10305. // discover they can't read/write any more and error out. Everything else
  10306. // (closing the socket, shutting ssl down) is unsafe because these actions
  10307. // are not thread-safe.
  10308. if (socket_requests_in_flight_ > 0) {
  10309. shutdown_socket(socket_);
  10310. // Aside from that, we set a flag for the socket to be closed when we're
  10311. // done.
  10312. socket_should_be_closed_when_request_is_done_ = true;
  10313. return;
  10314. }
  10315. // Otherwise, still holding the mutex, we can shut everything down ourselves
  10316. shutdown_ssl(socket_, true);
  10317. shutdown_socket(socket_);
  10318. close_socket(socket_);
  10319. }
  10320. inline std::string ClientImpl::host() const { return host_; }
  10321. inline int ClientImpl::port() const { return port_; }
  10322. inline size_t ClientImpl::is_socket_open() const {
  10323. std::lock_guard<std::mutex> guard(socket_mutex_);
  10324. return socket_.is_open();
  10325. }
  10326. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  10327. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  10328. connection_timeout_sec_ = sec;
  10329. connection_timeout_usec_ = usec;
  10330. }
  10331. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  10332. read_timeout_sec_ = sec;
  10333. read_timeout_usec_ = usec;
  10334. }
  10335. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  10336. write_timeout_sec_ = sec;
  10337. write_timeout_usec_ = usec;
  10338. }
  10339. inline void ClientImpl::set_max_timeout(time_t msec) {
  10340. max_timeout_msec_ = msec;
  10341. }
  10342. inline void ClientImpl::set_basic_auth(const std::string &username,
  10343. const std::string &password) {
  10344. basic_auth_username_ = username;
  10345. basic_auth_password_ = password;
  10346. }
  10347. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  10348. bearer_token_auth_token_ = token;
  10349. }
  10350. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10351. inline void ClientImpl::set_digest_auth(const std::string &username,
  10352. const std::string &password) {
  10353. digest_auth_username_ = username;
  10354. digest_auth_password_ = password;
  10355. }
  10356. #endif
  10357. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  10358. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  10359. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  10360. inline void
  10361. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  10362. addr_map_ = std::move(addr_map);
  10363. }
  10364. inline void ClientImpl::set_default_headers(Headers headers) {
  10365. default_headers_ = std::move(headers);
  10366. }
  10367. inline void ClientImpl::set_header_writer(
  10368. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  10369. header_writer_ = writer;
  10370. }
  10371. inline void ClientImpl::set_address_family(int family) {
  10372. address_family_ = family;
  10373. }
  10374. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  10375. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  10376. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  10377. socket_options_ = std::move(socket_options);
  10378. }
  10379. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  10380. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  10381. inline void ClientImpl::set_interface(const std::string &intf) {
  10382. interface_ = intf;
  10383. }
  10384. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  10385. proxy_host_ = host;
  10386. proxy_port_ = port;
  10387. }
  10388. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  10389. const std::string &password) {
  10390. proxy_basic_auth_username_ = username;
  10391. proxy_basic_auth_password_ = password;
  10392. }
  10393. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  10394. proxy_bearer_token_auth_token_ = token;
  10395. }
  10396. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10397. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  10398. const std::string &password) {
  10399. proxy_digest_auth_username_ = username;
  10400. proxy_digest_auth_password_ = password;
  10401. }
  10402. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  10403. const std::string &ca_cert_dir_path) {
  10404. ca_cert_file_path_ = ca_cert_file_path;
  10405. ca_cert_dir_path_ = ca_cert_dir_path;
  10406. }
  10407. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  10408. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  10409. ca_cert_store_ = ca_cert_store;
  10410. }
  10411. }
  10412. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  10413. std::size_t size) const {
  10414. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  10415. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  10416. if (!mem) { return nullptr; }
  10417. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  10418. if (!inf) { return nullptr; }
  10419. auto cts = X509_STORE_new();
  10420. if (cts) {
  10421. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  10422. auto itmp = sk_X509_INFO_value(inf, i);
  10423. if (!itmp) { continue; }
  10424. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  10425. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  10426. }
  10427. }
  10428. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  10429. return cts;
  10430. }
  10431. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  10432. server_certificate_verification_ = enabled;
  10433. }
  10434. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  10435. server_hostname_verification_ = enabled;
  10436. }
  10437. inline void ClientImpl::set_server_certificate_verifier(
  10438. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  10439. server_certificate_verifier_ = verifier;
  10440. }
  10441. #endif
  10442. inline void ClientImpl::set_logger(Logger logger) {
  10443. logger_ = std::move(logger);
  10444. }
  10445. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  10446. error_logger_ = std::move(error_logger);
  10447. }
  10448. /*
  10449. * SSL Implementation
  10450. */
  10451. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10452. namespace detail {
  10453. inline bool is_ip_address(const std::string &host) {
  10454. struct in_addr addr4;
  10455. struct in6_addr addr6;
  10456. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  10457. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  10458. }
  10459. template <typename U, typename V>
  10460. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  10461. U SSL_connect_or_accept, V setup) {
  10462. SSL *ssl = nullptr;
  10463. {
  10464. std::lock_guard<std::mutex> guard(ctx_mutex);
  10465. ssl = SSL_new(ctx);
  10466. }
  10467. if (ssl) {
  10468. set_nonblocking(sock, true);
  10469. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  10470. BIO_set_nbio(bio, 1);
  10471. SSL_set_bio(ssl, bio, bio);
  10472. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  10473. SSL_shutdown(ssl);
  10474. {
  10475. std::lock_guard<std::mutex> guard(ctx_mutex);
  10476. SSL_free(ssl);
  10477. }
  10478. set_nonblocking(sock, false);
  10479. return nullptr;
  10480. }
  10481. BIO_set_nbio(bio, 0);
  10482. set_nonblocking(sock, false);
  10483. }
  10484. return ssl;
  10485. }
  10486. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock,
  10487. bool shutdown_gracefully) {
  10488. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  10489. // the remote has closed the network connection
  10490. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  10491. // best-efforts.
  10492. if (shutdown_gracefully) {
  10493. (void)(sock);
  10494. // SSL_shutdown() returns 0 on first call (indicating close_notify alert
  10495. // sent) and 1 on subsequent call (indicating close_notify alert received)
  10496. if (SSL_shutdown(ssl) == 0) {
  10497. // Expected to return 1, but even if it doesn't, we free ssl
  10498. SSL_shutdown(ssl);
  10499. }
  10500. }
  10501. std::lock_guard<std::mutex> guard(ctx_mutex);
  10502. SSL_free(ssl);
  10503. }
  10504. template <typename U>
  10505. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  10506. U ssl_connect_or_accept,
  10507. time_t timeout_sec, time_t timeout_usec,
  10508. int *ssl_error) {
  10509. auto res = 0;
  10510. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  10511. auto err = SSL_get_error(ssl, res);
  10512. switch (err) {
  10513. case SSL_ERROR_WANT_READ:
  10514. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  10515. break;
  10516. case SSL_ERROR_WANT_WRITE:
  10517. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  10518. break;
  10519. default: break;
  10520. }
  10521. if (ssl_error) { *ssl_error = err; }
  10522. return false;
  10523. }
  10524. return true;
  10525. }
  10526. template <typename T>
  10527. inline bool process_server_socket_ssl(
  10528. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  10529. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  10530. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  10531. time_t write_timeout_usec, T callback) {
  10532. return process_server_socket_core(
  10533. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  10534. [&](bool close_connection, bool &connection_closed) {
  10535. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  10536. write_timeout_sec, write_timeout_usec);
  10537. return callback(strm, close_connection, connection_closed);
  10538. });
  10539. }
  10540. template <typename T>
  10541. inline bool process_client_socket_ssl(
  10542. SSL *ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  10543. time_t write_timeout_sec, time_t write_timeout_usec,
  10544. time_t max_timeout_msec,
  10545. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  10546. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  10547. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  10548. start_time);
  10549. return callback(strm);
  10550. }
  10551. // SSL socket stream implementation
  10552. inline SSLSocketStream::SSLSocketStream(
  10553. socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec,
  10554. time_t write_timeout_sec, time_t write_timeout_usec,
  10555. time_t max_timeout_msec,
  10556. std::chrono::time_point<std::chrono::steady_clock> start_time)
  10557. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  10558. read_timeout_usec_(read_timeout_usec),
  10559. write_timeout_sec_(write_timeout_sec),
  10560. write_timeout_usec_(write_timeout_usec),
  10561. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  10562. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  10563. }
  10564. inline SSLSocketStream::~SSLSocketStream() = default;
  10565. inline bool SSLSocketStream::is_readable() const {
  10566. return SSL_pending(ssl_) > 0;
  10567. }
  10568. inline bool SSLSocketStream::wait_readable() const {
  10569. if (max_timeout_msec_ <= 0) {
  10570. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10571. }
  10572. time_t read_timeout_sec;
  10573. time_t read_timeout_usec;
  10574. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  10575. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  10576. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  10577. }
  10578. inline bool SSLSocketStream::wait_writable() const {
  10579. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  10580. is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_);
  10581. }
  10582. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  10583. if (SSL_pending(ssl_) > 0) {
  10584. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  10585. if (ret == 0) { error_ = Error::ConnectionClosed; }
  10586. return ret;
  10587. } else if (wait_readable()) {
  10588. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  10589. if (ret < 0) {
  10590. auto err = SSL_get_error(ssl_, ret);
  10591. auto n = 1000;
  10592. #ifdef _WIN32
  10593. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  10594. (err == SSL_ERROR_SYSCALL &&
  10595. WSAGetLastError() == WSAETIMEDOUT))) {
  10596. #else
  10597. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  10598. #endif
  10599. if (SSL_pending(ssl_) > 0) {
  10600. return SSL_read(ssl_, ptr, static_cast<int>(size));
  10601. } else if (wait_readable()) {
  10602. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10603. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  10604. if (ret >= 0) { return ret; }
  10605. err = SSL_get_error(ssl_, ret);
  10606. } else {
  10607. break;
  10608. }
  10609. }
  10610. assert(ret < 0);
  10611. } else if (ret == 0) {
  10612. error_ = Error::ConnectionClosed;
  10613. }
  10614. return ret;
  10615. } else {
  10616. error_ = Error::Timeout;
  10617. return -1;
  10618. }
  10619. }
  10620. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  10621. if (wait_writable()) {
  10622. auto handle_size = static_cast<int>(
  10623. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  10624. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  10625. if (ret < 0) {
  10626. auto err = SSL_get_error(ssl_, ret);
  10627. auto n = 1000;
  10628. #ifdef _WIN32
  10629. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  10630. (err == SSL_ERROR_SYSCALL &&
  10631. WSAGetLastError() == WSAETIMEDOUT))) {
  10632. #else
  10633. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  10634. #endif
  10635. if (wait_writable()) {
  10636. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10637. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  10638. if (ret >= 0) { return ret; }
  10639. err = SSL_get_error(ssl_, ret);
  10640. } else {
  10641. break;
  10642. }
  10643. }
  10644. assert(ret < 0);
  10645. }
  10646. return ret;
  10647. }
  10648. return -1;
  10649. }
  10650. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  10651. int &port) const {
  10652. detail::get_remote_ip_and_port(sock_, ip, port);
  10653. }
  10654. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  10655. int &port) const {
  10656. detail::get_local_ip_and_port(sock_, ip, port);
  10657. }
  10658. inline socket_t SSLSocketStream::socket() const { return sock_; }
  10659. inline time_t SSLSocketStream::duration() const {
  10660. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10661. std::chrono::steady_clock::now() - start_time_)
  10662. .count();
  10663. }
  10664. } // namespace detail
  10665. // SSL HTTP server implementation
  10666. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  10667. const char *client_ca_cert_file_path,
  10668. const char *client_ca_cert_dir_path,
  10669. const char *private_key_password) {
  10670. ctx_ = SSL_CTX_new(TLS_server_method());
  10671. if (ctx_) {
  10672. SSL_CTX_set_options(ctx_,
  10673. SSL_OP_NO_COMPRESSION |
  10674. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  10675. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  10676. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  10677. SSL_CTX_set_default_passwd_cb_userdata(
  10678. ctx_,
  10679. reinterpret_cast<void *>(const_cast<char *>(private_key_password)));
  10680. }
  10681. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  10682. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  10683. 1 ||
  10684. SSL_CTX_check_private_key(ctx_) != 1) {
  10685. last_ssl_error_ = static_cast<int>(ERR_get_error());
  10686. SSL_CTX_free(ctx_);
  10687. ctx_ = nullptr;
  10688. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  10689. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  10690. client_ca_cert_dir_path);
  10691. // Set client CA list to be sent to clients during TLS handshake
  10692. if (client_ca_cert_file_path) {
  10693. auto ca_list = SSL_load_client_CA_file(client_ca_cert_file_path);
  10694. if (ca_list != nullptr) {
  10695. SSL_CTX_set_client_CA_list(ctx_, ca_list);
  10696. } else {
  10697. // Failed to load client CA list, but we continue since
  10698. // SSL_CTX_load_verify_locations already succeeded and
  10699. // certificate verification will still work
  10700. last_ssl_error_ = static_cast<int>(ERR_get_error());
  10701. }
  10702. }
  10703. SSL_CTX_set_verify(
  10704. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  10705. }
  10706. }
  10707. }
  10708. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  10709. X509_STORE *client_ca_cert_store) {
  10710. ctx_ = SSL_CTX_new(TLS_server_method());
  10711. if (ctx_) {
  10712. SSL_CTX_set_options(ctx_,
  10713. SSL_OP_NO_COMPRESSION |
  10714. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  10715. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  10716. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  10717. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  10718. SSL_CTX_free(ctx_);
  10719. ctx_ = nullptr;
  10720. } else if (client_ca_cert_store) {
  10721. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  10722. // Extract CA names from the store and set them as the client CA list
  10723. auto ca_list = extract_ca_names_from_x509_store(client_ca_cert_store);
  10724. if (ca_list) {
  10725. SSL_CTX_set_client_CA_list(ctx_, ca_list);
  10726. } else {
  10727. // Failed to extract CA names, record the error
  10728. last_ssl_error_ = static_cast<int>(ERR_get_error());
  10729. }
  10730. SSL_CTX_set_verify(
  10731. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  10732. }
  10733. }
  10734. }
  10735. inline SSLServer::SSLServer(
  10736. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  10737. ctx_ = SSL_CTX_new(TLS_method());
  10738. if (ctx_) {
  10739. if (!setup_ssl_ctx_callback(*ctx_)) {
  10740. SSL_CTX_free(ctx_);
  10741. ctx_ = nullptr;
  10742. }
  10743. }
  10744. }
  10745. inline SSLServer::~SSLServer() {
  10746. if (ctx_) { SSL_CTX_free(ctx_); }
  10747. }
  10748. inline bool SSLServer::is_valid() const { return ctx_; }
  10749. inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  10750. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  10751. X509_STORE *client_ca_cert_store) {
  10752. std::lock_guard<std::mutex> guard(ctx_mutex_);
  10753. SSL_CTX_use_certificate(ctx_, cert);
  10754. SSL_CTX_use_PrivateKey(ctx_, private_key);
  10755. if (client_ca_cert_store != nullptr) {
  10756. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  10757. }
  10758. }
  10759. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  10760. auto ssl = detail::ssl_new(
  10761. sock, ctx_, ctx_mutex_,
  10762. [&](SSL *ssl2) {
  10763. return detail::ssl_connect_or_accept_nonblocking(
  10764. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_,
  10765. &last_ssl_error_);
  10766. },
  10767. [](SSL * /*ssl2*/) { return true; });
  10768. auto ret = false;
  10769. if (ssl) {
  10770. std::string remote_addr;
  10771. int remote_port = 0;
  10772. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10773. std::string local_addr;
  10774. int local_port = 0;
  10775. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10776. ret = detail::process_server_socket_ssl(
  10777. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10778. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10779. write_timeout_usec_,
  10780. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10781. return process_request(strm, remote_addr, remote_port, local_addr,
  10782. local_port, close_connection,
  10783. connection_closed,
  10784. [&](Request &req) { req.ssl = ssl; });
  10785. });
  10786. // Shutdown gracefully if the result seemed successful, non-gracefully if
  10787. // the connection appeared to be closed.
  10788. const bool shutdown_gracefully = ret;
  10789. detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
  10790. }
  10791. detail::shutdown_socket(sock);
  10792. detail::close_socket(sock);
  10793. return ret;
  10794. }
  10795. inline STACK_OF(X509_NAME) * SSLServer::extract_ca_names_from_x509_store(
  10796. X509_STORE *store) {
  10797. if (!store) { return nullptr; }
  10798. auto ca_list = sk_X509_NAME_new_null();
  10799. if (!ca_list) { return nullptr; }
  10800. // Get all objects from the store
  10801. auto objs = X509_STORE_get0_objects(store);
  10802. if (!objs) {
  10803. sk_X509_NAME_free(ca_list);
  10804. return nullptr;
  10805. }
  10806. // Iterate through objects and extract certificate subject names
  10807. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  10808. auto obj = sk_X509_OBJECT_value(objs, i);
  10809. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  10810. auto cert = X509_OBJECT_get0_X509(obj);
  10811. if (cert) {
  10812. auto subject = X509_get_subject_name(cert);
  10813. if (subject) {
  10814. auto name_dup = X509_NAME_dup(subject);
  10815. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  10816. }
  10817. }
  10818. }
  10819. }
  10820. // If no names were extracted, free the list and return nullptr
  10821. if (sk_X509_NAME_num(ca_list) == 0) {
  10822. sk_X509_NAME_free(ca_list);
  10823. return nullptr;
  10824. }
  10825. return ca_list;
  10826. }
  10827. // SSL HTTP client implementation
  10828. inline SSLClient::SSLClient(const std::string &host)
  10829. : SSLClient(host, 443, std::string(), std::string()) {}
  10830. inline SSLClient::SSLClient(const std::string &host, int port)
  10831. : SSLClient(host, port, std::string(), std::string()) {}
  10832. inline SSLClient::SSLClient(const std::string &host, int port,
  10833. const std::string &client_cert_path,
  10834. const std::string &client_key_path,
  10835. const std::string &private_key_password)
  10836. : ClientImpl(host, port, client_cert_path, client_key_path) {
  10837. ctx_ = SSL_CTX_new(TLS_client_method());
  10838. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  10839. detail::split(&host_[0], &host_[host_.size()], '.',
  10840. [&](const char *b, const char *e) {
  10841. host_components_.emplace_back(b, e);
  10842. });
  10843. if (!client_cert_path.empty() && !client_key_path.empty()) {
  10844. if (!private_key_password.empty()) {
  10845. SSL_CTX_set_default_passwd_cb_userdata(
  10846. ctx_, reinterpret_cast<void *>(
  10847. const_cast<char *>(private_key_password.c_str())));
  10848. }
  10849. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  10850. SSL_FILETYPE_PEM) != 1 ||
  10851. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  10852. SSL_FILETYPE_PEM) != 1) {
  10853. last_openssl_error_ = ERR_get_error();
  10854. SSL_CTX_free(ctx_);
  10855. ctx_ = nullptr;
  10856. }
  10857. }
  10858. }
  10859. inline SSLClient::SSLClient(const std::string &host, int port,
  10860. X509 *client_cert, EVP_PKEY *client_key,
  10861. const std::string &private_key_password)
  10862. : ClientImpl(host, port) {
  10863. ctx_ = SSL_CTX_new(TLS_client_method());
  10864. detail::split(&host_[0], &host_[host_.size()], '.',
  10865. [&](const char *b, const char *e) {
  10866. host_components_.emplace_back(b, e);
  10867. });
  10868. if (client_cert != nullptr && client_key != nullptr) {
  10869. if (!private_key_password.empty()) {
  10870. SSL_CTX_set_default_passwd_cb_userdata(
  10871. ctx_, reinterpret_cast<void *>(
  10872. const_cast<char *>(private_key_password.c_str())));
  10873. }
  10874. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  10875. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  10876. last_openssl_error_ = ERR_get_error();
  10877. SSL_CTX_free(ctx_);
  10878. ctx_ = nullptr;
  10879. }
  10880. }
  10881. }
  10882. inline SSLClient::~SSLClient() {
  10883. if (ctx_) { SSL_CTX_free(ctx_); }
  10884. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  10885. // base function rather than the derived function once we get to the
  10886. // base class destructor, and won't free the SSL (causing a leak).
  10887. shutdown_ssl_impl(socket_, true);
  10888. }
  10889. inline bool SSLClient::is_valid() const { return ctx_; }
  10890. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  10891. if (ca_cert_store) {
  10892. if (ctx_) {
  10893. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  10894. // Free memory allocated for old cert and use new store
  10895. // `ca_cert_store`
  10896. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  10897. ca_cert_store_ = ca_cert_store;
  10898. }
  10899. } else {
  10900. X509_STORE_free(ca_cert_store);
  10901. }
  10902. }
  10903. }
  10904. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  10905. std::size_t size) {
  10906. set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
  10907. }
  10908. inline long SSLClient::get_openssl_verify_result() const {
  10909. return verify_result_;
  10910. }
  10911. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  10912. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  10913. if (!is_valid()) {
  10914. error = Error::SSLConnection;
  10915. return false;
  10916. }
  10917. return ClientImpl::create_and_connect_socket(socket, error);
  10918. }
  10919. // Assumes that socket_mutex_ is locked and that there are no requests in
  10920. // flight
  10921. inline bool SSLClient::connect_with_proxy(
  10922. Socket &socket,
  10923. std::chrono::time_point<std::chrono::steady_clock> start_time,
  10924. Response &res, bool &success, Error &error) {
  10925. success = true;
  10926. Response proxy_res;
  10927. if (!detail::process_client_socket(
  10928. socket.sock, read_timeout_sec_, read_timeout_usec_,
  10929. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  10930. start_time, [&](Stream &strm) {
  10931. Request req2;
  10932. req2.method = "CONNECT";
  10933. req2.path =
  10934. detail::make_host_and_port_string_always_port(host_, port_);
  10935. if (max_timeout_msec_ > 0) {
  10936. req2.start_time_ = std::chrono::steady_clock::now();
  10937. }
  10938. return process_request(strm, req2, proxy_res, false, error);
  10939. })) {
  10940. // Thread-safe to close everything because we are assuming there are no
  10941. // requests in flight
  10942. shutdown_ssl(socket, true);
  10943. shutdown_socket(socket);
  10944. close_socket(socket);
  10945. success = false;
  10946. return false;
  10947. }
  10948. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  10949. if (!proxy_digest_auth_username_.empty() &&
  10950. !proxy_digest_auth_password_.empty()) {
  10951. std::map<std::string, std::string> auth;
  10952. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  10953. // Close the current socket and create a new one for the authenticated
  10954. // request
  10955. shutdown_ssl(socket, true);
  10956. shutdown_socket(socket);
  10957. close_socket(socket);
  10958. // Create a new socket for the authenticated CONNECT request
  10959. if (!ensure_socket_connection(socket, error)) {
  10960. success = false;
  10961. output_error_log(error, nullptr);
  10962. return false;
  10963. }
  10964. proxy_res = Response();
  10965. if (!detail::process_client_socket(
  10966. socket.sock, read_timeout_sec_, read_timeout_usec_,
  10967. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  10968. start_time, [&](Stream &strm) {
  10969. Request req3;
  10970. req3.method = "CONNECT";
  10971. req3.path = detail::make_host_and_port_string_always_port(
  10972. host_, port_);
  10973. req3.headers.insert(detail::make_digest_authentication_header(
  10974. req3, auth, 1, detail::random_string(10),
  10975. proxy_digest_auth_username_, proxy_digest_auth_password_,
  10976. true));
  10977. if (max_timeout_msec_ > 0) {
  10978. req3.start_time_ = std::chrono::steady_clock::now();
  10979. }
  10980. return process_request(strm, req3, proxy_res, false, error);
  10981. })) {
  10982. // Thread-safe to close everything because we are assuming there are
  10983. // no requests in flight
  10984. shutdown_ssl(socket, true);
  10985. shutdown_socket(socket);
  10986. close_socket(socket);
  10987. success = false;
  10988. return false;
  10989. }
  10990. }
  10991. }
  10992. }
  10993. // If status code is not 200, proxy request is failed.
  10994. // Set error to ProxyConnection and return proxy response
  10995. // as the response of the request
  10996. if (proxy_res.status != StatusCode::OK_200) {
  10997. error = Error::ProxyConnection;
  10998. output_error_log(error, nullptr);
  10999. res = std::move(proxy_res);
  11000. // Thread-safe to close everything because we are assuming there are
  11001. // no requests in flight
  11002. shutdown_ssl(socket, true);
  11003. shutdown_socket(socket);
  11004. close_socket(socket);
  11005. return false;
  11006. }
  11007. return true;
  11008. }
  11009. inline bool SSLClient::load_certs() {
  11010. auto ret = true;
  11011. std::call_once(initialize_cert_, [&]() {
  11012. std::lock_guard<std::mutex> guard(ctx_mutex_);
  11013. if (!ca_cert_file_path_.empty()) {
  11014. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  11015. nullptr)) {
  11016. last_openssl_error_ = ERR_get_error();
  11017. ret = false;
  11018. }
  11019. } else if (!ca_cert_dir_path_.empty()) {
  11020. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  11021. ca_cert_dir_path_.c_str())) {
  11022. last_openssl_error_ = ERR_get_error();
  11023. ret = false;
  11024. }
  11025. } else if (!ca_cert_store_) {
  11026. auto loaded = false;
  11027. #ifdef _WIN32
  11028. loaded =
  11029. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  11030. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  11031. loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
  11032. #endif // _WIN32
  11033. if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }
  11034. }
  11035. });
  11036. return ret;
  11037. }
  11038. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  11039. auto ssl = detail::ssl_new(
  11040. socket.sock, ctx_, ctx_mutex_,
  11041. [&](SSL *ssl2) {
  11042. if (server_certificate_verification_) {
  11043. if (!load_certs()) {
  11044. error = Error::SSLLoadingCerts;
  11045. output_error_log(error, nullptr);
  11046. return false;
  11047. }
  11048. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  11049. }
  11050. if (!detail::ssl_connect_or_accept_nonblocking(
  11051. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  11052. connection_timeout_usec_, &last_ssl_error_)) {
  11053. error = Error::SSLConnection;
  11054. output_error_log(error, nullptr);
  11055. return false;
  11056. }
  11057. if (server_certificate_verification_) {
  11058. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  11059. if (server_certificate_verifier_) {
  11060. verification_status = server_certificate_verifier_(ssl2);
  11061. }
  11062. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  11063. last_openssl_error_ = ERR_get_error();
  11064. error = Error::SSLServerVerification;
  11065. output_error_log(error, nullptr);
  11066. return false;
  11067. }
  11068. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  11069. verify_result_ = SSL_get_verify_result(ssl2);
  11070. if (verify_result_ != X509_V_OK) {
  11071. last_openssl_error_ = static_cast<unsigned long>(verify_result_);
  11072. error = Error::SSLServerVerification;
  11073. output_error_log(error, nullptr);
  11074. return false;
  11075. }
  11076. auto server_cert = SSL_get1_peer_certificate(ssl2);
  11077. auto se = detail::scope_exit([&] { X509_free(server_cert); });
  11078. if (server_cert == nullptr) {
  11079. last_openssl_error_ = ERR_get_error();
  11080. error = Error::SSLServerVerification;
  11081. output_error_log(error, nullptr);
  11082. return false;
  11083. }
  11084. if (server_hostname_verification_) {
  11085. if (!verify_host(server_cert)) {
  11086. last_openssl_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  11087. error = Error::SSLServerHostnameVerification;
  11088. output_error_log(error, nullptr);
  11089. return false;
  11090. }
  11091. }
  11092. }
  11093. }
  11094. return true;
  11095. },
  11096. [&](SSL *ssl2) {
  11097. // Set SNI only if host is not IP address
  11098. if (!detail::is_ip_address(host_)) {
  11099. #if defined(OPENSSL_IS_BORINGSSL)
  11100. SSL_set_tlsext_host_name(ssl2, host_.c_str());
  11101. #else
  11102. // NOTE: Direct call instead of using the OpenSSL macro to suppress
  11103. // -Wold-style-cast warning
  11104. SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME,
  11105. TLSEXT_NAMETYPE_host_name,
  11106. static_cast<void *>(const_cast<char *>(host_.c_str())));
  11107. #endif
  11108. }
  11109. return true;
  11110. });
  11111. if (ssl) {
  11112. socket.ssl = ssl;
  11113. return true;
  11114. }
  11115. if (ctx_ == nullptr) {
  11116. error = Error::SSLConnection;
  11117. last_openssl_error_ = ERR_get_error();
  11118. }
  11119. shutdown_socket(socket);
  11120. close_socket(socket);
  11121. return false;
  11122. }
  11123. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  11124. shutdown_ssl_impl(socket, shutdown_gracefully);
  11125. }
  11126. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  11127. bool shutdown_gracefully) {
  11128. if (socket.sock == INVALID_SOCKET) {
  11129. assert(socket.ssl == nullptr);
  11130. return;
  11131. }
  11132. if (socket.ssl) {
  11133. detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock,
  11134. shutdown_gracefully);
  11135. socket.ssl = nullptr;
  11136. }
  11137. assert(socket.ssl == nullptr);
  11138. }
  11139. inline bool SSLClient::process_socket(
  11140. const Socket &socket,
  11141. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11142. std::function<bool(Stream &strm)> callback) {
  11143. assert(socket.ssl);
  11144. return detail::process_client_socket_ssl(
  11145. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  11146. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  11147. std::move(callback));
  11148. }
  11149. inline bool SSLClient::is_ssl() const { return true; }
  11150. inline bool SSLClient::verify_host(X509 *server_cert) const {
  11151. /* Quote from RFC2818 section 3.1 "Server Identity"
  11152. If a subjectAltName extension of type dNSName is present, that MUST
  11153. be used as the identity. Otherwise, the (most specific) Common Name
  11154. field in the Subject field of the certificate MUST be used. Although
  11155. the use of the Common Name is existing practice, it is deprecated and
  11156. Certification Authorities are encouraged to use the dNSName instead.
  11157. Matching is performed using the matching rules specified by
  11158. [RFC2459]. If more than one identity of a given type is present in
  11159. the certificate (e.g., more than one dNSName name, a match in any one
  11160. of the set is considered acceptable.) Names may contain the wildcard
  11161. character * which is considered to match any single domain name
  11162. component or component fragment. E.g., *.a.com matches foo.a.com but
  11163. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  11164. In some cases, the URI is specified as an IP address rather than a
  11165. hostname. In this case, the iPAddress subjectAltName must be present
  11166. in the certificate and must exactly match the IP in the URI.
  11167. */
  11168. return verify_host_with_subject_alt_name(server_cert) ||
  11169. verify_host_with_common_name(server_cert);
  11170. }
  11171. inline bool
  11172. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  11173. auto ret = false;
  11174. auto type = GEN_DNS;
  11175. struct in6_addr addr6 = {};
  11176. struct in_addr addr = {};
  11177. size_t addr_len = 0;
  11178. #ifndef __MINGW32__
  11179. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  11180. type = GEN_IPADD;
  11181. addr_len = sizeof(struct in6_addr);
  11182. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  11183. type = GEN_IPADD;
  11184. addr_len = sizeof(struct in_addr);
  11185. }
  11186. #endif
  11187. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  11188. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  11189. if (alt_names) {
  11190. auto dsn_matched = false;
  11191. auto ip_matched = false;
  11192. auto count = sk_GENERAL_NAME_num(alt_names);
  11193. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  11194. auto val = sk_GENERAL_NAME_value(alt_names, i);
  11195. if (!val || val->type != type) { continue; }
  11196. auto name =
  11197. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  11198. if (name == nullptr) { continue; }
  11199. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  11200. switch (type) {
  11201. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  11202. case GEN_IPADD:
  11203. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  11204. ip_matched = true;
  11205. }
  11206. break;
  11207. }
  11208. }
  11209. if (dsn_matched || ip_matched) { ret = true; }
  11210. }
  11211. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  11212. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  11213. return ret;
  11214. }
  11215. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  11216. const auto subject_name = X509_get_subject_name(server_cert);
  11217. if (subject_name != nullptr) {
  11218. char name[BUFSIZ];
  11219. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  11220. name, sizeof(name));
  11221. if (name_len != -1) {
  11222. return check_host_name(name, static_cast<size_t>(name_len));
  11223. }
  11224. }
  11225. return false;
  11226. }
  11227. inline bool SSLClient::check_host_name(const char *pattern,
  11228. size_t pattern_len) const {
  11229. // Exact match (case-insensitive)
  11230. if (host_.size() == pattern_len &&
  11231. detail::case_ignore::equal(host_, std::string(pattern, pattern_len))) {
  11232. return true;
  11233. }
  11234. // Wildcard match
  11235. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  11236. std::vector<std::string> pattern_components;
  11237. detail::split(&pattern[0], &pattern[pattern_len], '.',
  11238. [&](const char *b, const char *e) {
  11239. pattern_components.emplace_back(b, e);
  11240. });
  11241. if (host_components_.size() != pattern_components.size()) { return false; }
  11242. auto itr = pattern_components.begin();
  11243. for (const auto &h : host_components_) {
  11244. auto &p = *itr;
  11245. if (!httplib::detail::case_ignore::equal(p, h) && p != "*") {
  11246. bool partial_match = false;
  11247. if (!p.empty() && p[p.size() - 1] == '*') {
  11248. const auto prefix_length = p.size() - 1;
  11249. if (prefix_length == 0) {
  11250. partial_match = true;
  11251. } else if (h.size() >= prefix_length) {
  11252. partial_match =
  11253. std::equal(p.begin(), p.begin() + prefix_length, h.begin(),
  11254. [](const char ca, const char cb) {
  11255. return httplib::detail::case_ignore::to_lower(ca) ==
  11256. httplib::detail::case_ignore::to_lower(cb);
  11257. });
  11258. }
  11259. }
  11260. if (!partial_match) { return false; }
  11261. }
  11262. ++itr;
  11263. }
  11264. return true;
  11265. }
  11266. #endif
  11267. // Universal client implementation
  11268. inline Client::Client(const std::string &scheme_host_port)
  11269. : Client(scheme_host_port, std::string(), std::string()) {}
  11270. inline Client::Client(const std::string &scheme_host_port,
  11271. const std::string &client_cert_path,
  11272. const std::string &client_key_path) {
  11273. const static std::regex re(
  11274. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  11275. std::smatch m;
  11276. if (std::regex_match(scheme_host_port, m, re)) {
  11277. auto scheme = m[1].str();
  11278. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11279. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  11280. #else
  11281. if (!scheme.empty() && scheme != "http") {
  11282. #endif
  11283. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11284. std::string msg = "'" + scheme + "' scheme is not supported.";
  11285. throw std::invalid_argument(msg);
  11286. #endif
  11287. return;
  11288. }
  11289. auto is_ssl = scheme == "https";
  11290. auto host = m[2].str();
  11291. if (host.empty()) { host = m[3].str(); }
  11292. auto port_str = m[4].str();
  11293. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  11294. if (is_ssl) {
  11295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11296. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  11297. client_key_path);
  11298. is_ssl_ = is_ssl;
  11299. #endif
  11300. } else {
  11301. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  11302. client_key_path);
  11303. }
  11304. } else {
  11305. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  11306. // if port param below changes.
  11307. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  11308. client_cert_path, client_key_path);
  11309. }
  11310. } // namespace detail
  11311. inline Client::Client(const std::string &host, int port)
  11312. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  11313. inline Client::Client(const std::string &host, int port,
  11314. const std::string &client_cert_path,
  11315. const std::string &client_key_path)
  11316. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  11317. client_key_path)) {}
  11318. inline Client::~Client() = default;
  11319. inline bool Client::is_valid() const {
  11320. return cli_ != nullptr && cli_->is_valid();
  11321. }
  11322. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  11323. return cli_->Get(path, std::move(progress));
  11324. }
  11325. inline Result Client::Get(const std::string &path, const Headers &headers,
  11326. DownloadProgress progress) {
  11327. return cli_->Get(path, headers, std::move(progress));
  11328. }
  11329. inline Result Client::Get(const std::string &path,
  11330. ContentReceiver content_receiver,
  11331. DownloadProgress progress) {
  11332. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  11333. }
  11334. inline Result Client::Get(const std::string &path, const Headers &headers,
  11335. ContentReceiver content_receiver,
  11336. DownloadProgress progress) {
  11337. return cli_->Get(path, headers, std::move(content_receiver),
  11338. std::move(progress));
  11339. }
  11340. inline Result Client::Get(const std::string &path,
  11341. ResponseHandler response_handler,
  11342. ContentReceiver content_receiver,
  11343. DownloadProgress progress) {
  11344. return cli_->Get(path, std::move(response_handler),
  11345. std::move(content_receiver), std::move(progress));
  11346. }
  11347. inline Result Client::Get(const std::string &path, const Headers &headers,
  11348. ResponseHandler response_handler,
  11349. ContentReceiver content_receiver,
  11350. DownloadProgress progress) {
  11351. return cli_->Get(path, headers, std::move(response_handler),
  11352. std::move(content_receiver), std::move(progress));
  11353. }
  11354. inline Result Client::Get(const std::string &path, const Params &params,
  11355. const Headers &headers, DownloadProgress progress) {
  11356. return cli_->Get(path, params, headers, std::move(progress));
  11357. }
  11358. inline Result Client::Get(const std::string &path, const Params &params,
  11359. const Headers &headers,
  11360. ContentReceiver content_receiver,
  11361. DownloadProgress progress) {
  11362. return cli_->Get(path, params, headers, std::move(content_receiver),
  11363. std::move(progress));
  11364. }
  11365. inline Result Client::Get(const std::string &path, const Params &params,
  11366. const Headers &headers,
  11367. ResponseHandler response_handler,
  11368. ContentReceiver content_receiver,
  11369. DownloadProgress progress) {
  11370. return cli_->Get(path, params, headers, std::move(response_handler),
  11371. std::move(content_receiver), std::move(progress));
  11372. }
  11373. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  11374. inline Result Client::Head(const std::string &path, const Headers &headers) {
  11375. return cli_->Head(path, headers);
  11376. }
  11377. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  11378. inline Result Client::Post(const std::string &path, const Headers &headers) {
  11379. return cli_->Post(path, headers);
  11380. }
  11381. inline Result Client::Post(const std::string &path, const char *body,
  11382. size_t content_length,
  11383. const std::string &content_type,
  11384. UploadProgress progress) {
  11385. return cli_->Post(path, body, content_length, content_type, progress);
  11386. }
  11387. inline Result Client::Post(const std::string &path, const Headers &headers,
  11388. const char *body, size_t content_length,
  11389. const std::string &content_type,
  11390. UploadProgress progress) {
  11391. return cli_->Post(path, headers, body, content_length, content_type,
  11392. progress);
  11393. }
  11394. inline Result Client::Post(const std::string &path, const std::string &body,
  11395. const std::string &content_type,
  11396. UploadProgress progress) {
  11397. return cli_->Post(path, body, content_type, progress);
  11398. }
  11399. inline Result Client::Post(const std::string &path, const Headers &headers,
  11400. const std::string &body,
  11401. const std::string &content_type,
  11402. UploadProgress progress) {
  11403. return cli_->Post(path, headers, body, content_type, progress);
  11404. }
  11405. inline Result Client::Post(const std::string &path, size_t content_length,
  11406. ContentProvider content_provider,
  11407. const std::string &content_type,
  11408. UploadProgress progress) {
  11409. return cli_->Post(path, content_length, std::move(content_provider),
  11410. content_type, progress);
  11411. }
  11412. inline Result Client::Post(const std::string &path, size_t content_length,
  11413. ContentProvider content_provider,
  11414. const std::string &content_type,
  11415. ContentReceiver content_receiver,
  11416. UploadProgress progress) {
  11417. return cli_->Post(path, content_length, std::move(content_provider),
  11418. content_type, std::move(content_receiver), progress);
  11419. }
  11420. inline Result Client::Post(const std::string &path,
  11421. ContentProviderWithoutLength content_provider,
  11422. const std::string &content_type,
  11423. UploadProgress progress) {
  11424. return cli_->Post(path, std::move(content_provider), content_type, progress);
  11425. }
  11426. inline Result Client::Post(const std::string &path,
  11427. ContentProviderWithoutLength content_provider,
  11428. const std::string &content_type,
  11429. ContentReceiver content_receiver,
  11430. UploadProgress progress) {
  11431. return cli_->Post(path, std::move(content_provider), content_type,
  11432. std::move(content_receiver), progress);
  11433. }
  11434. inline Result Client::Post(const std::string &path, const Headers &headers,
  11435. size_t content_length,
  11436. ContentProvider content_provider,
  11437. const std::string &content_type,
  11438. UploadProgress progress) {
  11439. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11440. content_type, progress);
  11441. }
  11442. inline Result Client::Post(const std::string &path, const Headers &headers,
  11443. size_t content_length,
  11444. ContentProvider content_provider,
  11445. const std::string &content_type,
  11446. ContentReceiver content_receiver,
  11447. DownloadProgress progress) {
  11448. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11449. content_type, std::move(content_receiver), progress);
  11450. }
  11451. inline Result Client::Post(const std::string &path, const Headers &headers,
  11452. ContentProviderWithoutLength content_provider,
  11453. const std::string &content_type,
  11454. UploadProgress progress) {
  11455. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11456. progress);
  11457. }
  11458. inline Result Client::Post(const std::string &path, const Headers &headers,
  11459. ContentProviderWithoutLength content_provider,
  11460. const std::string &content_type,
  11461. ContentReceiver content_receiver,
  11462. DownloadProgress progress) {
  11463. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11464. std::move(content_receiver), progress);
  11465. }
  11466. inline Result Client::Post(const std::string &path, const Params &params) {
  11467. return cli_->Post(path, params);
  11468. }
  11469. inline Result Client::Post(const std::string &path, const Headers &headers,
  11470. const Params &params) {
  11471. return cli_->Post(path, headers, params);
  11472. }
  11473. inline Result Client::Post(const std::string &path,
  11474. const UploadFormDataItems &items,
  11475. UploadProgress progress) {
  11476. return cli_->Post(path, items, progress);
  11477. }
  11478. inline Result Client::Post(const std::string &path, const Headers &headers,
  11479. const UploadFormDataItems &items,
  11480. UploadProgress progress) {
  11481. return cli_->Post(path, headers, items, progress);
  11482. }
  11483. inline Result Client::Post(const std::string &path, const Headers &headers,
  11484. const UploadFormDataItems &items,
  11485. const std::string &boundary,
  11486. UploadProgress progress) {
  11487. return cli_->Post(path, headers, items, boundary, progress);
  11488. }
  11489. inline Result Client::Post(const std::string &path, const Headers &headers,
  11490. const UploadFormDataItems &items,
  11491. const FormDataProviderItems &provider_items,
  11492. UploadProgress progress) {
  11493. return cli_->Post(path, headers, items, provider_items, progress);
  11494. }
  11495. inline Result Client::Post(const std::string &path, const Headers &headers,
  11496. const std::string &body,
  11497. const std::string &content_type,
  11498. ContentReceiver content_receiver,
  11499. DownloadProgress progress) {
  11500. return cli_->Post(path, headers, body, content_type,
  11501. std::move(content_receiver), progress);
  11502. }
  11503. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  11504. inline Result Client::Put(const std::string &path, const Headers &headers) {
  11505. return cli_->Put(path, headers);
  11506. }
  11507. inline Result Client::Put(const std::string &path, const char *body,
  11508. size_t content_length,
  11509. const std::string &content_type,
  11510. UploadProgress progress) {
  11511. return cli_->Put(path, body, content_length, content_type, progress);
  11512. }
  11513. inline Result Client::Put(const std::string &path, const Headers &headers,
  11514. const char *body, size_t content_length,
  11515. const std::string &content_type,
  11516. UploadProgress progress) {
  11517. return cli_->Put(path, headers, body, content_length, content_type, progress);
  11518. }
  11519. inline Result Client::Put(const std::string &path, const std::string &body,
  11520. const std::string &content_type,
  11521. UploadProgress progress) {
  11522. return cli_->Put(path, body, content_type, progress);
  11523. }
  11524. inline Result Client::Put(const std::string &path, const Headers &headers,
  11525. const std::string &body,
  11526. const std::string &content_type,
  11527. UploadProgress progress) {
  11528. return cli_->Put(path, headers, body, content_type, progress);
  11529. }
  11530. inline Result Client::Put(const std::string &path, size_t content_length,
  11531. ContentProvider content_provider,
  11532. const std::string &content_type,
  11533. UploadProgress progress) {
  11534. return cli_->Put(path, content_length, std::move(content_provider),
  11535. content_type, progress);
  11536. }
  11537. inline Result Client::Put(const std::string &path, size_t content_length,
  11538. ContentProvider content_provider,
  11539. const std::string &content_type,
  11540. ContentReceiver content_receiver,
  11541. UploadProgress progress) {
  11542. return cli_->Put(path, content_length, std::move(content_provider),
  11543. content_type, std::move(content_receiver), progress);
  11544. }
  11545. inline Result Client::Put(const std::string &path,
  11546. ContentProviderWithoutLength content_provider,
  11547. const std::string &content_type,
  11548. UploadProgress progress) {
  11549. return cli_->Put(path, std::move(content_provider), content_type, progress);
  11550. }
  11551. inline Result Client::Put(const std::string &path,
  11552. ContentProviderWithoutLength content_provider,
  11553. const std::string &content_type,
  11554. ContentReceiver content_receiver,
  11555. UploadProgress progress) {
  11556. return cli_->Put(path, std::move(content_provider), content_type,
  11557. std::move(content_receiver), progress);
  11558. }
  11559. inline Result Client::Put(const std::string &path, const Headers &headers,
  11560. size_t content_length,
  11561. ContentProvider content_provider,
  11562. const std::string &content_type,
  11563. UploadProgress progress) {
  11564. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11565. content_type, progress);
  11566. }
  11567. inline Result Client::Put(const std::string &path, const Headers &headers,
  11568. size_t content_length,
  11569. ContentProvider content_provider,
  11570. const std::string &content_type,
  11571. ContentReceiver content_receiver,
  11572. UploadProgress progress) {
  11573. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11574. content_type, std::move(content_receiver), progress);
  11575. }
  11576. inline Result Client::Put(const std::string &path, const Headers &headers,
  11577. ContentProviderWithoutLength content_provider,
  11578. const std::string &content_type,
  11579. UploadProgress progress) {
  11580. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11581. progress);
  11582. }
  11583. inline Result Client::Put(const std::string &path, const Headers &headers,
  11584. ContentProviderWithoutLength content_provider,
  11585. const std::string &content_type,
  11586. ContentReceiver content_receiver,
  11587. UploadProgress progress) {
  11588. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11589. std::move(content_receiver), progress);
  11590. }
  11591. inline Result Client::Put(const std::string &path, const Params &params) {
  11592. return cli_->Put(path, params);
  11593. }
  11594. inline Result Client::Put(const std::string &path, const Headers &headers,
  11595. const Params &params) {
  11596. return cli_->Put(path, headers, params);
  11597. }
  11598. inline Result Client::Put(const std::string &path,
  11599. const UploadFormDataItems &items,
  11600. UploadProgress progress) {
  11601. return cli_->Put(path, items, progress);
  11602. }
  11603. inline Result Client::Put(const std::string &path, const Headers &headers,
  11604. const UploadFormDataItems &items,
  11605. UploadProgress progress) {
  11606. return cli_->Put(path, headers, items, progress);
  11607. }
  11608. inline Result Client::Put(const std::string &path, const Headers &headers,
  11609. const UploadFormDataItems &items,
  11610. const std::string &boundary,
  11611. UploadProgress progress) {
  11612. return cli_->Put(path, headers, items, boundary, progress);
  11613. }
  11614. inline Result Client::Put(const std::string &path, const Headers &headers,
  11615. const UploadFormDataItems &items,
  11616. const FormDataProviderItems &provider_items,
  11617. UploadProgress progress) {
  11618. return cli_->Put(path, headers, items, provider_items, progress);
  11619. }
  11620. inline Result Client::Put(const std::string &path, const Headers &headers,
  11621. const std::string &body,
  11622. const std::string &content_type,
  11623. ContentReceiver content_receiver,
  11624. DownloadProgress progress) {
  11625. return cli_->Put(path, headers, body, content_type, content_receiver,
  11626. progress);
  11627. }
  11628. inline Result Client::Patch(const std::string &path) {
  11629. return cli_->Patch(path);
  11630. }
  11631. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  11632. return cli_->Patch(path, headers);
  11633. }
  11634. inline Result Client::Patch(const std::string &path, const char *body,
  11635. size_t content_length,
  11636. const std::string &content_type,
  11637. UploadProgress progress) {
  11638. return cli_->Patch(path, body, content_length, content_type, progress);
  11639. }
  11640. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11641. const char *body, size_t content_length,
  11642. const std::string &content_type,
  11643. UploadProgress progress) {
  11644. return cli_->Patch(path, headers, body, content_length, content_type,
  11645. progress);
  11646. }
  11647. inline Result Client::Patch(const std::string &path, const std::string &body,
  11648. const std::string &content_type,
  11649. UploadProgress progress) {
  11650. return cli_->Patch(path, body, content_type, progress);
  11651. }
  11652. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11653. const std::string &body,
  11654. const std::string &content_type,
  11655. UploadProgress progress) {
  11656. return cli_->Patch(path, headers, body, content_type, progress);
  11657. }
  11658. inline Result Client::Patch(const std::string &path, size_t content_length,
  11659. ContentProvider content_provider,
  11660. const std::string &content_type,
  11661. UploadProgress progress) {
  11662. return cli_->Patch(path, content_length, std::move(content_provider),
  11663. content_type, progress);
  11664. }
  11665. inline Result Client::Patch(const std::string &path, size_t content_length,
  11666. ContentProvider content_provider,
  11667. const std::string &content_type,
  11668. ContentReceiver content_receiver,
  11669. UploadProgress progress) {
  11670. return cli_->Patch(path, content_length, std::move(content_provider),
  11671. content_type, std::move(content_receiver), progress);
  11672. }
  11673. inline Result Client::Patch(const std::string &path,
  11674. ContentProviderWithoutLength content_provider,
  11675. const std::string &content_type,
  11676. UploadProgress progress) {
  11677. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  11678. }
  11679. inline Result Client::Patch(const std::string &path,
  11680. ContentProviderWithoutLength content_provider,
  11681. const std::string &content_type,
  11682. ContentReceiver content_receiver,
  11683. UploadProgress progress) {
  11684. return cli_->Patch(path, std::move(content_provider), content_type,
  11685. std::move(content_receiver), progress);
  11686. }
  11687. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11688. size_t content_length,
  11689. ContentProvider content_provider,
  11690. const std::string &content_type,
  11691. UploadProgress progress) {
  11692. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11693. content_type, progress);
  11694. }
  11695. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11696. size_t content_length,
  11697. ContentProvider content_provider,
  11698. const std::string &content_type,
  11699. ContentReceiver content_receiver,
  11700. UploadProgress progress) {
  11701. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11702. content_type, std::move(content_receiver), progress);
  11703. }
  11704. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11705. ContentProviderWithoutLength content_provider,
  11706. const std::string &content_type,
  11707. UploadProgress progress) {
  11708. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11709. progress);
  11710. }
  11711. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11712. ContentProviderWithoutLength content_provider,
  11713. const std::string &content_type,
  11714. ContentReceiver content_receiver,
  11715. UploadProgress progress) {
  11716. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11717. std::move(content_receiver), progress);
  11718. }
  11719. inline Result Client::Patch(const std::string &path, const Params &params) {
  11720. return cli_->Patch(path, params);
  11721. }
  11722. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11723. const Params &params) {
  11724. return cli_->Patch(path, headers, params);
  11725. }
  11726. inline Result Client::Patch(const std::string &path,
  11727. const UploadFormDataItems &items,
  11728. UploadProgress progress) {
  11729. return cli_->Patch(path, items, progress);
  11730. }
  11731. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11732. const UploadFormDataItems &items,
  11733. UploadProgress progress) {
  11734. return cli_->Patch(path, headers, items, progress);
  11735. }
  11736. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11737. const UploadFormDataItems &items,
  11738. const std::string &boundary,
  11739. UploadProgress progress) {
  11740. return cli_->Patch(path, headers, items, boundary, progress);
  11741. }
  11742. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11743. const UploadFormDataItems &items,
  11744. const FormDataProviderItems &provider_items,
  11745. UploadProgress progress) {
  11746. return cli_->Patch(path, headers, items, provider_items, progress);
  11747. }
  11748. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11749. const std::string &body,
  11750. const std::string &content_type,
  11751. ContentReceiver content_receiver,
  11752. DownloadProgress progress) {
  11753. return cli_->Patch(path, headers, body, content_type, content_receiver,
  11754. progress);
  11755. }
  11756. inline Result Client::Delete(const std::string &path,
  11757. DownloadProgress progress) {
  11758. return cli_->Delete(path, progress);
  11759. }
  11760. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11761. DownloadProgress progress) {
  11762. return cli_->Delete(path, headers, progress);
  11763. }
  11764. inline Result Client::Delete(const std::string &path, const char *body,
  11765. size_t content_length,
  11766. const std::string &content_type,
  11767. DownloadProgress progress) {
  11768. return cli_->Delete(path, body, content_length, content_type, progress);
  11769. }
  11770. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11771. const char *body, size_t content_length,
  11772. const std::string &content_type,
  11773. DownloadProgress progress) {
  11774. return cli_->Delete(path, headers, body, content_length, content_type,
  11775. progress);
  11776. }
  11777. inline Result Client::Delete(const std::string &path, const std::string &body,
  11778. const std::string &content_type,
  11779. DownloadProgress progress) {
  11780. return cli_->Delete(path, body, content_type, progress);
  11781. }
  11782. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11783. const std::string &body,
  11784. const std::string &content_type,
  11785. DownloadProgress progress) {
  11786. return cli_->Delete(path, headers, body, content_type, progress);
  11787. }
  11788. inline Result Client::Delete(const std::string &path, const Params &params,
  11789. DownloadProgress progress) {
  11790. return cli_->Delete(path, params, progress);
  11791. }
  11792. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11793. const Params &params, DownloadProgress progress) {
  11794. return cli_->Delete(path, headers, params, progress);
  11795. }
  11796. inline Result Client::Options(const std::string &path) {
  11797. return cli_->Options(path);
  11798. }
  11799. inline Result Client::Options(const std::string &path, const Headers &headers) {
  11800. return cli_->Options(path, headers);
  11801. }
  11802. inline ClientImpl::StreamHandle
  11803. Client::open_stream(const std::string &method, const std::string &path,
  11804. const Params &params, const Headers &headers,
  11805. const std::string &body, const std::string &content_type) {
  11806. return cli_->open_stream(method, path, params, headers, body, content_type);
  11807. }
  11808. inline bool Client::send(Request &req, Response &res, Error &error) {
  11809. return cli_->send(req, res, error);
  11810. }
  11811. inline Result Client::send(const Request &req) { return cli_->send(req); }
  11812. inline void Client::stop() { cli_->stop(); }
  11813. inline std::string Client::host() const { return cli_->host(); }
  11814. inline int Client::port() const { return cli_->port(); }
  11815. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  11816. inline socket_t Client::socket() const { return cli_->socket(); }
  11817. inline void
  11818. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  11819. cli_->set_hostname_addr_map(std::move(addr_map));
  11820. }
  11821. inline void Client::set_default_headers(Headers headers) {
  11822. cli_->set_default_headers(std::move(headers));
  11823. }
  11824. inline void Client::set_header_writer(
  11825. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11826. cli_->set_header_writer(writer);
  11827. }
  11828. inline void Client::set_address_family(int family) {
  11829. cli_->set_address_family(family);
  11830. }
  11831. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  11832. inline void Client::set_socket_options(SocketOptions socket_options) {
  11833. cli_->set_socket_options(std::move(socket_options));
  11834. }
  11835. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  11836. cli_->set_connection_timeout(sec, usec);
  11837. }
  11838. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  11839. cli_->set_read_timeout(sec, usec);
  11840. }
  11841. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  11842. cli_->set_write_timeout(sec, usec);
  11843. }
  11844. inline void Client::set_basic_auth(const std::string &username,
  11845. const std::string &password) {
  11846. cli_->set_basic_auth(username, password);
  11847. }
  11848. inline void Client::set_bearer_token_auth(const std::string &token) {
  11849. cli_->set_bearer_token_auth(token);
  11850. }
  11851. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11852. inline void Client::set_digest_auth(const std::string &username,
  11853. const std::string &password) {
  11854. cli_->set_digest_auth(username, password);
  11855. }
  11856. #endif
  11857. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  11858. inline void Client::set_follow_location(bool on) {
  11859. cli_->set_follow_location(on);
  11860. }
  11861. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  11862. [[deprecated("Use set_path_encode instead")]]
  11863. inline void Client::set_url_encode(bool on) {
  11864. cli_->set_path_encode(on);
  11865. }
  11866. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  11867. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  11868. inline void Client::set_interface(const std::string &intf) {
  11869. cli_->set_interface(intf);
  11870. }
  11871. inline void Client::set_proxy(const std::string &host, int port) {
  11872. cli_->set_proxy(host, port);
  11873. }
  11874. inline void Client::set_proxy_basic_auth(const std::string &username,
  11875. const std::string &password) {
  11876. cli_->set_proxy_basic_auth(username, password);
  11877. }
  11878. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  11879. cli_->set_proxy_bearer_token_auth(token);
  11880. }
  11881. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11882. inline void Client::set_proxy_digest_auth(const std::string &username,
  11883. const std::string &password) {
  11884. cli_->set_proxy_digest_auth(username, password);
  11885. }
  11886. #endif
  11887. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11888. inline void Client::enable_server_certificate_verification(bool enabled) {
  11889. cli_->enable_server_certificate_verification(enabled);
  11890. }
  11891. inline void Client::enable_server_hostname_verification(bool enabled) {
  11892. cli_->enable_server_hostname_verification(enabled);
  11893. }
  11894. inline void Client::set_server_certificate_verifier(
  11895. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  11896. cli_->set_server_certificate_verifier(verifier);
  11897. }
  11898. #endif
  11899. inline void Client::set_logger(Logger logger) {
  11900. cli_->set_logger(std::move(logger));
  11901. }
  11902. inline void Client::set_error_logger(ErrorLogger error_logger) {
  11903. cli_->set_error_logger(std::move(error_logger));
  11904. }
  11905. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11906. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  11907. const std::string &ca_cert_dir_path) {
  11908. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  11909. }
  11910. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  11911. if (is_ssl_) {
  11912. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  11913. } else {
  11914. cli_->set_ca_cert_store(ca_cert_store);
  11915. }
  11916. }
  11917. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  11918. set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
  11919. }
  11920. inline long Client::get_openssl_verify_result() const {
  11921. if (is_ssl_) {
  11922. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  11923. }
  11924. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  11925. }
  11926. inline SSL_CTX *Client::ssl_context() const {
  11927. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  11928. return nullptr;
  11929. }
  11930. #endif
  11931. // ----------------------------------------------------------------------------
  11932. } // namespace httplib
  11933. #endif // CPPHTTPLIB_HTTPLIB_H