httplib.h 357 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2025 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.22.0"
  10. /*
  11. * Configuration
  12. */
  13. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  14. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  15. #endif
  16. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  17. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  18. #endif
  19. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  20. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  21. #endif
  22. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  23. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  24. #endif
  25. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  26. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  27. #endif
  28. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  29. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  30. #endif
  31. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  32. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  33. #endif
  34. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  35. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  36. #endif
  37. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  38. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  39. #endif
  40. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  41. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  42. #endif
  43. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  44. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  45. #endif
  46. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  47. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  48. #endif
  49. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  50. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  51. #endif
  52. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  53. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  54. #endif
  55. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  56. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  57. #endif
  58. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  59. #ifdef _WIN32
  60. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  61. #else
  62. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  63. #endif
  64. #endif
  65. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  66. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  67. #endif
  68. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  69. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  70. #endif
  71. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  72. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  73. #endif
  74. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  75. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  76. #endif
  77. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  78. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  79. #endif
  80. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  81. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  82. #endif
  83. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  84. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  85. #endif
  86. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  87. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  88. #endif
  89. #ifndef CPPHTTPLIB_TCP_NODELAY
  90. #define CPPHTTPLIB_TCP_NODELAY false
  91. #endif
  92. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  93. #define CPPHTTPLIB_IPV6_V6ONLY false
  94. #endif
  95. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  96. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  97. #endif
  98. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  99. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  100. #endif
  101. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  102. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  103. #endif
  104. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  105. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  106. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  107. ? std::thread::hardware_concurrency() - 1 \
  108. : 0))
  109. #endif
  110. #ifndef CPPHTTPLIB_RECV_FLAGS
  111. #define CPPHTTPLIB_RECV_FLAGS 0
  112. #endif
  113. #ifndef CPPHTTPLIB_SEND_FLAGS
  114. #define CPPHTTPLIB_SEND_FLAGS 0
  115. #endif
  116. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  117. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  118. #endif
  119. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  120. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  121. #endif
  122. /*
  123. * Headers
  124. */
  125. #ifdef _WIN32
  126. #ifndef _CRT_SECURE_NO_WARNINGS
  127. #define _CRT_SECURE_NO_WARNINGS
  128. #endif //_CRT_SECURE_NO_WARNINGS
  129. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  130. #define _CRT_NONSTDC_NO_DEPRECATE
  131. #endif //_CRT_NONSTDC_NO_DEPRECATE
  132. #if defined(_MSC_VER)
  133. #if _MSC_VER < 1900
  134. #error Sorry, Visual Studio versions prior to 2015 are not supported
  135. #endif
  136. #pragma comment(lib, "ws2_32.lib")
  137. #ifdef _WIN64
  138. using ssize_t = __int64;
  139. #else
  140. using ssize_t = long;
  141. #endif
  142. #endif // _MSC_VER
  143. #ifndef S_ISREG
  144. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  145. #endif // S_ISREG
  146. #ifndef S_ISDIR
  147. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  148. #endif // S_ISDIR
  149. #ifndef NOMINMAX
  150. #define NOMINMAX
  151. #endif // NOMINMAX
  152. #include <io.h>
  153. #include <winsock2.h>
  154. #include <ws2tcpip.h>
  155. #if defined(__has_include)
  156. #if __has_include(<afunix.h>)
  157. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  158. #include <afunix.h>
  159. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  160. #endif
  161. #endif
  162. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  163. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  164. #endif
  165. using nfds_t = unsigned long;
  166. using socket_t = SOCKET;
  167. using socklen_t = int;
  168. #else // not _WIN32
  169. #include <arpa/inet.h>
  170. #if !defined(_AIX) && !defined(__MVS__)
  171. #include <ifaddrs.h>
  172. #endif
  173. #ifdef __MVS__
  174. #include <strings.h>
  175. #ifndef NI_MAXHOST
  176. #define NI_MAXHOST 1025
  177. #endif
  178. #endif
  179. #include <net/if.h>
  180. #include <netdb.h>
  181. #include <netinet/in.h>
  182. #ifdef __linux__
  183. #include <resolv.h>
  184. #endif
  185. #include <csignal>
  186. #include <netinet/tcp.h>
  187. #include <poll.h>
  188. #include <pthread.h>
  189. #include <sys/mman.h>
  190. #include <sys/socket.h>
  191. #include <sys/un.h>
  192. #include <unistd.h>
  193. using socket_t = int;
  194. #ifndef INVALID_SOCKET
  195. #define INVALID_SOCKET (-1)
  196. #endif
  197. #endif //_WIN32
  198. #include <algorithm>
  199. #include <array>
  200. #include <atomic>
  201. #include <cassert>
  202. #include <cctype>
  203. #include <climits>
  204. #include <condition_variable>
  205. #include <cstring>
  206. #include <errno.h>
  207. #include <exception>
  208. #include <fcntl.h>
  209. #include <functional>
  210. #include <iomanip>
  211. #include <iostream>
  212. #include <list>
  213. #include <map>
  214. #include <memory>
  215. #include <mutex>
  216. #include <random>
  217. #include <regex>
  218. #include <set>
  219. #include <sstream>
  220. #include <string>
  221. #include <sys/stat.h>
  222. #include <thread>
  223. #include <unordered_map>
  224. #include <unordered_set>
  225. #include <utility>
  226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  227. #ifdef _WIN32
  228. #include <wincrypt.h>
  229. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  230. // used
  231. #undef X509_NAME
  232. #undef X509_CERT_PAIR
  233. #undef X509_EXTENSIONS
  234. #undef PKCS7_SIGNER_INFO
  235. #ifdef _MSC_VER
  236. #pragma comment(lib, "crypt32.lib")
  237. #endif
  238. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
  239. #include <TargetConditionals.h>
  240. #if TARGET_OS_OSX
  241. #include <CoreFoundation/CoreFoundation.h>
  242. #include <Security/Security.h>
  243. #endif // TARGET_OS_OSX
  244. #endif // _WIN32
  245. #include <openssl/err.h>
  246. #include <openssl/evp.h>
  247. #include <openssl/ssl.h>
  248. #include <openssl/x509v3.h>
  249. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  250. #include <openssl/applink.c>
  251. #endif
  252. #include <iostream>
  253. #include <sstream>
  254. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  255. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  256. #error Please use OpenSSL or a current version of BoringSSL
  257. #endif
  258. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  259. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  260. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  261. #endif
  262. #endif
  263. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  264. #include <zlib.h>
  265. #endif
  266. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  267. #include <brotli/decode.h>
  268. #include <brotli/encode.h>
  269. #endif
  270. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  271. #include <zstd.h>
  272. #endif
  273. /*
  274. * Declaration
  275. */
  276. namespace httplib {
  277. namespace detail {
  278. /*
  279. * Backport std::make_unique from C++14.
  280. *
  281. * NOTE: This code came up with the following stackoverflow post:
  282. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  283. *
  284. */
  285. template <class T, class... Args>
  286. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  287. make_unique(Args &&...args) {
  288. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  289. }
  290. template <class T>
  291. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  292. make_unique(std::size_t n) {
  293. typedef typename std::remove_extent<T>::type RT;
  294. return std::unique_ptr<T>(new RT[n]);
  295. }
  296. namespace case_ignore {
  297. inline unsigned char to_lower(int c) {
  298. const static unsigned char table[256] = {
  299. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  300. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  301. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  302. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  303. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  304. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  305. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  306. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  307. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  308. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  309. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  310. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  311. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  312. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  313. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  314. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  315. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  316. 255,
  317. };
  318. return table[(unsigned char)(char)c];
  319. }
  320. inline bool equal(const std::string &a, const std::string &b) {
  321. return a.size() == b.size() &&
  322. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  323. return to_lower(ca) == to_lower(cb);
  324. });
  325. }
  326. struct equal_to {
  327. bool operator()(const std::string &a, const std::string &b) const {
  328. return equal(a, b);
  329. }
  330. };
  331. struct hash {
  332. size_t operator()(const std::string &key) const {
  333. return hash_core(key.data(), key.size(), 0);
  334. }
  335. size_t hash_core(const char *s, size_t l, size_t h) const {
  336. return (l == 0) ? h
  337. : hash_core(s + 1, l - 1,
  338. // Unsets the 6 high bits of h, therefore no
  339. // overflow happens
  340. (((std::numeric_limits<size_t>::max)() >> 6) &
  341. h * 33) ^
  342. static_cast<unsigned char>(to_lower(*s)));
  343. }
  344. };
  345. } // namespace case_ignore
  346. // This is based on
  347. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  348. struct scope_exit {
  349. explicit scope_exit(std::function<void(void)> &&f)
  350. : exit_function(std::move(f)), execute_on_destruction{true} {}
  351. scope_exit(scope_exit &&rhs) noexcept
  352. : exit_function(std::move(rhs.exit_function)),
  353. execute_on_destruction{rhs.execute_on_destruction} {
  354. rhs.release();
  355. }
  356. ~scope_exit() {
  357. if (execute_on_destruction) { this->exit_function(); }
  358. }
  359. void release() { this->execute_on_destruction = false; }
  360. private:
  361. scope_exit(const scope_exit &) = delete;
  362. void operator=(const scope_exit &) = delete;
  363. scope_exit &operator=(scope_exit &&) = delete;
  364. std::function<void(void)> exit_function;
  365. bool execute_on_destruction;
  366. };
  367. } // namespace detail
  368. enum SSLVerifierResponse {
  369. // no decision has been made, use the built-in certificate verifier
  370. NoDecisionMade,
  371. // connection certificate is verified and accepted
  372. CertificateAccepted,
  373. // connection certificate was processed but is rejected
  374. CertificateRejected
  375. };
  376. enum StatusCode {
  377. // Information responses
  378. Continue_100 = 100,
  379. SwitchingProtocol_101 = 101,
  380. Processing_102 = 102,
  381. EarlyHints_103 = 103,
  382. // Successful responses
  383. OK_200 = 200,
  384. Created_201 = 201,
  385. Accepted_202 = 202,
  386. NonAuthoritativeInformation_203 = 203,
  387. NoContent_204 = 204,
  388. ResetContent_205 = 205,
  389. PartialContent_206 = 206,
  390. MultiStatus_207 = 207,
  391. AlreadyReported_208 = 208,
  392. IMUsed_226 = 226,
  393. // Redirection messages
  394. MultipleChoices_300 = 300,
  395. MovedPermanently_301 = 301,
  396. Found_302 = 302,
  397. SeeOther_303 = 303,
  398. NotModified_304 = 304,
  399. UseProxy_305 = 305,
  400. unused_306 = 306,
  401. TemporaryRedirect_307 = 307,
  402. PermanentRedirect_308 = 308,
  403. // Client error responses
  404. BadRequest_400 = 400,
  405. Unauthorized_401 = 401,
  406. PaymentRequired_402 = 402,
  407. Forbidden_403 = 403,
  408. NotFound_404 = 404,
  409. MethodNotAllowed_405 = 405,
  410. NotAcceptable_406 = 406,
  411. ProxyAuthenticationRequired_407 = 407,
  412. RequestTimeout_408 = 408,
  413. Conflict_409 = 409,
  414. Gone_410 = 410,
  415. LengthRequired_411 = 411,
  416. PreconditionFailed_412 = 412,
  417. PayloadTooLarge_413 = 413,
  418. UriTooLong_414 = 414,
  419. UnsupportedMediaType_415 = 415,
  420. RangeNotSatisfiable_416 = 416,
  421. ExpectationFailed_417 = 417,
  422. ImATeapot_418 = 418,
  423. MisdirectedRequest_421 = 421,
  424. UnprocessableContent_422 = 422,
  425. Locked_423 = 423,
  426. FailedDependency_424 = 424,
  427. TooEarly_425 = 425,
  428. UpgradeRequired_426 = 426,
  429. PreconditionRequired_428 = 428,
  430. TooManyRequests_429 = 429,
  431. RequestHeaderFieldsTooLarge_431 = 431,
  432. UnavailableForLegalReasons_451 = 451,
  433. // Server error responses
  434. InternalServerError_500 = 500,
  435. NotImplemented_501 = 501,
  436. BadGateway_502 = 502,
  437. ServiceUnavailable_503 = 503,
  438. GatewayTimeout_504 = 504,
  439. HttpVersionNotSupported_505 = 505,
  440. VariantAlsoNegotiates_506 = 506,
  441. InsufficientStorage_507 = 507,
  442. LoopDetected_508 = 508,
  443. NotExtended_510 = 510,
  444. NetworkAuthenticationRequired_511 = 511,
  445. };
  446. using Headers =
  447. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  448. detail::case_ignore::equal_to>;
  449. using Params = std::multimap<std::string, std::string>;
  450. using Match = std::smatch;
  451. using DownloadProgress = std::function<bool(uint64_t current, uint64_t total)>;
  452. using UploadProgress = std::function<bool(uint64_t current, uint64_t total)>;
  453. struct Response;
  454. using ResponseHandler = std::function<bool(const Response &response)>;
  455. struct MultipartFormData {
  456. std::string name;
  457. std::string content;
  458. std::string filename;
  459. std::string content_type;
  460. Headers headers;
  461. };
  462. using MultipartFormDataItems = std::vector<MultipartFormData>;
  463. using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
  464. struct MultipartFormDataForClientInput {
  465. std::string name;
  466. std::string content;
  467. std::string filename;
  468. std::string content_type;
  469. };
  470. using MultipartFormDataItemsForClientInput =
  471. std::vector<MultipartFormDataForClientInput>;
  472. class DataSink {
  473. public:
  474. DataSink() : os(&sb_), sb_(*this) {}
  475. DataSink(const DataSink &) = delete;
  476. DataSink &operator=(const DataSink &) = delete;
  477. DataSink(DataSink &&) = delete;
  478. DataSink &operator=(DataSink &&) = delete;
  479. std::function<bool(const char *data, size_t data_len)> write;
  480. std::function<bool()> is_writable;
  481. std::function<void()> done;
  482. std::function<void(const Headers &trailer)> done_with_trailer;
  483. std::ostream os;
  484. private:
  485. class data_sink_streambuf final : public std::streambuf {
  486. public:
  487. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  488. protected:
  489. std::streamsize xsputn(const char *s, std::streamsize n) override {
  490. sink_.write(s, static_cast<size_t>(n));
  491. return n;
  492. }
  493. private:
  494. DataSink &sink_;
  495. };
  496. data_sink_streambuf sb_;
  497. };
  498. using ContentProvider =
  499. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  500. using ContentProviderWithoutLength =
  501. std::function<bool(size_t offset, DataSink &sink)>;
  502. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  503. struct MultipartFormDataProvider {
  504. std::string name;
  505. ContentProviderWithoutLength provider;
  506. std::string filename;
  507. std::string content_type;
  508. };
  509. using MultipartFormDataProviderItems = std::vector<MultipartFormDataProvider>;
  510. using ContentReceiverWithProgress =
  511. std::function<bool(const char *data, size_t data_length, uint64_t offset,
  512. uint64_t total_length)>;
  513. using ContentReceiver =
  514. std::function<bool(const char *data, size_t data_length)>;
  515. using MultipartContentHeader =
  516. std::function<bool(const MultipartFormData &file)>;
  517. class ContentReader {
  518. public:
  519. using Reader = std::function<bool(ContentReceiver receiver)>;
  520. using MultipartReader = std::function<bool(MultipartContentHeader header,
  521. ContentReceiver receiver)>;
  522. ContentReader(Reader reader, MultipartReader multipart_reader)
  523. : reader_(std::move(reader)),
  524. multipart_reader_(std::move(multipart_reader)) {}
  525. bool operator()(MultipartContentHeader header,
  526. ContentReceiver receiver) const {
  527. return multipart_reader_(std::move(header), std::move(receiver));
  528. }
  529. bool operator()(ContentReceiver receiver) const {
  530. return reader_(std::move(receiver));
  531. }
  532. Reader reader_;
  533. MultipartReader multipart_reader_;
  534. };
  535. using Range = std::pair<ssize_t, ssize_t>;
  536. using Ranges = std::vector<Range>;
  537. struct Request {
  538. std::string method;
  539. std::string path;
  540. std::string matched_route;
  541. Params params;
  542. Headers headers;
  543. std::string body;
  544. std::string remote_addr;
  545. int remote_port = -1;
  546. std::string local_addr;
  547. int local_port = -1;
  548. // for server
  549. std::string version;
  550. std::string target;
  551. MultipartFormDataMap files;
  552. Ranges ranges;
  553. Match matches;
  554. std::unordered_map<std::string, std::string> path_params;
  555. std::function<bool()> is_connection_closed = []() { return true; };
  556. // for client
  557. std::vector<std::string> accept_content_types;
  558. ResponseHandler response_handler;
  559. ContentReceiverWithProgress content_receiver;
  560. DownloadProgress download_progress;
  561. UploadProgress upload_progress;
  562. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  563. const SSL *ssl = nullptr;
  564. #endif
  565. bool has_header(const std::string &key) const;
  566. std::string get_header_value(const std::string &key, const char *def = "",
  567. size_t id = 0) const;
  568. uint64_t get_header_value_u64(const std::string &key, uint64_t def = 0,
  569. size_t id = 0) const;
  570. size_t get_header_value_count(const std::string &key) const;
  571. void set_header(const std::string &key, const std::string &val);
  572. bool has_param(const std::string &key) const;
  573. std::string get_param_value(const std::string &key, size_t id = 0) const;
  574. size_t get_param_value_count(const std::string &key) const;
  575. bool is_multipart_form_data() const;
  576. bool has_file(const std::string &key) const;
  577. MultipartFormData get_file_value(const std::string &key) const;
  578. std::vector<MultipartFormData> get_file_values(const std::string &key) const;
  579. // private members...
  580. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  581. size_t content_length_ = 0;
  582. ContentProvider content_provider_;
  583. bool is_chunked_content_provider_ = false;
  584. size_t authorization_count_ = 0;
  585. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  586. (std::chrono::steady_clock::time_point::min)();
  587. };
  588. struct Response {
  589. std::string version;
  590. int status = -1;
  591. std::string reason;
  592. Headers headers;
  593. std::string body;
  594. std::string location; // Redirect location
  595. bool has_header(const std::string &key) const;
  596. std::string get_header_value(const std::string &key, const char *def = "",
  597. size_t id = 0) const;
  598. uint64_t get_header_value_u64(const std::string &key, uint64_t def = 0,
  599. size_t id = 0) const;
  600. size_t get_header_value_count(const std::string &key) const;
  601. void set_header(const std::string &key, const std::string &val);
  602. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  603. void set_content(const char *s, size_t n, const std::string &content_type);
  604. void set_content(const std::string &s, const std::string &content_type);
  605. void set_content(std::string &&s, const std::string &content_type);
  606. void set_content_provider(
  607. size_t length, const std::string &content_type, ContentProvider provider,
  608. ContentProviderResourceReleaser resource_releaser = nullptr);
  609. void set_content_provider(
  610. const std::string &content_type, ContentProviderWithoutLength provider,
  611. ContentProviderResourceReleaser resource_releaser = nullptr);
  612. void set_chunked_content_provider(
  613. const std::string &content_type, ContentProviderWithoutLength provider,
  614. ContentProviderResourceReleaser resource_releaser = nullptr);
  615. void set_file_content(const std::string &path,
  616. const std::string &content_type);
  617. void set_file_content(const std::string &path);
  618. Response() = default;
  619. Response(const Response &) = default;
  620. Response &operator=(const Response &) = default;
  621. Response(Response &&) = default;
  622. Response &operator=(Response &&) = default;
  623. ~Response() {
  624. if (content_provider_resource_releaser_) {
  625. content_provider_resource_releaser_(content_provider_success_);
  626. }
  627. }
  628. // private members...
  629. size_t content_length_ = 0;
  630. ContentProvider content_provider_;
  631. ContentProviderResourceReleaser content_provider_resource_releaser_;
  632. bool is_chunked_content_provider_ = false;
  633. bool content_provider_success_ = false;
  634. std::string file_content_path_;
  635. std::string file_content_content_type_;
  636. };
  637. class Stream {
  638. public:
  639. virtual ~Stream() = default;
  640. virtual bool is_readable() const = 0;
  641. virtual bool wait_readable() const = 0;
  642. virtual bool wait_writable() const = 0;
  643. virtual ssize_t read(char *ptr, size_t size) = 0;
  644. virtual ssize_t write(const char *ptr, size_t size) = 0;
  645. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  646. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  647. virtual socket_t socket() const = 0;
  648. virtual time_t duration() const = 0;
  649. ssize_t write(const char *ptr);
  650. ssize_t write(const std::string &s);
  651. };
  652. class TaskQueue {
  653. public:
  654. TaskQueue() = default;
  655. virtual ~TaskQueue() = default;
  656. virtual bool enqueue(std::function<void()> fn) = 0;
  657. virtual void shutdown() = 0;
  658. virtual void on_idle() {}
  659. };
  660. class ThreadPool final : public TaskQueue {
  661. public:
  662. explicit ThreadPool(size_t n, size_t mqr = 0)
  663. : shutdown_(false), max_queued_requests_(mqr) {
  664. while (n) {
  665. threads_.emplace_back(worker(*this));
  666. n--;
  667. }
  668. }
  669. ThreadPool(const ThreadPool &) = delete;
  670. ~ThreadPool() override = default;
  671. bool enqueue(std::function<void()> fn) override {
  672. {
  673. std::unique_lock<std::mutex> lock(mutex_);
  674. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  675. return false;
  676. }
  677. jobs_.push_back(std::move(fn));
  678. }
  679. cond_.notify_one();
  680. return true;
  681. }
  682. void shutdown() override {
  683. // Stop all worker threads...
  684. {
  685. std::unique_lock<std::mutex> lock(mutex_);
  686. shutdown_ = true;
  687. }
  688. cond_.notify_all();
  689. // Join...
  690. for (auto &t : threads_) {
  691. t.join();
  692. }
  693. }
  694. private:
  695. struct worker {
  696. explicit worker(ThreadPool &pool) : pool_(pool) {}
  697. void operator()() {
  698. for (;;) {
  699. std::function<void()> fn;
  700. {
  701. std::unique_lock<std::mutex> lock(pool_.mutex_);
  702. pool_.cond_.wait(
  703. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  704. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  705. fn = pool_.jobs_.front();
  706. pool_.jobs_.pop_front();
  707. }
  708. assert(true == static_cast<bool>(fn));
  709. fn();
  710. }
  711. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  712. !defined(LIBRESSL_VERSION_NUMBER)
  713. OPENSSL_thread_stop();
  714. #endif
  715. }
  716. ThreadPool &pool_;
  717. };
  718. friend struct worker;
  719. std::vector<std::thread> threads_;
  720. std::list<std::function<void()>> jobs_;
  721. bool shutdown_;
  722. size_t max_queued_requests_ = 0;
  723. std::condition_variable cond_;
  724. std::mutex mutex_;
  725. };
  726. using Logger = std::function<void(const Request &, const Response &)>;
  727. using SocketOptions = std::function<void(socket_t sock)>;
  728. namespace detail {
  729. bool set_socket_opt_impl(socket_t sock, int level, int optname,
  730. const void *optval, socklen_t optlen);
  731. bool set_socket_opt(socket_t sock, int level, int optname, int opt);
  732. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  733. time_t usec);
  734. } // namespace detail
  735. void default_socket_options(socket_t sock);
  736. const char *status_message(int status);
  737. std::string get_bearer_token_auth(const Request &req);
  738. namespace detail {
  739. class MatcherBase {
  740. public:
  741. MatcherBase(std::string pattern) : pattern_(pattern) {}
  742. virtual ~MatcherBase() = default;
  743. const std::string &pattern() const { return pattern_; }
  744. // Match request path and populate its matches and
  745. virtual bool match(Request &request) const = 0;
  746. private:
  747. std::string pattern_;
  748. };
  749. /**
  750. * Captures parameters in request path and stores them in Request::path_params
  751. *
  752. * Capture name is a substring of a pattern from : to /.
  753. * The rest of the pattern is matched against the request path directly
  754. * Parameters are captured starting from the next character after
  755. * the end of the last matched static pattern fragment until the next /.
  756. *
  757. * Example pattern:
  758. * "/path/fragments/:capture/more/fragments/:second_capture"
  759. * Static fragments:
  760. * "/path/fragments/", "more/fragments/"
  761. *
  762. * Given the following request path:
  763. * "/path/fragments/:1/more/fragments/:2"
  764. * the resulting capture will be
  765. * {{"capture", "1"}, {"second_capture", "2"}}
  766. */
  767. class PathParamsMatcher final : public MatcherBase {
  768. public:
  769. PathParamsMatcher(const std::string &pattern);
  770. bool match(Request &request) const override;
  771. private:
  772. // Treat segment separators as the end of path parameter capture
  773. // Does not need to handle query parameters as they are parsed before path
  774. // matching
  775. static constexpr char separator = '/';
  776. // Contains static path fragments to match against, excluding the '/' after
  777. // path params
  778. // Fragments are separated by path params
  779. std::vector<std::string> static_fragments_;
  780. // Stores the names of the path parameters to be used as keys in the
  781. // Request::path_params map
  782. std::vector<std::string> param_names_;
  783. };
  784. /**
  785. * Performs std::regex_match on request path
  786. * and stores the result in Request::matches
  787. *
  788. * Note that regex match is performed directly on the whole request.
  789. * This means that wildcard patterns may match multiple path segments with /:
  790. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  791. */
  792. class RegexMatcher final : public MatcherBase {
  793. public:
  794. RegexMatcher(const std::string &pattern)
  795. : MatcherBase(pattern), regex_(pattern) {}
  796. bool match(Request &request) const override;
  797. private:
  798. std::regex regex_;
  799. };
  800. ssize_t write_headers(Stream &strm, const Headers &headers);
  801. } // namespace detail
  802. class Server {
  803. public:
  804. using Handler = std::function<void(const Request &, Response &)>;
  805. using ExceptionHandler =
  806. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  807. enum class HandlerResponse {
  808. Handled,
  809. Unhandled,
  810. };
  811. using HandlerWithResponse =
  812. std::function<HandlerResponse(const Request &, Response &)>;
  813. using HandlerWithContentReader = std::function<void(
  814. const Request &, Response &, const ContentReader &content_reader)>;
  815. using Expect100ContinueHandler =
  816. std::function<int(const Request &, Response &)>;
  817. Server();
  818. virtual ~Server();
  819. virtual bool is_valid() const;
  820. Server &Get(const std::string &pattern, Handler handler);
  821. Server &Post(const std::string &pattern, Handler handler);
  822. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  823. Server &Put(const std::string &pattern, Handler handler);
  824. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  825. Server &Patch(const std::string &pattern, Handler handler);
  826. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  827. Server &Delete(const std::string &pattern, Handler handler);
  828. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  829. Server &Options(const std::string &pattern, Handler handler);
  830. bool set_base_dir(const std::string &dir,
  831. const std::string &mount_point = std::string());
  832. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  833. Headers headers = Headers());
  834. bool remove_mount_point(const std::string &mount_point);
  835. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  836. const std::string &mime);
  837. Server &set_default_file_mimetype(const std::string &mime);
  838. Server &set_file_request_handler(Handler handler);
  839. template <class ErrorHandlerFunc>
  840. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  841. return set_error_handler_core(
  842. std::forward<ErrorHandlerFunc>(handler),
  843. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  844. }
  845. Server &set_exception_handler(ExceptionHandler handler);
  846. Server &set_pre_routing_handler(HandlerWithResponse handler);
  847. Server &set_post_routing_handler(Handler handler);
  848. Server &set_pre_request_handler(HandlerWithResponse handler);
  849. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  850. Server &set_logger(Logger logger);
  851. Server &set_address_family(int family);
  852. Server &set_tcp_nodelay(bool on);
  853. Server &set_ipv6_v6only(bool on);
  854. Server &set_socket_options(SocketOptions socket_options);
  855. Server &set_default_headers(Headers headers);
  856. Server &
  857. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  858. Server &set_keep_alive_max_count(size_t count);
  859. Server &set_keep_alive_timeout(time_t sec);
  860. Server &set_read_timeout(time_t sec, time_t usec = 0);
  861. template <class Rep, class Period>
  862. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  863. Server &set_write_timeout(time_t sec, time_t usec = 0);
  864. template <class Rep, class Period>
  865. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  866. Server &set_idle_interval(time_t sec, time_t usec = 0);
  867. template <class Rep, class Period>
  868. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  869. Server &set_payload_max_length(size_t length);
  870. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  871. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  872. bool listen_after_bind();
  873. bool listen(const std::string &host, int port, int socket_flags = 0);
  874. bool is_running() const;
  875. void wait_until_ready() const;
  876. void stop();
  877. void decommission();
  878. std::function<TaskQueue *(void)> new_task_queue;
  879. protected:
  880. bool process_request(Stream &strm, const std::string &remote_addr,
  881. int remote_port, const std::string &local_addr,
  882. int local_port, bool close_connection,
  883. bool &connection_closed,
  884. const std::function<void(Request &)> &setup_request);
  885. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  886. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  887. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  888. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  889. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  890. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  891. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  892. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  893. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  894. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  895. private:
  896. using Handlers =
  897. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  898. using HandlersForContentReader =
  899. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  900. HandlerWithContentReader>>;
  901. static std::unique_ptr<detail::MatcherBase>
  902. make_matcher(const std::string &pattern);
  903. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  904. Server &set_error_handler_core(Handler handler, std::false_type);
  905. socket_t create_server_socket(const std::string &host, int port,
  906. int socket_flags,
  907. SocketOptions socket_options) const;
  908. int bind_internal(const std::string &host, int port, int socket_flags);
  909. bool listen_internal();
  910. bool routing(Request &req, Response &res, Stream &strm);
  911. bool handle_file_request(const Request &req, Response &res);
  912. bool dispatch_request(Request &req, Response &res,
  913. const Handlers &handlers) const;
  914. bool dispatch_request_for_content_reader(
  915. Request &req, Response &res, ContentReader content_reader,
  916. const HandlersForContentReader &handlers) const;
  917. bool parse_request_line(const char *s, Request &req) const;
  918. void apply_ranges(const Request &req, Response &res,
  919. std::string &content_type, std::string &boundary) const;
  920. bool write_response(Stream &strm, bool close_connection, Request &req,
  921. Response &res);
  922. bool write_response_with_content(Stream &strm, bool close_connection,
  923. const Request &req, Response &res);
  924. bool write_response_core(Stream &strm, bool close_connection,
  925. const Request &req, Response &res,
  926. bool need_apply_ranges);
  927. bool write_content_with_provider(Stream &strm, const Request &req,
  928. Response &res, const std::string &boundary,
  929. const std::string &content_type);
  930. bool read_content(Stream &strm, Request &req, Response &res);
  931. bool
  932. read_content_with_content_receiver(Stream &strm, Request &req, Response &res,
  933. ContentReceiver receiver,
  934. MultipartContentHeader multipart_header,
  935. ContentReceiver multipart_receiver);
  936. bool read_content_core(Stream &strm, Request &req, Response &res,
  937. ContentReceiver receiver,
  938. MultipartContentHeader multipart_header,
  939. ContentReceiver multipart_receiver) const;
  940. virtual bool process_and_close_socket(socket_t sock);
  941. std::atomic<bool> is_running_{false};
  942. std::atomic<bool> is_decommissioned{false};
  943. struct MountPointEntry {
  944. std::string mount_point;
  945. std::string base_dir;
  946. Headers headers;
  947. };
  948. std::vector<MountPointEntry> base_dirs_;
  949. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  950. std::string default_file_mimetype_ = "application/octet-stream";
  951. Handler file_request_handler_;
  952. Handlers get_handlers_;
  953. Handlers post_handlers_;
  954. HandlersForContentReader post_handlers_for_content_reader_;
  955. Handlers put_handlers_;
  956. HandlersForContentReader put_handlers_for_content_reader_;
  957. Handlers patch_handlers_;
  958. HandlersForContentReader patch_handlers_for_content_reader_;
  959. Handlers delete_handlers_;
  960. HandlersForContentReader delete_handlers_for_content_reader_;
  961. Handlers options_handlers_;
  962. HandlerWithResponse error_handler_;
  963. ExceptionHandler exception_handler_;
  964. HandlerWithResponse pre_routing_handler_;
  965. Handler post_routing_handler_;
  966. HandlerWithResponse pre_request_handler_;
  967. Expect100ContinueHandler expect_100_continue_handler_;
  968. Logger logger_;
  969. int address_family_ = AF_UNSPEC;
  970. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  971. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  972. SocketOptions socket_options_ = default_socket_options;
  973. Headers default_headers_;
  974. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  975. detail::write_headers;
  976. };
  977. enum class Error {
  978. Success = 0,
  979. Unknown,
  980. Connection,
  981. BindIPAddress,
  982. Read,
  983. Write,
  984. ExceedRedirectCount,
  985. Canceled,
  986. SSLConnection,
  987. SSLLoadingCerts,
  988. SSLServerVerification,
  989. SSLServerHostnameVerification,
  990. UnsupportedMultipartBoundaryChars,
  991. Compression,
  992. ConnectionTimeout,
  993. ProxyConnection,
  994. // For internal use only
  995. SSLPeerCouldBeClosed_,
  996. };
  997. std::string to_string(Error error);
  998. std::ostream &operator<<(std::ostream &os, const Error &obj);
  999. class Result {
  1000. public:
  1001. Result() = default;
  1002. Result(std::unique_ptr<Response> &&res, Error err,
  1003. Headers &&request_headers = Headers{})
  1004. : res_(std::move(res)), err_(err),
  1005. request_headers_(std::move(request_headers)) {}
  1006. // Response
  1007. operator bool() const { return res_ != nullptr; }
  1008. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1009. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1010. const Response &value() const { return *res_; }
  1011. Response &value() { return *res_; }
  1012. const Response &operator*() const { return *res_; }
  1013. Response &operator*() { return *res_; }
  1014. const Response *operator->() const { return res_.get(); }
  1015. Response *operator->() { return res_.get(); }
  1016. // Error
  1017. Error error() const { return err_; }
  1018. // Request Headers
  1019. bool has_request_header(const std::string &key) const;
  1020. std::string get_request_header_value(const std::string &key,
  1021. const char *def = "",
  1022. size_t id = 0) const;
  1023. uint64_t get_request_header_value_u64(const std::string &key,
  1024. uint64_t def = 0, size_t id = 0) const;
  1025. size_t get_request_header_value_count(const std::string &key) const;
  1026. private:
  1027. std::unique_ptr<Response> res_;
  1028. Error err_ = Error::Unknown;
  1029. Headers request_headers_;
  1030. };
  1031. class ClientImpl {
  1032. public:
  1033. explicit ClientImpl(const std::string &host);
  1034. explicit ClientImpl(const std::string &host, int port);
  1035. explicit ClientImpl(const std::string &host, int port,
  1036. const std::string &client_cert_path,
  1037. const std::string &client_key_path);
  1038. virtual ~ClientImpl();
  1039. virtual bool is_valid() const;
  1040. // clang-format off
  1041. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1042. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1043. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1044. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1045. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1046. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1047. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1048. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1049. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1050. Result Head(const std::string &path);
  1051. Result Head(const std::string &path, const Headers &headers);
  1052. Result Post(const std::string &path);
  1053. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1054. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1055. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1056. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1057. Result Post(const std::string &path, const Params &params);
  1058. Result Post(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1059. Result Post(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1060. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1061. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1062. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1063. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1064. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1065. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1066. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1067. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1068. Result Put(const std::string &path);
  1069. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1070. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1071. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1072. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1073. Result Put(const std::string &path, const Params &params);
  1074. Result Put(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1075. Result Put(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1076. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1077. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1078. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1079. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1080. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1081. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1082. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1083. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1084. Result Patch(const std::string &path);
  1085. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1086. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1087. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1088. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1089. Result Patch(const std::string &path, const Params &params);
  1090. Result Patch(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1091. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1092. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1093. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1094. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1095. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1096. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1097. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1098. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1099. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1100. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1101. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1102. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1103. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1104. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1105. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1106. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1107. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1108. Result Options(const std::string &path);
  1109. Result Options(const std::string &path, const Headers &headers);
  1110. // clang-format on
  1111. bool send(Request &req, Response &res, Error &error);
  1112. Result send(const Request &req);
  1113. void stop();
  1114. std::string host() const;
  1115. int port() const;
  1116. size_t is_socket_open() const;
  1117. socket_t socket() const;
  1118. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1119. void set_default_headers(Headers headers);
  1120. void
  1121. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1122. void set_address_family(int family);
  1123. void set_tcp_nodelay(bool on);
  1124. void set_ipv6_v6only(bool on);
  1125. void set_socket_options(SocketOptions socket_options);
  1126. void set_connection_timeout(time_t sec, time_t usec = 0);
  1127. template <class Rep, class Period>
  1128. void
  1129. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1130. void set_read_timeout(time_t sec, time_t usec = 0);
  1131. template <class Rep, class Period>
  1132. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1133. void set_write_timeout(time_t sec, time_t usec = 0);
  1134. template <class Rep, class Period>
  1135. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1136. void set_max_timeout(time_t msec);
  1137. template <class Rep, class Period>
  1138. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1139. void set_basic_auth(const std::string &username, const std::string &password);
  1140. void set_bearer_token_auth(const std::string &token);
  1141. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1142. void set_digest_auth(const std::string &username,
  1143. const std::string &password);
  1144. #endif
  1145. void set_keep_alive(bool on);
  1146. void set_follow_location(bool on);
  1147. void set_url_encode(bool on);
  1148. void set_compress(bool on);
  1149. void set_decompress(bool on);
  1150. void set_interface(const std::string &intf);
  1151. void set_proxy(const std::string &host, int port);
  1152. void set_proxy_basic_auth(const std::string &username,
  1153. const std::string &password);
  1154. void set_proxy_bearer_token_auth(const std::string &token);
  1155. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1156. void set_proxy_digest_auth(const std::string &username,
  1157. const std::string &password);
  1158. #endif
  1159. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1160. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1161. const std::string &ca_cert_dir_path = std::string());
  1162. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1163. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1164. #endif
  1165. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1166. void enable_server_certificate_verification(bool enabled);
  1167. void enable_server_hostname_verification(bool enabled);
  1168. void set_server_certificate_verifier(
  1169. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1170. #endif
  1171. void set_logger(Logger logger);
  1172. protected:
  1173. struct Socket {
  1174. socket_t sock = INVALID_SOCKET;
  1175. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1176. SSL *ssl = nullptr;
  1177. #endif
  1178. bool is_open() const { return sock != INVALID_SOCKET; }
  1179. };
  1180. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1181. // All of:
  1182. // shutdown_ssl
  1183. // shutdown_socket
  1184. // close_socket
  1185. // should ONLY be called when socket_mutex_ is locked.
  1186. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1187. // with a DIFFERENT thread sending requests using that socket.
  1188. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1189. void shutdown_socket(Socket &socket) const;
  1190. void close_socket(Socket &socket);
  1191. bool process_request(Stream &strm, Request &req, Response &res,
  1192. bool close_connection, Error &error);
  1193. bool write_content_with_provider(Stream &strm, const Request &req,
  1194. Error &error) const;
  1195. void copy_settings(const ClientImpl &rhs);
  1196. // Socket endpoint information
  1197. const std::string host_;
  1198. const int port_;
  1199. const std::string host_and_port_;
  1200. // Current open socket
  1201. Socket socket_;
  1202. mutable std::mutex socket_mutex_;
  1203. std::recursive_mutex request_mutex_;
  1204. // These are all protected under socket_mutex
  1205. size_t socket_requests_in_flight_ = 0;
  1206. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1207. bool socket_should_be_closed_when_request_is_done_ = false;
  1208. // Hostname-IP map
  1209. std::map<std::string, std::string> addr_map_;
  1210. // Default headers
  1211. Headers default_headers_;
  1212. // Header writer
  1213. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1214. detail::write_headers;
  1215. // Settings
  1216. std::string client_cert_path_;
  1217. std::string client_key_path_;
  1218. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1219. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1220. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1221. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1222. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1223. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1224. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1225. std::string basic_auth_username_;
  1226. std::string basic_auth_password_;
  1227. std::string bearer_token_auth_token_;
  1228. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1229. std::string digest_auth_username_;
  1230. std::string digest_auth_password_;
  1231. #endif
  1232. bool keep_alive_ = false;
  1233. bool follow_location_ = false;
  1234. bool url_encode_ = true;
  1235. int address_family_ = AF_UNSPEC;
  1236. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1237. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1238. SocketOptions socket_options_ = nullptr;
  1239. bool compress_ = false;
  1240. bool decompress_ = true;
  1241. std::string interface_;
  1242. std::string proxy_host_;
  1243. int proxy_port_ = -1;
  1244. std::string proxy_basic_auth_username_;
  1245. std::string proxy_basic_auth_password_;
  1246. std::string proxy_bearer_token_auth_token_;
  1247. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1248. std::string proxy_digest_auth_username_;
  1249. std::string proxy_digest_auth_password_;
  1250. #endif
  1251. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1252. std::string ca_cert_file_path_;
  1253. std::string ca_cert_dir_path_;
  1254. X509_STORE *ca_cert_store_ = nullptr;
  1255. #endif
  1256. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1257. bool server_certificate_verification_ = true;
  1258. bool server_hostname_verification_ = true;
  1259. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1260. #endif
  1261. Logger logger_;
  1262. private:
  1263. bool send_(Request &req, Response &res, Error &error);
  1264. Result send_(Request &&req);
  1265. socket_t create_client_socket(Error &error) const;
  1266. bool read_response_line(Stream &strm, const Request &req,
  1267. Response &res) const;
  1268. bool write_request(Stream &strm, Request &req, bool close_connection,
  1269. Error &error);
  1270. bool redirect(Request &req, Response &res, Error &error);
  1271. bool create_redirect_client(const std::string &scheme,
  1272. const std::string &host, int port, Request &req,
  1273. Response &res, const std::string &path,
  1274. const std::string &location, Error &error);
  1275. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1276. bool handle_request(Stream &strm, Request &req, Response &res,
  1277. bool close_connection, Error &error);
  1278. std::unique_ptr<Response> send_with_content_provider(
  1279. Request &req, const char *body, size_t content_length,
  1280. ContentProvider content_provider,
  1281. ContentProviderWithoutLength content_provider_without_length,
  1282. const std::string &content_type, Error &error);
  1283. Result send_with_content_provider(
  1284. const std::string &method, const std::string &path,
  1285. const Headers &headers, const char *body, size_t content_length,
  1286. ContentProvider content_provider,
  1287. ContentProviderWithoutLength content_provider_without_length,
  1288. const std::string &content_type, UploadProgress progress);
  1289. ContentProviderWithoutLength get_multipart_content_provider(
  1290. const std::string &boundary,
  1291. const MultipartFormDataItemsForClientInput &items,
  1292. const MultipartFormDataProviderItems &provider_items) const;
  1293. std::string adjust_host_string(const std::string &host) const;
  1294. virtual bool
  1295. process_socket(const Socket &socket,
  1296. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1297. std::function<bool(Stream &strm)> callback);
  1298. virtual bool is_ssl() const;
  1299. };
  1300. class Client {
  1301. public:
  1302. // Universal interface
  1303. explicit Client(const std::string &scheme_host_port);
  1304. explicit Client(const std::string &scheme_host_port,
  1305. const std::string &client_cert_path,
  1306. const std::string &client_key_path);
  1307. // HTTP only interface
  1308. explicit Client(const std::string &host, int port);
  1309. explicit Client(const std::string &host, int port,
  1310. const std::string &client_cert_path,
  1311. const std::string &client_key_path);
  1312. Client(Client &&) = default;
  1313. Client &operator=(Client &&) = default;
  1314. ~Client();
  1315. bool is_valid() const;
  1316. // clang-format off
  1317. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1318. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1319. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1320. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1321. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1322. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1323. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1324. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1325. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1326. Result Head(const std::string &path);
  1327. Result Head(const std::string &path, const Headers &headers);
  1328. Result Post(const std::string &path);
  1329. Result Post(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1330. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1331. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1332. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1333. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1334. Result Post(const std::string &path, const Params &params);
  1335. Result Post(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1336. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1337. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1338. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1339. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1340. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1341. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1342. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1343. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1344. Result Put(const std::string &path);
  1345. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1346. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1347. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1348. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1349. Result Put(const std::string &path, const Params &params);
  1350. Result Put(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1351. Result Put(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1352. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1353. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1354. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1355. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1356. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1357. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1358. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1359. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1360. Result Patch(const std::string &path);
  1361. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1362. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1363. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1364. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1365. Result Patch(const std::string &path, const Params &params);
  1366. Result Patch(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1367. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1368. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1369. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1370. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1371. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1372. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1373. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1374. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1375. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1376. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1377. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1378. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1379. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1380. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1381. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1382. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1383. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1384. Result Options(const std::string &path);
  1385. Result Options(const std::string &path, const Headers &headers);
  1386. // clang-format on
  1387. bool send(Request &req, Response &res, Error &error);
  1388. Result send(const Request &req);
  1389. void stop();
  1390. std::string host() const;
  1391. int port() const;
  1392. size_t is_socket_open() const;
  1393. socket_t socket() const;
  1394. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1395. void set_default_headers(Headers headers);
  1396. void
  1397. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1398. void set_address_family(int family);
  1399. void set_tcp_nodelay(bool on);
  1400. void set_socket_options(SocketOptions socket_options);
  1401. void set_connection_timeout(time_t sec, time_t usec = 0);
  1402. template <class Rep, class Period>
  1403. void
  1404. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1405. void set_read_timeout(time_t sec, time_t usec = 0);
  1406. template <class Rep, class Period>
  1407. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1408. void set_write_timeout(time_t sec, time_t usec = 0);
  1409. template <class Rep, class Period>
  1410. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1411. void set_max_timeout(time_t msec);
  1412. template <class Rep, class Period>
  1413. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1414. void set_basic_auth(const std::string &username, const std::string &password);
  1415. void set_bearer_token_auth(const std::string &token);
  1416. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1417. void set_digest_auth(const std::string &username,
  1418. const std::string &password);
  1419. #endif
  1420. void set_keep_alive(bool on);
  1421. void set_follow_location(bool on);
  1422. void set_url_encode(bool on);
  1423. void set_compress(bool on);
  1424. void set_decompress(bool on);
  1425. void set_interface(const std::string &intf);
  1426. void set_proxy(const std::string &host, int port);
  1427. void set_proxy_basic_auth(const std::string &username,
  1428. const std::string &password);
  1429. void set_proxy_bearer_token_auth(const std::string &token);
  1430. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1431. void set_proxy_digest_auth(const std::string &username,
  1432. const std::string &password);
  1433. #endif
  1434. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1435. void enable_server_certificate_verification(bool enabled);
  1436. void enable_server_hostname_verification(bool enabled);
  1437. void set_server_certificate_verifier(
  1438. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1439. #endif
  1440. void set_logger(Logger logger);
  1441. // SSL
  1442. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1443. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1444. const std::string &ca_cert_dir_path = std::string());
  1445. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1446. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1447. long get_openssl_verify_result() const;
  1448. SSL_CTX *ssl_context() const;
  1449. #endif
  1450. private:
  1451. std::unique_ptr<ClientImpl> cli_;
  1452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1453. bool is_ssl_ = false;
  1454. #endif
  1455. };
  1456. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1457. class SSLServer : public Server {
  1458. public:
  1459. SSLServer(const char *cert_path, const char *private_key_path,
  1460. const char *client_ca_cert_file_path = nullptr,
  1461. const char *client_ca_cert_dir_path = nullptr,
  1462. const char *private_key_password = nullptr);
  1463. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1464. X509_STORE *client_ca_cert_store = nullptr);
  1465. SSLServer(
  1466. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1467. ~SSLServer() override;
  1468. bool is_valid() const override;
  1469. SSL_CTX *ssl_context() const;
  1470. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1471. X509_STORE *client_ca_cert_store = nullptr);
  1472. private:
  1473. bool process_and_close_socket(socket_t sock) override;
  1474. SSL_CTX *ctx_;
  1475. std::mutex ctx_mutex_;
  1476. };
  1477. class SSLClient final : public ClientImpl {
  1478. public:
  1479. explicit SSLClient(const std::string &host);
  1480. explicit SSLClient(const std::string &host, int port);
  1481. explicit SSLClient(const std::string &host, int port,
  1482. const std::string &client_cert_path,
  1483. const std::string &client_key_path,
  1484. const std::string &private_key_password = std::string());
  1485. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1486. EVP_PKEY *client_key,
  1487. const std::string &private_key_password = std::string());
  1488. ~SSLClient() override;
  1489. bool is_valid() const override;
  1490. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1491. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1492. long get_openssl_verify_result() const;
  1493. SSL_CTX *ssl_context() const;
  1494. private:
  1495. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1496. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1497. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1498. bool
  1499. process_socket(const Socket &socket,
  1500. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1501. std::function<bool(Stream &strm)> callback) override;
  1502. bool is_ssl() const override;
  1503. bool connect_with_proxy(
  1504. Socket &sock,
  1505. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1506. Response &res, bool &success, Error &error);
  1507. bool initialize_ssl(Socket &socket, Error &error);
  1508. bool load_certs();
  1509. bool verify_host(X509 *server_cert) const;
  1510. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1511. bool verify_host_with_common_name(X509 *server_cert) const;
  1512. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1513. SSL_CTX *ctx_;
  1514. std::mutex ctx_mutex_;
  1515. std::once_flag initialize_cert_;
  1516. std::vector<std::string> host_components_;
  1517. long verify_result_ = 0;
  1518. friend class ClientImpl;
  1519. };
  1520. #endif
  1521. /*
  1522. * Implementation of template methods.
  1523. */
  1524. namespace detail {
  1525. template <typename T, typename U>
  1526. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1527. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1528. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1529. duration - std::chrono::seconds(sec))
  1530. .count();
  1531. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1532. }
  1533. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1534. return N - 1;
  1535. }
  1536. inline bool is_numeric(const std::string &str) {
  1537. return !str.empty() &&
  1538. std::all_of(str.cbegin(), str.cend(),
  1539. [](unsigned char c) { return std::isdigit(c); });
  1540. }
  1541. inline uint64_t get_header_value_u64(const Headers &headers,
  1542. const std::string &key, uint64_t def,
  1543. size_t id, bool &is_invalid_value) {
  1544. is_invalid_value = false;
  1545. auto rng = headers.equal_range(key);
  1546. auto it = rng.first;
  1547. std::advance(it, static_cast<ssize_t>(id));
  1548. if (it != rng.second) {
  1549. if (is_numeric(it->second)) {
  1550. return std::strtoull(it->second.data(), nullptr, 10);
  1551. } else {
  1552. is_invalid_value = true;
  1553. }
  1554. }
  1555. return def;
  1556. }
  1557. inline uint64_t get_header_value_u64(const Headers &headers,
  1558. const std::string &key, uint64_t def,
  1559. size_t id) {
  1560. bool dummy = false;
  1561. return get_header_value_u64(headers, key, def, id, dummy);
  1562. }
  1563. } // namespace detail
  1564. inline uint64_t Request::get_header_value_u64(const std::string &key,
  1565. uint64_t def, size_t id) const {
  1566. return detail::get_header_value_u64(headers, key, def, id);
  1567. }
  1568. inline uint64_t Response::get_header_value_u64(const std::string &key,
  1569. uint64_t def, size_t id) const {
  1570. return detail::get_header_value_u64(headers, key, def, id);
  1571. }
  1572. namespace detail {
  1573. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1574. const void *optval, socklen_t optlen) {
  1575. return setsockopt(sock, level, optname,
  1576. #ifdef _WIN32
  1577. reinterpret_cast<const char *>(optval),
  1578. #else
  1579. optval,
  1580. #endif
  1581. optlen) == 0;
  1582. }
  1583. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1584. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1585. }
  1586. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1587. time_t sec, time_t usec) {
  1588. #ifdef _WIN32
  1589. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1590. #else
  1591. timeval timeout;
  1592. timeout.tv_sec = static_cast<long>(sec);
  1593. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1594. #endif
  1595. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  1596. }
  1597. } // namespace detail
  1598. inline void default_socket_options(socket_t sock) {
  1599. detail::set_socket_opt(sock, SOL_SOCKET,
  1600. #ifdef SO_REUSEPORT
  1601. SO_REUSEPORT,
  1602. #else
  1603. SO_REUSEADDR,
  1604. #endif
  1605. 1);
  1606. }
  1607. inline const char *status_message(int status) {
  1608. switch (status) {
  1609. case StatusCode::Continue_100: return "Continue";
  1610. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  1611. case StatusCode::Processing_102: return "Processing";
  1612. case StatusCode::EarlyHints_103: return "Early Hints";
  1613. case StatusCode::OK_200: return "OK";
  1614. case StatusCode::Created_201: return "Created";
  1615. case StatusCode::Accepted_202: return "Accepted";
  1616. case StatusCode::NonAuthoritativeInformation_203:
  1617. return "Non-Authoritative Information";
  1618. case StatusCode::NoContent_204: return "No Content";
  1619. case StatusCode::ResetContent_205: return "Reset Content";
  1620. case StatusCode::PartialContent_206: return "Partial Content";
  1621. case StatusCode::MultiStatus_207: return "Multi-Status";
  1622. case StatusCode::AlreadyReported_208: return "Already Reported";
  1623. case StatusCode::IMUsed_226: return "IM Used";
  1624. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  1625. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  1626. case StatusCode::Found_302: return "Found";
  1627. case StatusCode::SeeOther_303: return "See Other";
  1628. case StatusCode::NotModified_304: return "Not Modified";
  1629. case StatusCode::UseProxy_305: return "Use Proxy";
  1630. case StatusCode::unused_306: return "unused";
  1631. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  1632. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  1633. case StatusCode::BadRequest_400: return "Bad Request";
  1634. case StatusCode::Unauthorized_401: return "Unauthorized";
  1635. case StatusCode::PaymentRequired_402: return "Payment Required";
  1636. case StatusCode::Forbidden_403: return "Forbidden";
  1637. case StatusCode::NotFound_404: return "Not Found";
  1638. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  1639. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  1640. case StatusCode::ProxyAuthenticationRequired_407:
  1641. return "Proxy Authentication Required";
  1642. case StatusCode::RequestTimeout_408: return "Request Timeout";
  1643. case StatusCode::Conflict_409: return "Conflict";
  1644. case StatusCode::Gone_410: return "Gone";
  1645. case StatusCode::LengthRequired_411: return "Length Required";
  1646. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  1647. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  1648. case StatusCode::UriTooLong_414: return "URI Too Long";
  1649. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  1650. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  1651. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  1652. case StatusCode::ImATeapot_418: return "I'm a teapot";
  1653. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  1654. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  1655. case StatusCode::Locked_423: return "Locked";
  1656. case StatusCode::FailedDependency_424: return "Failed Dependency";
  1657. case StatusCode::TooEarly_425: return "Too Early";
  1658. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  1659. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  1660. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  1661. case StatusCode::RequestHeaderFieldsTooLarge_431:
  1662. return "Request Header Fields Too Large";
  1663. case StatusCode::UnavailableForLegalReasons_451:
  1664. return "Unavailable For Legal Reasons";
  1665. case StatusCode::NotImplemented_501: return "Not Implemented";
  1666. case StatusCode::BadGateway_502: return "Bad Gateway";
  1667. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  1668. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  1669. case StatusCode::HttpVersionNotSupported_505:
  1670. return "HTTP Version Not Supported";
  1671. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  1672. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  1673. case StatusCode::LoopDetected_508: return "Loop Detected";
  1674. case StatusCode::NotExtended_510: return "Not Extended";
  1675. case StatusCode::NetworkAuthenticationRequired_511:
  1676. return "Network Authentication Required";
  1677. default:
  1678. case StatusCode::InternalServerError_500: return "Internal Server Error";
  1679. }
  1680. }
  1681. inline std::string get_bearer_token_auth(const Request &req) {
  1682. if (req.has_header("Authorization")) {
  1683. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  1684. return req.get_header_value("Authorization")
  1685. .substr(bearer_header_prefix_len);
  1686. }
  1687. return "";
  1688. }
  1689. template <class Rep, class Period>
  1690. inline Server &
  1691. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1692. detail::duration_to_sec_and_usec(
  1693. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1694. return *this;
  1695. }
  1696. template <class Rep, class Period>
  1697. inline Server &
  1698. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1699. detail::duration_to_sec_and_usec(
  1700. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1701. return *this;
  1702. }
  1703. template <class Rep, class Period>
  1704. inline Server &
  1705. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  1706. detail::duration_to_sec_and_usec(
  1707. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  1708. return *this;
  1709. }
  1710. inline std::string to_string(const Error error) {
  1711. switch (error) {
  1712. case Error::Success: return "Success (no error)";
  1713. case Error::Connection: return "Could not establish connection";
  1714. case Error::BindIPAddress: return "Failed to bind IP address";
  1715. case Error::Read: return "Failed to read connection";
  1716. case Error::Write: return "Failed to write connection";
  1717. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  1718. case Error::Canceled: return "Connection handling canceled";
  1719. case Error::SSLConnection: return "SSL connection failed";
  1720. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  1721. case Error::SSLServerVerification: return "SSL server verification failed";
  1722. case Error::SSLServerHostnameVerification:
  1723. return "SSL server hostname verification failed";
  1724. case Error::UnsupportedMultipartBoundaryChars:
  1725. return "Unsupported HTTP multipart boundary characters";
  1726. case Error::Compression: return "Compression failed";
  1727. case Error::ConnectionTimeout: return "Connection timed out";
  1728. case Error::ProxyConnection: return "Proxy connection failed";
  1729. case Error::Unknown: return "Unknown";
  1730. default: break;
  1731. }
  1732. return "Invalid";
  1733. }
  1734. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  1735. os << to_string(obj);
  1736. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  1737. return os;
  1738. }
  1739. inline uint64_t Result::get_request_header_value_u64(const std::string &key,
  1740. uint64_t def,
  1741. size_t id) const {
  1742. return detail::get_header_value_u64(request_headers_, key, def, id);
  1743. }
  1744. template <class Rep, class Period>
  1745. inline void ClientImpl::set_connection_timeout(
  1746. const std::chrono::duration<Rep, Period> &duration) {
  1747. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  1748. set_connection_timeout(sec, usec);
  1749. });
  1750. }
  1751. template <class Rep, class Period>
  1752. inline void ClientImpl::set_read_timeout(
  1753. const std::chrono::duration<Rep, Period> &duration) {
  1754. detail::duration_to_sec_and_usec(
  1755. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1756. }
  1757. template <class Rep, class Period>
  1758. inline void ClientImpl::set_write_timeout(
  1759. const std::chrono::duration<Rep, Period> &duration) {
  1760. detail::duration_to_sec_and_usec(
  1761. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1762. }
  1763. template <class Rep, class Period>
  1764. inline void ClientImpl::set_max_timeout(
  1765. const std::chrono::duration<Rep, Period> &duration) {
  1766. auto msec =
  1767. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  1768. set_max_timeout(msec);
  1769. }
  1770. template <class Rep, class Period>
  1771. inline void Client::set_connection_timeout(
  1772. const std::chrono::duration<Rep, Period> &duration) {
  1773. cli_->set_connection_timeout(duration);
  1774. }
  1775. template <class Rep, class Period>
  1776. inline void
  1777. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1778. cli_->set_read_timeout(duration);
  1779. }
  1780. template <class Rep, class Period>
  1781. inline void
  1782. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1783. cli_->set_write_timeout(duration);
  1784. }
  1785. template <class Rep, class Period>
  1786. inline void
  1787. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1788. cli_->set_max_timeout(duration);
  1789. }
  1790. /*
  1791. * Forward declarations and types that will be part of the .h file if split into
  1792. * .h + .cc.
  1793. */
  1794. std::string hosted_at(const std::string &hostname);
  1795. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  1796. std::string append_query_params(const std::string &path, const Params &params);
  1797. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  1798. std::pair<std::string, std::string>
  1799. make_basic_authentication_header(const std::string &username,
  1800. const std::string &password,
  1801. bool is_proxy = false);
  1802. namespace detail {
  1803. #if defined(_WIN32)
  1804. inline std::wstring u8string_to_wstring(const char *s) {
  1805. std::wstring ws;
  1806. auto len = static_cast<int>(strlen(s));
  1807. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  1808. if (wlen > 0) {
  1809. ws.resize(wlen);
  1810. wlen = ::MultiByteToWideChar(
  1811. CP_UTF8, 0, s, len,
  1812. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  1813. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  1814. }
  1815. return ws;
  1816. }
  1817. #endif
  1818. struct FileStat {
  1819. FileStat(const std::string &path);
  1820. bool is_file() const;
  1821. bool is_dir() const;
  1822. private:
  1823. #if defined(_WIN32)
  1824. struct _stat st_;
  1825. #else
  1826. struct stat st_;
  1827. #endif
  1828. int ret_ = -1;
  1829. };
  1830. std::string encode_query_param(const std::string &value);
  1831. std::string decode_url(const std::string &s, bool convert_plus_to_space);
  1832. std::string trim_copy(const std::string &s);
  1833. void divide(
  1834. const char *data, std::size_t size, char d,
  1835. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  1836. fn);
  1837. void divide(
  1838. const std::string &str, char d,
  1839. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  1840. fn);
  1841. void split(const char *b, const char *e, char d,
  1842. std::function<void(const char *, const char *)> fn);
  1843. void split(const char *b, const char *e, char d, size_t m,
  1844. std::function<void(const char *, const char *)> fn);
  1845. bool process_client_socket(
  1846. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  1847. time_t write_timeout_sec, time_t write_timeout_usec,
  1848. time_t max_timeout_msec,
  1849. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1850. std::function<bool(Stream &)> callback);
  1851. socket_t create_client_socket(const std::string &host, const std::string &ip,
  1852. int port, int address_family, bool tcp_nodelay,
  1853. bool ipv6_v6only, SocketOptions socket_options,
  1854. time_t connection_timeout_sec,
  1855. time_t connection_timeout_usec,
  1856. time_t read_timeout_sec, time_t read_timeout_usec,
  1857. time_t write_timeout_sec,
  1858. time_t write_timeout_usec,
  1859. const std::string &intf, Error &error);
  1860. const char *get_header_value(const Headers &headers, const std::string &key,
  1861. const char *def, size_t id);
  1862. std::string params_to_query_str(const Params &params);
  1863. void parse_query_text(const char *data, std::size_t size, Params &params);
  1864. void parse_query_text(const std::string &s, Params &params);
  1865. bool parse_multipart_boundary(const std::string &content_type,
  1866. std::string &boundary);
  1867. bool parse_range_header(const std::string &s, Ranges &ranges);
  1868. bool parse_accept_header(const std::string &s,
  1869. std::vector<std::string> &content_types);
  1870. int close_socket(socket_t sock);
  1871. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  1872. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  1873. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  1874. EncodingType encoding_type(const Request &req, const Response &res);
  1875. class BufferStream final : public Stream {
  1876. public:
  1877. BufferStream() = default;
  1878. ~BufferStream() override = default;
  1879. bool is_readable() const override;
  1880. bool wait_readable() const override;
  1881. bool wait_writable() const override;
  1882. ssize_t read(char *ptr, size_t size) override;
  1883. ssize_t write(const char *ptr, size_t size) override;
  1884. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1885. void get_local_ip_and_port(std::string &ip, int &port) const override;
  1886. socket_t socket() const override;
  1887. time_t duration() const override;
  1888. const std::string &get_buffer() const;
  1889. private:
  1890. std::string buffer;
  1891. size_t position = 0;
  1892. };
  1893. class compressor {
  1894. public:
  1895. virtual ~compressor() = default;
  1896. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1897. virtual bool compress(const char *data, size_t data_length, bool last,
  1898. Callback callback) = 0;
  1899. };
  1900. class decompressor {
  1901. public:
  1902. virtual ~decompressor() = default;
  1903. virtual bool is_valid() const = 0;
  1904. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1905. virtual bool decompress(const char *data, size_t data_length,
  1906. Callback callback) = 0;
  1907. };
  1908. class nocompressor final : public compressor {
  1909. public:
  1910. ~nocompressor() override = default;
  1911. bool compress(const char *data, size_t data_length, bool /*last*/,
  1912. Callback callback) override;
  1913. };
  1914. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1915. class gzip_compressor final : public compressor {
  1916. public:
  1917. gzip_compressor();
  1918. ~gzip_compressor() override;
  1919. bool compress(const char *data, size_t data_length, bool last,
  1920. Callback callback) override;
  1921. private:
  1922. bool is_valid_ = false;
  1923. z_stream strm_;
  1924. };
  1925. class gzip_decompressor final : public decompressor {
  1926. public:
  1927. gzip_decompressor();
  1928. ~gzip_decompressor() override;
  1929. bool is_valid() const override;
  1930. bool decompress(const char *data, size_t data_length,
  1931. Callback callback) override;
  1932. private:
  1933. bool is_valid_ = false;
  1934. z_stream strm_;
  1935. };
  1936. #endif
  1937. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1938. class brotli_compressor final : public compressor {
  1939. public:
  1940. brotli_compressor();
  1941. ~brotli_compressor();
  1942. bool compress(const char *data, size_t data_length, bool last,
  1943. Callback callback) override;
  1944. private:
  1945. BrotliEncoderState *state_ = nullptr;
  1946. };
  1947. class brotli_decompressor final : public decompressor {
  1948. public:
  1949. brotli_decompressor();
  1950. ~brotli_decompressor();
  1951. bool is_valid() const override;
  1952. bool decompress(const char *data, size_t data_length,
  1953. Callback callback) override;
  1954. private:
  1955. BrotliDecoderResult decoder_r;
  1956. BrotliDecoderState *decoder_s = nullptr;
  1957. };
  1958. #endif
  1959. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  1960. class zstd_compressor : public compressor {
  1961. public:
  1962. zstd_compressor();
  1963. ~zstd_compressor();
  1964. bool compress(const char *data, size_t data_length, bool last,
  1965. Callback callback) override;
  1966. private:
  1967. ZSTD_CCtx *ctx_ = nullptr;
  1968. };
  1969. class zstd_decompressor : public decompressor {
  1970. public:
  1971. zstd_decompressor();
  1972. ~zstd_decompressor();
  1973. bool is_valid() const override;
  1974. bool decompress(const char *data, size_t data_length,
  1975. Callback callback) override;
  1976. private:
  1977. ZSTD_DCtx *ctx_ = nullptr;
  1978. };
  1979. #endif
  1980. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  1981. // to store data. The call can set memory on stack for performance.
  1982. class stream_line_reader {
  1983. public:
  1984. stream_line_reader(Stream &strm, char *fixed_buffer,
  1985. size_t fixed_buffer_size);
  1986. const char *ptr() const;
  1987. size_t size() const;
  1988. bool end_with_crlf() const;
  1989. bool getline();
  1990. private:
  1991. void append(char c);
  1992. Stream &strm_;
  1993. char *fixed_buffer_;
  1994. const size_t fixed_buffer_size_;
  1995. size_t fixed_buffer_used_size_ = 0;
  1996. std::string growable_buffer_;
  1997. };
  1998. class mmap {
  1999. public:
  2000. mmap(const char *path);
  2001. ~mmap();
  2002. bool open(const char *path);
  2003. void close();
  2004. bool is_open() const;
  2005. size_t size() const;
  2006. const char *data() const;
  2007. private:
  2008. #if defined(_WIN32)
  2009. HANDLE hFile_ = NULL;
  2010. HANDLE hMapping_ = NULL;
  2011. #else
  2012. int fd_ = -1;
  2013. #endif
  2014. size_t size_ = 0;
  2015. void *addr_ = nullptr;
  2016. bool is_open_empty_file = false;
  2017. };
  2018. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2019. namespace fields {
  2020. inline bool is_token_char(char c) {
  2021. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  2022. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  2023. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  2024. }
  2025. inline bool is_token(const std::string &s) {
  2026. if (s.empty()) { return false; }
  2027. for (auto c : s) {
  2028. if (!is_token_char(c)) { return false; }
  2029. }
  2030. return true;
  2031. }
  2032. inline bool is_field_name(const std::string &s) { return is_token(s); }
  2033. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  2034. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  2035. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  2036. inline bool is_field_content(const std::string &s) {
  2037. if (s.empty()) { return true; }
  2038. if (s.size() == 1) {
  2039. return is_field_vchar(s[0]);
  2040. } else if (s.size() == 2) {
  2041. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  2042. } else {
  2043. size_t i = 0;
  2044. if (!is_field_vchar(s[i])) { return false; }
  2045. i++;
  2046. while (i < s.size() - 1) {
  2047. auto c = s[i++];
  2048. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  2049. } else {
  2050. return false;
  2051. }
  2052. }
  2053. return is_field_vchar(s[i]);
  2054. }
  2055. }
  2056. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  2057. } // namespace fields
  2058. } // namespace detail
  2059. // ----------------------------------------------------------------------------
  2060. /*
  2061. * Implementation that will be part of the .cc file if split into .h + .cc.
  2062. */
  2063. namespace detail {
  2064. inline bool is_hex(char c, int &v) {
  2065. if (0x20 <= c && isdigit(c)) {
  2066. v = c - '0';
  2067. return true;
  2068. } else if ('A' <= c && c <= 'F') {
  2069. v = c - 'A' + 10;
  2070. return true;
  2071. } else if ('a' <= c && c <= 'f') {
  2072. v = c - 'a' + 10;
  2073. return true;
  2074. }
  2075. return false;
  2076. }
  2077. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  2078. int &val) {
  2079. if (i >= s.size()) { return false; }
  2080. val = 0;
  2081. for (; cnt; i++, cnt--) {
  2082. if (!s[i]) { return false; }
  2083. auto v = 0;
  2084. if (is_hex(s[i], v)) {
  2085. val = val * 16 + v;
  2086. } else {
  2087. return false;
  2088. }
  2089. }
  2090. return true;
  2091. }
  2092. inline std::string from_i_to_hex(size_t n) {
  2093. static const auto charset = "0123456789abcdef";
  2094. std::string ret;
  2095. do {
  2096. ret = charset[n & 15] + ret;
  2097. n >>= 4;
  2098. } while (n > 0);
  2099. return ret;
  2100. }
  2101. inline size_t to_utf8(int code, char *buff) {
  2102. if (code < 0x0080) {
  2103. buff[0] = static_cast<char>(code & 0x7F);
  2104. return 1;
  2105. } else if (code < 0x0800) {
  2106. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  2107. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  2108. return 2;
  2109. } else if (code < 0xD800) {
  2110. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2111. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2112. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2113. return 3;
  2114. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  2115. return 0;
  2116. } else if (code < 0x10000) {
  2117. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2118. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2119. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2120. return 3;
  2121. } else if (code < 0x110000) {
  2122. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  2123. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  2124. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2125. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  2126. return 4;
  2127. }
  2128. // NOTREACHED
  2129. return 0;
  2130. }
  2131. // NOTE: This code came up with the following stackoverflow post:
  2132. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  2133. inline std::string base64_encode(const std::string &in) {
  2134. static const auto lookup =
  2135. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2136. std::string out;
  2137. out.reserve(in.size());
  2138. auto val = 0;
  2139. auto valb = -6;
  2140. for (auto c : in) {
  2141. val = (val << 8) + static_cast<uint8_t>(c);
  2142. valb += 8;
  2143. while (valb >= 0) {
  2144. out.push_back(lookup[(val >> valb) & 0x3F]);
  2145. valb -= 6;
  2146. }
  2147. }
  2148. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  2149. while (out.size() % 4) {
  2150. out.push_back('=');
  2151. }
  2152. return out;
  2153. }
  2154. inline bool is_valid_path(const std::string &path) {
  2155. size_t level = 0;
  2156. size_t i = 0;
  2157. // Skip slash
  2158. while (i < path.size() && path[i] == '/') {
  2159. i++;
  2160. }
  2161. while (i < path.size()) {
  2162. // Read component
  2163. auto beg = i;
  2164. while (i < path.size() && path[i] != '/') {
  2165. if (path[i] == '\0') {
  2166. return false;
  2167. } else if (path[i] == '\\') {
  2168. return false;
  2169. }
  2170. i++;
  2171. }
  2172. auto len = i - beg;
  2173. assert(len > 0);
  2174. if (!path.compare(beg, len, ".")) {
  2175. ;
  2176. } else if (!path.compare(beg, len, "..")) {
  2177. if (level == 0) { return false; }
  2178. level--;
  2179. } else {
  2180. level++;
  2181. }
  2182. // Skip slash
  2183. while (i < path.size() && path[i] == '/') {
  2184. i++;
  2185. }
  2186. }
  2187. return true;
  2188. }
  2189. inline FileStat::FileStat(const std::string &path) {
  2190. #if defined(_WIN32)
  2191. auto wpath = u8string_to_wstring(path.c_str());
  2192. ret_ = _wstat(wpath.c_str(), &st_);
  2193. #else
  2194. ret_ = stat(path.c_str(), &st_);
  2195. #endif
  2196. }
  2197. inline bool FileStat::is_file() const {
  2198. return ret_ >= 0 && S_ISREG(st_.st_mode);
  2199. }
  2200. inline bool FileStat::is_dir() const {
  2201. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  2202. }
  2203. inline std::string encode_query_param(const std::string &value) {
  2204. std::ostringstream escaped;
  2205. escaped.fill('0');
  2206. escaped << std::hex;
  2207. for (auto c : value) {
  2208. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  2209. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  2210. c == ')') {
  2211. escaped << c;
  2212. } else {
  2213. escaped << std::uppercase;
  2214. escaped << '%' << std::setw(2)
  2215. << static_cast<int>(static_cast<unsigned char>(c));
  2216. escaped << std::nouppercase;
  2217. }
  2218. }
  2219. return escaped.str();
  2220. }
  2221. inline std::string encode_url(const std::string &s) {
  2222. std::string result;
  2223. result.reserve(s.size());
  2224. for (size_t i = 0; s[i]; i++) {
  2225. switch (s[i]) {
  2226. case ' ': result += "%20"; break;
  2227. case '+': result += "%2B"; break;
  2228. case '\r': result += "%0D"; break;
  2229. case '\n': result += "%0A"; break;
  2230. case '\'': result += "%27"; break;
  2231. case ',': result += "%2C"; break;
  2232. // case ':': result += "%3A"; break; // ok? probably...
  2233. case ';': result += "%3B"; break;
  2234. default:
  2235. auto c = static_cast<uint8_t>(s[i]);
  2236. if (c >= 0x80) {
  2237. result += '%';
  2238. char hex[4];
  2239. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  2240. assert(len == 2);
  2241. result.append(hex, static_cast<size_t>(len));
  2242. } else {
  2243. result += s[i];
  2244. }
  2245. break;
  2246. }
  2247. }
  2248. return result;
  2249. }
  2250. inline std::string decode_url(const std::string &s,
  2251. bool convert_plus_to_space) {
  2252. std::string result;
  2253. for (size_t i = 0; i < s.size(); i++) {
  2254. if (s[i] == '%' && i + 1 < s.size()) {
  2255. if (s[i + 1] == 'u') {
  2256. auto val = 0;
  2257. if (from_hex_to_i(s, i + 2, 4, val)) {
  2258. // 4 digits Unicode codes
  2259. char buff[4];
  2260. size_t len = to_utf8(val, buff);
  2261. if (len > 0) { result.append(buff, len); }
  2262. i += 5; // 'u0000'
  2263. } else {
  2264. result += s[i];
  2265. }
  2266. } else {
  2267. auto val = 0;
  2268. if (from_hex_to_i(s, i + 1, 2, val)) {
  2269. // 2 digits hex codes
  2270. result += static_cast<char>(val);
  2271. i += 2; // '00'
  2272. } else {
  2273. result += s[i];
  2274. }
  2275. }
  2276. } else if (convert_plus_to_space && s[i] == '+') {
  2277. result += ' ';
  2278. } else {
  2279. result += s[i];
  2280. }
  2281. }
  2282. return result;
  2283. }
  2284. inline std::string file_extension(const std::string &path) {
  2285. std::smatch m;
  2286. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  2287. if (std::regex_search(path, m, re)) { return m[1].str(); }
  2288. return std::string();
  2289. }
  2290. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  2291. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  2292. size_t right) {
  2293. while (b + left < e && is_space_or_tab(b[left])) {
  2294. left++;
  2295. }
  2296. while (right > 0 && is_space_or_tab(b[right - 1])) {
  2297. right--;
  2298. }
  2299. return std::make_pair(left, right);
  2300. }
  2301. inline std::string trim_copy(const std::string &s) {
  2302. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  2303. return s.substr(r.first, r.second - r.first);
  2304. }
  2305. inline std::string trim_double_quotes_copy(const std::string &s) {
  2306. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  2307. return s.substr(1, s.size() - 2);
  2308. }
  2309. return s;
  2310. }
  2311. inline void
  2312. divide(const char *data, std::size_t size, char d,
  2313. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2314. fn) {
  2315. const auto it = std::find(data, data + size, d);
  2316. const auto found = static_cast<std::size_t>(it != data + size);
  2317. const auto lhs_data = data;
  2318. const auto lhs_size = static_cast<std::size_t>(it - data);
  2319. const auto rhs_data = it + found;
  2320. const auto rhs_size = size - lhs_size - found;
  2321. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  2322. }
  2323. inline void
  2324. divide(const std::string &str, char d,
  2325. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2326. fn) {
  2327. divide(str.data(), str.size(), d, std::move(fn));
  2328. }
  2329. inline void split(const char *b, const char *e, char d,
  2330. std::function<void(const char *, const char *)> fn) {
  2331. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  2332. }
  2333. inline void split(const char *b, const char *e, char d, size_t m,
  2334. std::function<void(const char *, const char *)> fn) {
  2335. size_t i = 0;
  2336. size_t beg = 0;
  2337. size_t count = 1;
  2338. while (e ? (b + i < e) : (b[i] != '\0')) {
  2339. if (b[i] == d && count < m) {
  2340. auto r = trim(b, e, beg, i);
  2341. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2342. beg = i + 1;
  2343. count++;
  2344. }
  2345. i++;
  2346. }
  2347. if (i) {
  2348. auto r = trim(b, e, beg, i);
  2349. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2350. }
  2351. }
  2352. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  2353. size_t fixed_buffer_size)
  2354. : strm_(strm), fixed_buffer_(fixed_buffer),
  2355. fixed_buffer_size_(fixed_buffer_size) {}
  2356. inline const char *stream_line_reader::ptr() const {
  2357. if (growable_buffer_.empty()) {
  2358. return fixed_buffer_;
  2359. } else {
  2360. return growable_buffer_.data();
  2361. }
  2362. }
  2363. inline size_t stream_line_reader::size() const {
  2364. if (growable_buffer_.empty()) {
  2365. return fixed_buffer_used_size_;
  2366. } else {
  2367. return growable_buffer_.size();
  2368. }
  2369. }
  2370. inline bool stream_line_reader::end_with_crlf() const {
  2371. auto end = ptr() + size();
  2372. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  2373. }
  2374. inline bool stream_line_reader::getline() {
  2375. fixed_buffer_used_size_ = 0;
  2376. growable_buffer_.clear();
  2377. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2378. char prev_byte = 0;
  2379. #endif
  2380. for (size_t i = 0;; i++) {
  2381. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  2382. // Treat exceptionally long lines as an error to
  2383. // prevent infinite loops/memory exhaustion
  2384. return false;
  2385. }
  2386. char byte;
  2387. auto n = strm_.read(&byte, 1);
  2388. if (n < 0) {
  2389. return false;
  2390. } else if (n == 0) {
  2391. if (i == 0) {
  2392. return false;
  2393. } else {
  2394. break;
  2395. }
  2396. }
  2397. append(byte);
  2398. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2399. if (byte == '\n') { break; }
  2400. #else
  2401. if (prev_byte == '\r' && byte == '\n') { break; }
  2402. prev_byte = byte;
  2403. #endif
  2404. }
  2405. return true;
  2406. }
  2407. inline void stream_line_reader::append(char c) {
  2408. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  2409. fixed_buffer_[fixed_buffer_used_size_++] = c;
  2410. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  2411. } else {
  2412. if (growable_buffer_.empty()) {
  2413. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  2414. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  2415. }
  2416. growable_buffer_ += c;
  2417. }
  2418. }
  2419. inline mmap::mmap(const char *path) { open(path); }
  2420. inline mmap::~mmap() { close(); }
  2421. inline bool mmap::open(const char *path) {
  2422. close();
  2423. #if defined(_WIN32)
  2424. auto wpath = u8string_to_wstring(path);
  2425. if (wpath.empty()) { return false; }
  2426. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  2427. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  2428. OPEN_EXISTING, NULL);
  2429. #else
  2430. hFile_ = ::CreateFileW(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL,
  2431. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  2432. #endif
  2433. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  2434. LARGE_INTEGER size{};
  2435. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  2436. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  2437. // See:
  2438. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  2439. if (static_cast<ULONGLONG>(size.QuadPart) >
  2440. (std::numeric_limits<decltype(size_)>::max)()) {
  2441. // `size_t` might be 32-bits, on 32-bits Windows.
  2442. return false;
  2443. }
  2444. size_ = static_cast<size_t>(size.QuadPart);
  2445. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  2446. hMapping_ =
  2447. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  2448. #else
  2449. hMapping_ = ::CreateFileMappingW(hFile_, NULL, PAGE_READONLY, 0, 0, NULL);
  2450. #endif
  2451. // Special treatment for an empty file...
  2452. if (hMapping_ == NULL && size_ == 0) {
  2453. close();
  2454. is_open_empty_file = true;
  2455. return true;
  2456. }
  2457. if (hMapping_ == NULL) {
  2458. close();
  2459. return false;
  2460. }
  2461. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  2462. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  2463. #else
  2464. addr_ = ::MapViewOfFile(hMapping_, FILE_MAP_READ, 0, 0, 0);
  2465. #endif
  2466. if (addr_ == nullptr) {
  2467. close();
  2468. return false;
  2469. }
  2470. #else
  2471. fd_ = ::open(path, O_RDONLY);
  2472. if (fd_ == -1) { return false; }
  2473. struct stat sb;
  2474. if (fstat(fd_, &sb) == -1) {
  2475. close();
  2476. return false;
  2477. }
  2478. size_ = static_cast<size_t>(sb.st_size);
  2479. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  2480. // Special treatment for an empty file...
  2481. if (addr_ == MAP_FAILED && size_ == 0) {
  2482. close();
  2483. is_open_empty_file = true;
  2484. return false;
  2485. }
  2486. #endif
  2487. return true;
  2488. }
  2489. inline bool mmap::is_open() const {
  2490. return is_open_empty_file ? true : addr_ != nullptr;
  2491. }
  2492. inline size_t mmap::size() const { return size_; }
  2493. inline const char *mmap::data() const {
  2494. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  2495. }
  2496. inline void mmap::close() {
  2497. #if defined(_WIN32)
  2498. if (addr_) {
  2499. ::UnmapViewOfFile(addr_);
  2500. addr_ = nullptr;
  2501. }
  2502. if (hMapping_) {
  2503. ::CloseHandle(hMapping_);
  2504. hMapping_ = NULL;
  2505. }
  2506. if (hFile_ != INVALID_HANDLE_VALUE) {
  2507. ::CloseHandle(hFile_);
  2508. hFile_ = INVALID_HANDLE_VALUE;
  2509. }
  2510. is_open_empty_file = false;
  2511. #else
  2512. if (addr_ != nullptr) {
  2513. munmap(addr_, size_);
  2514. addr_ = nullptr;
  2515. }
  2516. if (fd_ != -1) {
  2517. ::close(fd_);
  2518. fd_ = -1;
  2519. }
  2520. #endif
  2521. size_ = 0;
  2522. }
  2523. inline int close_socket(socket_t sock) {
  2524. #ifdef _WIN32
  2525. return closesocket(sock);
  2526. #else
  2527. return close(sock);
  2528. #endif
  2529. }
  2530. template <typename T> inline ssize_t handle_EINTR(T fn) {
  2531. ssize_t res = 0;
  2532. while (true) {
  2533. res = fn();
  2534. if (res < 0 && errno == EINTR) {
  2535. std::this_thread::sleep_for(std::chrono::microseconds{1});
  2536. continue;
  2537. }
  2538. break;
  2539. }
  2540. return res;
  2541. }
  2542. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  2543. return handle_EINTR([&]() {
  2544. return recv(sock,
  2545. #ifdef _WIN32
  2546. static_cast<char *>(ptr), static_cast<int>(size),
  2547. #else
  2548. ptr, size,
  2549. #endif
  2550. flags);
  2551. });
  2552. }
  2553. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  2554. int flags) {
  2555. return handle_EINTR([&]() {
  2556. return send(sock,
  2557. #ifdef _WIN32
  2558. static_cast<const char *>(ptr), static_cast<int>(size),
  2559. #else
  2560. ptr, size,
  2561. #endif
  2562. flags);
  2563. });
  2564. }
  2565. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  2566. #ifdef _WIN32
  2567. return ::WSAPoll(fds, nfds, timeout);
  2568. #else
  2569. return ::poll(fds, nfds, timeout);
  2570. #endif
  2571. }
  2572. template <bool Read>
  2573. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  2574. struct pollfd pfd;
  2575. pfd.fd = sock;
  2576. pfd.events = (Read ? POLLIN : POLLOUT);
  2577. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2578. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  2579. }
  2580. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  2581. return select_impl<true>(sock, sec, usec);
  2582. }
  2583. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  2584. return select_impl<false>(sock, sec, usec);
  2585. }
  2586. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  2587. time_t usec) {
  2588. struct pollfd pfd_read;
  2589. pfd_read.fd = sock;
  2590. pfd_read.events = POLLIN | POLLOUT;
  2591. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2592. auto poll_res =
  2593. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  2594. if (poll_res == 0) { return Error::ConnectionTimeout; }
  2595. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  2596. auto error = 0;
  2597. socklen_t len = sizeof(error);
  2598. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  2599. reinterpret_cast<char *>(&error), &len);
  2600. auto successful = res >= 0 && !error;
  2601. return successful ? Error::Success : Error::Connection;
  2602. }
  2603. return Error::Connection;
  2604. }
  2605. inline bool is_socket_alive(socket_t sock) {
  2606. const auto val = detail::select_read(sock, 0, 0);
  2607. if (val == 0) {
  2608. return true;
  2609. } else if (val < 0 && errno == EBADF) {
  2610. return false;
  2611. }
  2612. char buf[1];
  2613. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  2614. }
  2615. class SocketStream final : public Stream {
  2616. public:
  2617. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2618. time_t write_timeout_sec, time_t write_timeout_usec,
  2619. time_t max_timeout_msec = 0,
  2620. std::chrono::time_point<std::chrono::steady_clock> start_time =
  2621. (std::chrono::steady_clock::time_point::min)());
  2622. ~SocketStream() override;
  2623. bool is_readable() const override;
  2624. bool wait_readable() const override;
  2625. bool wait_writable() const override;
  2626. ssize_t read(char *ptr, size_t size) override;
  2627. ssize_t write(const char *ptr, size_t size) override;
  2628. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2629. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2630. socket_t socket() const override;
  2631. time_t duration() const override;
  2632. private:
  2633. socket_t sock_;
  2634. time_t read_timeout_sec_;
  2635. time_t read_timeout_usec_;
  2636. time_t write_timeout_sec_;
  2637. time_t write_timeout_usec_;
  2638. time_t max_timeout_msec_;
  2639. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2640. std::vector<char> read_buff_;
  2641. size_t read_buff_off_ = 0;
  2642. size_t read_buff_content_size_ = 0;
  2643. static const size_t read_buff_size_ = 1024l * 4;
  2644. };
  2645. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2646. class SSLSocketStream final : public Stream {
  2647. public:
  2648. SSLSocketStream(
  2649. socket_t sock, SSL *ssl, time_t read_timeout_sec,
  2650. time_t read_timeout_usec, time_t write_timeout_sec,
  2651. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  2652. std::chrono::time_point<std::chrono::steady_clock> start_time =
  2653. (std::chrono::steady_clock::time_point::min)());
  2654. ~SSLSocketStream() override;
  2655. bool is_readable() const override;
  2656. bool wait_readable() const override;
  2657. bool wait_writable() const override;
  2658. ssize_t read(char *ptr, size_t size) override;
  2659. ssize_t write(const char *ptr, size_t size) override;
  2660. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2661. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2662. socket_t socket() const override;
  2663. time_t duration() const override;
  2664. private:
  2665. socket_t sock_;
  2666. SSL *ssl_;
  2667. time_t read_timeout_sec_;
  2668. time_t read_timeout_usec_;
  2669. time_t write_timeout_sec_;
  2670. time_t write_timeout_usec_;
  2671. time_t max_timeout_msec_;
  2672. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2673. };
  2674. #endif
  2675. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2676. time_t keep_alive_timeout_sec) {
  2677. using namespace std::chrono;
  2678. const auto interval_usec =
  2679. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  2680. // Avoid expensive `steady_clock::now()` call for the first time
  2681. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  2682. const auto start = steady_clock::now() - microseconds{interval_usec};
  2683. const auto timeout = seconds{keep_alive_timeout_sec};
  2684. while (true) {
  2685. if (svr_sock == INVALID_SOCKET) {
  2686. break; // Server socket is closed
  2687. }
  2688. auto val = select_read(sock, 0, interval_usec);
  2689. if (val < 0) {
  2690. break; // Ssocket error
  2691. } else if (val == 0) {
  2692. if (steady_clock::now() - start > timeout) {
  2693. break; // Timeout
  2694. }
  2695. } else {
  2696. return true; // Ready for read
  2697. }
  2698. }
  2699. return false;
  2700. }
  2701. template <typename T>
  2702. inline bool
  2703. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2704. size_t keep_alive_max_count,
  2705. time_t keep_alive_timeout_sec, T callback) {
  2706. assert(keep_alive_max_count > 0);
  2707. auto ret = false;
  2708. auto count = keep_alive_max_count;
  2709. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  2710. auto close_connection = count == 1;
  2711. auto connection_closed = false;
  2712. ret = callback(close_connection, connection_closed);
  2713. if (!ret || connection_closed) { break; }
  2714. count--;
  2715. }
  2716. return ret;
  2717. }
  2718. template <typename T>
  2719. inline bool
  2720. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2721. size_t keep_alive_max_count,
  2722. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  2723. time_t read_timeout_usec, time_t write_timeout_sec,
  2724. time_t write_timeout_usec, T callback) {
  2725. return process_server_socket_core(
  2726. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  2727. [&](bool close_connection, bool &connection_closed) {
  2728. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2729. write_timeout_sec, write_timeout_usec);
  2730. return callback(strm, close_connection, connection_closed);
  2731. });
  2732. }
  2733. inline bool process_client_socket(
  2734. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2735. time_t write_timeout_sec, time_t write_timeout_usec,
  2736. time_t max_timeout_msec,
  2737. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2738. std::function<bool(Stream &)> callback) {
  2739. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2740. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  2741. start_time);
  2742. return callback(strm);
  2743. }
  2744. inline int shutdown_socket(socket_t sock) {
  2745. #ifdef _WIN32
  2746. return shutdown(sock, SD_BOTH);
  2747. #else
  2748. return shutdown(sock, SHUT_RDWR);
  2749. #endif
  2750. }
  2751. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  2752. if (s.size() > 1 && s[0] == '\0') {
  2753. auto ret = s;
  2754. ret[0] = '@';
  2755. return ret;
  2756. }
  2757. return s;
  2758. }
  2759. inline std::string
  2760. unescape_abstract_namespace_unix_domain(const std::string &s) {
  2761. if (s.size() > 1 && s[0] == '@') {
  2762. auto ret = s;
  2763. ret[0] = '\0';
  2764. return ret;
  2765. }
  2766. return s;
  2767. }
  2768. template <typename BindOrConnect>
  2769. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  2770. int address_family, int socket_flags, bool tcp_nodelay,
  2771. bool ipv6_v6only, SocketOptions socket_options,
  2772. BindOrConnect bind_or_connect) {
  2773. // Get address info
  2774. const char *node = nullptr;
  2775. struct addrinfo hints;
  2776. struct addrinfo *result;
  2777. memset(&hints, 0, sizeof(struct addrinfo));
  2778. hints.ai_socktype = SOCK_STREAM;
  2779. hints.ai_protocol = IPPROTO_IP;
  2780. if (!ip.empty()) {
  2781. node = ip.c_str();
  2782. // Ask getaddrinfo to convert IP in c-string to address
  2783. hints.ai_family = AF_UNSPEC;
  2784. hints.ai_flags = AI_NUMERICHOST;
  2785. } else {
  2786. if (!host.empty()) { node = host.c_str(); }
  2787. hints.ai_family = address_family;
  2788. hints.ai_flags = socket_flags;
  2789. }
  2790. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  2791. if (hints.ai_family == AF_UNIX) {
  2792. const auto addrlen = host.length();
  2793. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  2794. #ifdef SOCK_CLOEXEC
  2795. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  2796. hints.ai_protocol);
  2797. #else
  2798. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  2799. #endif
  2800. if (sock != INVALID_SOCKET) {
  2801. sockaddr_un addr{};
  2802. addr.sun_family = AF_UNIX;
  2803. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  2804. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  2805. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  2806. hints.ai_addrlen = static_cast<socklen_t>(
  2807. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  2808. #ifndef SOCK_CLOEXEC
  2809. #ifndef _WIN32
  2810. fcntl(sock, F_SETFD, FD_CLOEXEC);
  2811. #endif
  2812. #endif
  2813. if (socket_options) { socket_options(sock); }
  2814. #ifdef _WIN32
  2815. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  2816. // remove the option.
  2817. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  2818. #endif
  2819. bool dummy;
  2820. if (!bind_or_connect(sock, hints, dummy)) {
  2821. close_socket(sock);
  2822. sock = INVALID_SOCKET;
  2823. }
  2824. }
  2825. return sock;
  2826. }
  2827. #endif
  2828. auto service = std::to_string(port);
  2829. if (getaddrinfo(node, service.c_str(), &hints, &result)) {
  2830. #if defined __linux__ && !defined __ANDROID__
  2831. res_init();
  2832. #endif
  2833. return INVALID_SOCKET;
  2834. }
  2835. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  2836. for (auto rp = result; rp; rp = rp->ai_next) {
  2837. // Create a socket
  2838. #ifdef _WIN32
  2839. auto sock =
  2840. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  2841. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  2842. /**
  2843. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  2844. * and above the socket creation fails on older Windows Systems.
  2845. *
  2846. * Let's try to create a socket the old way in this case.
  2847. *
  2848. * Reference:
  2849. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  2850. *
  2851. * WSA_FLAG_NO_HANDLE_INHERIT:
  2852. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  2853. * SP1, and later
  2854. *
  2855. */
  2856. if (sock == INVALID_SOCKET) {
  2857. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  2858. }
  2859. #else
  2860. #ifdef SOCK_CLOEXEC
  2861. auto sock =
  2862. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  2863. #else
  2864. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  2865. #endif
  2866. #endif
  2867. if (sock == INVALID_SOCKET) { continue; }
  2868. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  2869. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  2870. close_socket(sock);
  2871. continue;
  2872. }
  2873. #endif
  2874. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  2875. if (rp->ai_family == AF_INET6) {
  2876. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  2877. }
  2878. if (socket_options) { socket_options(sock); }
  2879. // bind or connect
  2880. auto quit = false;
  2881. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  2882. close_socket(sock);
  2883. if (quit) { break; }
  2884. }
  2885. return INVALID_SOCKET;
  2886. }
  2887. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  2888. #ifdef _WIN32
  2889. auto flags = nonblocking ? 1UL : 0UL;
  2890. ioctlsocket(sock, FIONBIO, &flags);
  2891. #else
  2892. auto flags = fcntl(sock, F_GETFL, 0);
  2893. fcntl(sock, F_SETFL,
  2894. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  2895. #endif
  2896. }
  2897. inline bool is_connection_error() {
  2898. #ifdef _WIN32
  2899. return WSAGetLastError() != WSAEWOULDBLOCK;
  2900. #else
  2901. return errno != EINPROGRESS;
  2902. #endif
  2903. }
  2904. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  2905. struct addrinfo hints;
  2906. struct addrinfo *result;
  2907. memset(&hints, 0, sizeof(struct addrinfo));
  2908. hints.ai_family = AF_UNSPEC;
  2909. hints.ai_socktype = SOCK_STREAM;
  2910. hints.ai_protocol = 0;
  2911. if (getaddrinfo(host.c_str(), "0", &hints, &result)) { return false; }
  2912. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  2913. auto ret = false;
  2914. for (auto rp = result; rp; rp = rp->ai_next) {
  2915. const auto &ai = *rp;
  2916. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  2917. ret = true;
  2918. break;
  2919. }
  2920. }
  2921. return ret;
  2922. }
  2923. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  2924. #define USE_IF2IP
  2925. #endif
  2926. #ifdef USE_IF2IP
  2927. inline std::string if2ip(int address_family, const std::string &ifn) {
  2928. struct ifaddrs *ifap;
  2929. getifaddrs(&ifap);
  2930. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  2931. std::string addr_candidate;
  2932. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  2933. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  2934. (AF_UNSPEC == address_family ||
  2935. ifa->ifa_addr->sa_family == address_family)) {
  2936. if (ifa->ifa_addr->sa_family == AF_INET) {
  2937. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  2938. char buf[INET_ADDRSTRLEN];
  2939. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  2940. return std::string(buf, INET_ADDRSTRLEN);
  2941. }
  2942. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  2943. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  2944. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  2945. char buf[INET6_ADDRSTRLEN] = {};
  2946. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  2947. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  2948. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  2949. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  2950. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  2951. } else {
  2952. return std::string(buf, INET6_ADDRSTRLEN);
  2953. }
  2954. }
  2955. }
  2956. }
  2957. }
  2958. }
  2959. return addr_candidate;
  2960. }
  2961. #endif
  2962. inline socket_t create_client_socket(
  2963. const std::string &host, const std::string &ip, int port,
  2964. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  2965. SocketOptions socket_options, time_t connection_timeout_sec,
  2966. time_t connection_timeout_usec, time_t read_timeout_sec,
  2967. time_t read_timeout_usec, time_t write_timeout_sec,
  2968. time_t write_timeout_usec, const std::string &intf, Error &error) {
  2969. auto sock = create_socket(
  2970. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  2971. std::move(socket_options),
  2972. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  2973. if (!intf.empty()) {
  2974. #ifdef USE_IF2IP
  2975. auto ip_from_if = if2ip(address_family, intf);
  2976. if (ip_from_if.empty()) { ip_from_if = intf; }
  2977. if (!bind_ip_address(sock2, ip_from_if)) {
  2978. error = Error::BindIPAddress;
  2979. return false;
  2980. }
  2981. #endif
  2982. }
  2983. set_nonblocking(sock2, true);
  2984. auto ret =
  2985. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  2986. if (ret < 0) {
  2987. if (is_connection_error()) {
  2988. error = Error::Connection;
  2989. return false;
  2990. }
  2991. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  2992. connection_timeout_usec);
  2993. if (error != Error::Success) {
  2994. if (error == Error::ConnectionTimeout) { quit = true; }
  2995. return false;
  2996. }
  2997. }
  2998. set_nonblocking(sock2, false);
  2999. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  3000. read_timeout_usec);
  3001. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  3002. write_timeout_usec);
  3003. error = Error::Success;
  3004. return true;
  3005. });
  3006. if (sock != INVALID_SOCKET) {
  3007. error = Error::Success;
  3008. } else {
  3009. if (error == Error::Success) { error = Error::Connection; }
  3010. }
  3011. return sock;
  3012. }
  3013. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  3014. socklen_t addr_len, std::string &ip, int &port) {
  3015. if (addr.ss_family == AF_INET) {
  3016. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  3017. } else if (addr.ss_family == AF_INET6) {
  3018. port =
  3019. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  3020. } else {
  3021. return false;
  3022. }
  3023. std::array<char, NI_MAXHOST> ipstr{};
  3024. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  3025. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  3026. 0, NI_NUMERICHOST)) {
  3027. return false;
  3028. }
  3029. ip = ipstr.data();
  3030. return true;
  3031. }
  3032. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  3033. struct sockaddr_storage addr;
  3034. socklen_t addr_len = sizeof(addr);
  3035. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  3036. &addr_len)) {
  3037. get_ip_and_port(addr, addr_len, ip, port);
  3038. }
  3039. }
  3040. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  3041. struct sockaddr_storage addr;
  3042. socklen_t addr_len = sizeof(addr);
  3043. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  3044. &addr_len)) {
  3045. #ifndef _WIN32
  3046. if (addr.ss_family == AF_UNIX) {
  3047. #if defined(__linux__)
  3048. struct ucred ucred;
  3049. socklen_t len = sizeof(ucred);
  3050. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  3051. port = ucred.pid;
  3052. }
  3053. #elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__
  3054. pid_t pid;
  3055. socklen_t len = sizeof(pid);
  3056. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  3057. port = pid;
  3058. }
  3059. #endif
  3060. return;
  3061. }
  3062. #endif
  3063. get_ip_and_port(addr, addr_len, ip, port);
  3064. }
  3065. }
  3066. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  3067. unsigned int h) {
  3068. return (l == 0)
  3069. ? h
  3070. : str2tag_core(
  3071. s + 1, l - 1,
  3072. // Unsets the 6 high bits of h, therefore no overflow happens
  3073. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  3074. h * 33) ^
  3075. static_cast<unsigned char>(*s));
  3076. }
  3077. inline unsigned int str2tag(const std::string &s) {
  3078. return str2tag_core(s.data(), s.size(), 0);
  3079. }
  3080. namespace udl {
  3081. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  3082. return str2tag_core(s, l, 0);
  3083. }
  3084. } // namespace udl
  3085. inline std::string
  3086. find_content_type(const std::string &path,
  3087. const std::map<std::string, std::string> &user_data,
  3088. const std::string &default_content_type) {
  3089. auto ext = file_extension(path);
  3090. auto it = user_data.find(ext);
  3091. if (it != user_data.end()) { return it->second; }
  3092. using udl::operator""_t;
  3093. switch (str2tag(ext)) {
  3094. default: return default_content_type;
  3095. case "css"_t: return "text/css";
  3096. case "csv"_t: return "text/csv";
  3097. case "htm"_t:
  3098. case "html"_t: return "text/html";
  3099. case "js"_t:
  3100. case "mjs"_t: return "text/javascript";
  3101. case "txt"_t: return "text/plain";
  3102. case "vtt"_t: return "text/vtt";
  3103. case "apng"_t: return "image/apng";
  3104. case "avif"_t: return "image/avif";
  3105. case "bmp"_t: return "image/bmp";
  3106. case "gif"_t: return "image/gif";
  3107. case "png"_t: return "image/png";
  3108. case "svg"_t: return "image/svg+xml";
  3109. case "webp"_t: return "image/webp";
  3110. case "ico"_t: return "image/x-icon";
  3111. case "tif"_t: return "image/tiff";
  3112. case "tiff"_t: return "image/tiff";
  3113. case "jpg"_t:
  3114. case "jpeg"_t: return "image/jpeg";
  3115. case "mp4"_t: return "video/mp4";
  3116. case "mpeg"_t: return "video/mpeg";
  3117. case "webm"_t: return "video/webm";
  3118. case "mp3"_t: return "audio/mp3";
  3119. case "mpga"_t: return "audio/mpeg";
  3120. case "weba"_t: return "audio/webm";
  3121. case "wav"_t: return "audio/wave";
  3122. case "otf"_t: return "font/otf";
  3123. case "ttf"_t: return "font/ttf";
  3124. case "woff"_t: return "font/woff";
  3125. case "woff2"_t: return "font/woff2";
  3126. case "7z"_t: return "application/x-7z-compressed";
  3127. case "atom"_t: return "application/atom+xml";
  3128. case "pdf"_t: return "application/pdf";
  3129. case "json"_t: return "application/json";
  3130. case "rss"_t: return "application/rss+xml";
  3131. case "tar"_t: return "application/x-tar";
  3132. case "xht"_t:
  3133. case "xhtml"_t: return "application/xhtml+xml";
  3134. case "xslt"_t: return "application/xslt+xml";
  3135. case "xml"_t: return "application/xml";
  3136. case "gz"_t: return "application/gzip";
  3137. case "zip"_t: return "application/zip";
  3138. case "wasm"_t: return "application/wasm";
  3139. }
  3140. }
  3141. inline bool can_compress_content_type(const std::string &content_type) {
  3142. using udl::operator""_t;
  3143. auto tag = str2tag(content_type);
  3144. switch (tag) {
  3145. case "image/svg+xml"_t:
  3146. case "application/javascript"_t:
  3147. case "application/json"_t:
  3148. case "application/xml"_t:
  3149. case "application/protobuf"_t:
  3150. case "application/xhtml+xml"_t: return true;
  3151. case "text/event-stream"_t: return false;
  3152. default: return !content_type.rfind("text/", 0);
  3153. }
  3154. }
  3155. inline EncodingType encoding_type(const Request &req, const Response &res) {
  3156. auto ret =
  3157. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  3158. if (!ret) { return EncodingType::None; }
  3159. const auto &s = req.get_header_value("Accept-Encoding");
  3160. (void)(s);
  3161. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3162. // TODO: 'Accept-Encoding' has br, not br;q=0
  3163. ret = s.find("br") != std::string::npos;
  3164. if (ret) { return EncodingType::Brotli; }
  3165. #endif
  3166. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3167. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  3168. ret = s.find("gzip") != std::string::npos;
  3169. if (ret) { return EncodingType::Gzip; }
  3170. #endif
  3171. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3172. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  3173. ret = s.find("zstd") != std::string::npos;
  3174. if (ret) { return EncodingType::Zstd; }
  3175. #endif
  3176. return EncodingType::None;
  3177. }
  3178. inline bool nocompressor::compress(const char *data, size_t data_length,
  3179. bool /*last*/, Callback callback) {
  3180. if (!data_length) { return true; }
  3181. return callback(data, data_length);
  3182. }
  3183. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3184. inline gzip_compressor::gzip_compressor() {
  3185. std::memset(&strm_, 0, sizeof(strm_));
  3186. strm_.zalloc = Z_NULL;
  3187. strm_.zfree = Z_NULL;
  3188. strm_.opaque = Z_NULL;
  3189. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  3190. Z_DEFAULT_STRATEGY) == Z_OK;
  3191. }
  3192. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  3193. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  3194. bool last, Callback callback) {
  3195. assert(is_valid_);
  3196. do {
  3197. constexpr size_t max_avail_in =
  3198. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3199. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3200. (std::min)(data_length, max_avail_in));
  3201. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3202. data_length -= strm_.avail_in;
  3203. data += strm_.avail_in;
  3204. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  3205. auto ret = Z_OK;
  3206. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3207. do {
  3208. strm_.avail_out = static_cast<uInt>(buff.size());
  3209. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3210. ret = deflate(&strm_, flush);
  3211. if (ret == Z_STREAM_ERROR) { return false; }
  3212. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3213. return false;
  3214. }
  3215. } while (strm_.avail_out == 0);
  3216. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  3217. (flush == Z_NO_FLUSH && ret == Z_OK));
  3218. assert(strm_.avail_in == 0);
  3219. } while (data_length > 0);
  3220. return true;
  3221. }
  3222. inline gzip_decompressor::gzip_decompressor() {
  3223. std::memset(&strm_, 0, sizeof(strm_));
  3224. strm_.zalloc = Z_NULL;
  3225. strm_.zfree = Z_NULL;
  3226. strm_.opaque = Z_NULL;
  3227. // 15 is the value of wbits, which should be at the maximum possible value
  3228. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  3229. // that the stream type should be automatically detected either gzip or
  3230. // deflate.
  3231. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  3232. }
  3233. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  3234. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  3235. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  3236. Callback callback) {
  3237. assert(is_valid_);
  3238. auto ret = Z_OK;
  3239. do {
  3240. constexpr size_t max_avail_in =
  3241. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3242. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3243. (std::min)(data_length, max_avail_in));
  3244. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3245. data_length -= strm_.avail_in;
  3246. data += strm_.avail_in;
  3247. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3248. while (strm_.avail_in > 0 && ret == Z_OK) {
  3249. strm_.avail_out = static_cast<uInt>(buff.size());
  3250. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3251. ret = inflate(&strm_, Z_NO_FLUSH);
  3252. assert(ret != Z_STREAM_ERROR);
  3253. switch (ret) {
  3254. case Z_NEED_DICT:
  3255. case Z_DATA_ERROR:
  3256. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  3257. }
  3258. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3259. return false;
  3260. }
  3261. }
  3262. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  3263. } while (data_length > 0);
  3264. return true;
  3265. }
  3266. #endif
  3267. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3268. inline brotli_compressor::brotli_compressor() {
  3269. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  3270. }
  3271. inline brotli_compressor::~brotli_compressor() {
  3272. BrotliEncoderDestroyInstance(state_);
  3273. }
  3274. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  3275. bool last, Callback callback) {
  3276. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3277. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  3278. auto available_in = data_length;
  3279. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3280. for (;;) {
  3281. if (last) {
  3282. if (BrotliEncoderIsFinished(state_)) { break; }
  3283. } else {
  3284. if (!available_in) { break; }
  3285. }
  3286. auto available_out = buff.size();
  3287. auto next_out = buff.data();
  3288. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  3289. &available_out, &next_out, nullptr)) {
  3290. return false;
  3291. }
  3292. auto output_bytes = buff.size() - available_out;
  3293. if (output_bytes) {
  3294. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  3295. }
  3296. }
  3297. return true;
  3298. }
  3299. inline brotli_decompressor::brotli_decompressor() {
  3300. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  3301. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  3302. : BROTLI_DECODER_RESULT_ERROR;
  3303. }
  3304. inline brotli_decompressor::~brotli_decompressor() {
  3305. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  3306. }
  3307. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  3308. inline bool brotli_decompressor::decompress(const char *data,
  3309. size_t data_length,
  3310. Callback callback) {
  3311. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3312. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  3313. return 0;
  3314. }
  3315. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3316. size_t avail_in = data_length;
  3317. size_t total_out;
  3318. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  3319. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3320. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  3321. char *next_out = buff.data();
  3322. size_t avail_out = buff.size();
  3323. decoder_r = BrotliDecoderDecompressStream(
  3324. decoder_s, &avail_in, &next_in, &avail_out,
  3325. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  3326. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  3327. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  3328. }
  3329. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3330. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  3331. }
  3332. #endif
  3333. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3334. inline zstd_compressor::zstd_compressor() {
  3335. ctx_ = ZSTD_createCCtx();
  3336. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  3337. }
  3338. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  3339. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  3340. bool last, Callback callback) {
  3341. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3342. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  3343. ZSTD_inBuffer input = {data, data_length, 0};
  3344. bool finished;
  3345. do {
  3346. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  3347. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  3348. if (ZSTD_isError(remaining)) { return false; }
  3349. if (!callback(buff.data(), output.pos)) { return false; }
  3350. finished = last ? (remaining == 0) : (input.pos == input.size);
  3351. } while (!finished);
  3352. return true;
  3353. }
  3354. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  3355. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  3356. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  3357. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  3358. Callback callback) {
  3359. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3360. ZSTD_inBuffer input = {data, data_length, 0};
  3361. while (input.pos < input.size) {
  3362. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  3363. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  3364. if (ZSTD_isError(remaining)) { return false; }
  3365. if (!callback(buff.data(), output.pos)) { return false; }
  3366. }
  3367. return true;
  3368. }
  3369. #endif
  3370. inline bool has_header(const Headers &headers, const std::string &key) {
  3371. return headers.find(key) != headers.end();
  3372. }
  3373. inline const char *get_header_value(const Headers &headers,
  3374. const std::string &key, const char *def,
  3375. size_t id) {
  3376. auto rng = headers.equal_range(key);
  3377. auto it = rng.first;
  3378. std::advance(it, static_cast<ssize_t>(id));
  3379. if (it != rng.second) { return it->second.c_str(); }
  3380. return def;
  3381. }
  3382. template <typename T>
  3383. inline bool parse_header(const char *beg, const char *end, T fn) {
  3384. // Skip trailing spaces and tabs.
  3385. while (beg < end && is_space_or_tab(end[-1])) {
  3386. end--;
  3387. }
  3388. auto p = beg;
  3389. while (p < end && *p != ':') {
  3390. p++;
  3391. }
  3392. auto name = std::string(beg, p);
  3393. if (!detail::fields::is_field_name(name)) { return false; }
  3394. if (p == end) { return false; }
  3395. auto key_end = p;
  3396. if (*p++ != ':') { return false; }
  3397. while (p < end && is_space_or_tab(*p)) {
  3398. p++;
  3399. }
  3400. if (p <= end) {
  3401. auto key_len = key_end - beg;
  3402. if (!key_len) { return false; }
  3403. auto key = std::string(beg, key_end);
  3404. auto val = std::string(p, end);
  3405. if (!detail::fields::is_field_value(val)) { return false; }
  3406. if (case_ignore::equal(key, "Location") ||
  3407. case_ignore::equal(key, "Referer")) {
  3408. fn(key, val);
  3409. } else {
  3410. fn(key, decode_url(val, false));
  3411. }
  3412. return true;
  3413. }
  3414. return false;
  3415. }
  3416. inline bool read_headers(Stream &strm, Headers &headers) {
  3417. const auto bufsiz = 2048;
  3418. char buf[bufsiz];
  3419. stream_line_reader line_reader(strm, buf, bufsiz);
  3420. size_t header_count = 0;
  3421. for (;;) {
  3422. if (!line_reader.getline()) { return false; }
  3423. // Check if the line ends with CRLF.
  3424. auto line_terminator_len = 2;
  3425. if (line_reader.end_with_crlf()) {
  3426. // Blank line indicates end of headers.
  3427. if (line_reader.size() == 2) { break; }
  3428. } else {
  3429. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3430. // Blank line indicates end of headers.
  3431. if (line_reader.size() == 1) { break; }
  3432. line_terminator_len = 1;
  3433. #else
  3434. continue; // Skip invalid line.
  3435. #endif
  3436. }
  3437. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3438. // Check header count limit
  3439. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3440. // Exclude line terminator
  3441. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3442. if (!parse_header(line_reader.ptr(), end,
  3443. [&](const std::string &key, const std::string &val) {
  3444. headers.emplace(key, val);
  3445. })) {
  3446. return false;
  3447. }
  3448. header_count++;
  3449. }
  3450. return true;
  3451. }
  3452. inline bool read_content_with_length(Stream &strm, uint64_t len,
  3453. DownloadProgress progress,
  3454. ContentReceiverWithProgress out) {
  3455. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3456. uint64_t r = 0;
  3457. while (r < len) {
  3458. auto read_len = static_cast<size_t>(len - r);
  3459. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3460. if (n <= 0) { return false; }
  3461. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  3462. r += static_cast<uint64_t>(n);
  3463. if (progress) {
  3464. if (!progress(r, len)) { return false; }
  3465. }
  3466. }
  3467. return true;
  3468. }
  3469. inline void skip_content_with_length(Stream &strm, uint64_t len) {
  3470. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3471. uint64_t r = 0;
  3472. while (r < len) {
  3473. auto read_len = static_cast<size_t>(len - r);
  3474. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3475. if (n <= 0) { return; }
  3476. r += static_cast<uint64_t>(n);
  3477. }
  3478. }
  3479. inline bool read_content_without_length(Stream &strm,
  3480. ContentReceiverWithProgress out) {
  3481. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3482. uint64_t r = 0;
  3483. for (;;) {
  3484. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  3485. if (n == 0) { return true; }
  3486. if (n < 0) { return false; }
  3487. if (!out(buf, static_cast<size_t>(n), r, 0)) { return false; }
  3488. r += static_cast<uint64_t>(n);
  3489. }
  3490. return true;
  3491. }
  3492. template <typename T>
  3493. inline bool read_content_chunked(Stream &strm, T &x,
  3494. ContentReceiverWithProgress out) {
  3495. const auto bufsiz = 16;
  3496. char buf[bufsiz];
  3497. stream_line_reader line_reader(strm, buf, bufsiz);
  3498. if (!line_reader.getline()) { return false; }
  3499. unsigned long chunk_len;
  3500. while (true) {
  3501. char *end_ptr;
  3502. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  3503. if (end_ptr == line_reader.ptr()) { return false; }
  3504. if (chunk_len == ULONG_MAX) { return false; }
  3505. if (chunk_len == 0) { break; }
  3506. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  3507. return false;
  3508. }
  3509. if (!line_reader.getline()) { return false; }
  3510. if (strcmp(line_reader.ptr(), "\r\n") != 0) { return false; }
  3511. if (!line_reader.getline()) { return false; }
  3512. }
  3513. assert(chunk_len == 0);
  3514. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3515. // transfer coding is complete when a chunk with a chunk-size of zero is
  3516. // received, possibly followed by a trailer section, and finally terminated by
  3517. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3518. //
  3519. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3520. // does't care for the existence of the final CRLF. In other words, it seems
  3521. // to be ok whether the final CRLF exists or not in the chunked data.
  3522. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3523. //
  3524. // According to the reference code in RFC 9112, cpp-httplib now allows
  3525. // chunked transfer coding data without the final CRLF.
  3526. if (!line_reader.getline()) { return true; }
  3527. size_t trailer_header_count = 0;
  3528. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3529. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3530. // Check trailer header count limit
  3531. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3532. // Exclude line terminator
  3533. constexpr auto line_terminator_len = 2;
  3534. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3535. parse_header(line_reader.ptr(), end,
  3536. [&](const std::string &key, const std::string &val) {
  3537. x.headers.emplace(key, val);
  3538. });
  3539. trailer_header_count++;
  3540. if (!line_reader.getline()) { return false; }
  3541. }
  3542. return true;
  3543. }
  3544. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  3545. return case_ignore::equal(
  3546. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  3547. }
  3548. template <typename T, typename U>
  3549. bool prepare_content_receiver(T &x, int &status,
  3550. ContentReceiverWithProgress receiver,
  3551. bool decompress, U callback) {
  3552. if (decompress) {
  3553. std::string encoding = x.get_header_value("Content-Encoding");
  3554. std::unique_ptr<decompressor> decompressor;
  3555. if (encoding == "gzip" || encoding == "deflate") {
  3556. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3557. decompressor = detail::make_unique<gzip_decompressor>();
  3558. #else
  3559. status = StatusCode::UnsupportedMediaType_415;
  3560. return false;
  3561. #endif
  3562. } else if (encoding.find("br") != std::string::npos) {
  3563. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3564. decompressor = detail::make_unique<brotli_decompressor>();
  3565. #else
  3566. status = StatusCode::UnsupportedMediaType_415;
  3567. return false;
  3568. #endif
  3569. } else if (encoding == "zstd") {
  3570. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3571. decompressor = detail::make_unique<zstd_decompressor>();
  3572. #else
  3573. status = StatusCode::UnsupportedMediaType_415;
  3574. return false;
  3575. #endif
  3576. }
  3577. if (decompressor) {
  3578. if (decompressor->is_valid()) {
  3579. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  3580. uint64_t off, uint64_t len) {
  3581. return decompressor->decompress(buf, n,
  3582. [&](const char *buf2, size_t n2) {
  3583. return receiver(buf2, n2, off, len);
  3584. });
  3585. };
  3586. return callback(std::move(out));
  3587. } else {
  3588. status = StatusCode::InternalServerError_500;
  3589. return false;
  3590. }
  3591. }
  3592. }
  3593. ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off,
  3594. uint64_t len) {
  3595. return receiver(buf, n, off, len);
  3596. };
  3597. return callback(std::move(out));
  3598. }
  3599. template <typename T>
  3600. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  3601. DownloadProgress progress,
  3602. ContentReceiverWithProgress receiver, bool decompress) {
  3603. return prepare_content_receiver(
  3604. x, status, std::move(receiver), decompress,
  3605. [&](const ContentReceiverWithProgress &out) {
  3606. auto ret = true;
  3607. auto exceed_payload_max_length = false;
  3608. if (is_chunked_transfer_encoding(x.headers)) {
  3609. ret = read_content_chunked(strm, x, out);
  3610. } else if (!has_header(x.headers, "Content-Length")) {
  3611. ret = read_content_without_length(strm, out);
  3612. } else {
  3613. auto is_invalid_value = false;
  3614. auto len = get_header_value_u64(
  3615. x.headers, "Content-Length",
  3616. (std::numeric_limits<uint64_t>::max)(), 0, is_invalid_value);
  3617. if (is_invalid_value) {
  3618. ret = false;
  3619. } else if (len > payload_max_length) {
  3620. exceed_payload_max_length = true;
  3621. skip_content_with_length(strm, len);
  3622. ret = false;
  3623. } else if (len > 0) {
  3624. ret = read_content_with_length(strm, len, std::move(progress), out);
  3625. }
  3626. }
  3627. if (!ret) {
  3628. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  3629. : StatusCode::BadRequest_400;
  3630. }
  3631. return ret;
  3632. });
  3633. }
  3634. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  3635. const std::string &path) {
  3636. std::string s = method;
  3637. s += " ";
  3638. s += path;
  3639. s += " HTTP/1.1\r\n";
  3640. return strm.write(s.data(), s.size());
  3641. }
  3642. inline ssize_t write_response_line(Stream &strm, int status) {
  3643. std::string s = "HTTP/1.1 ";
  3644. s += std::to_string(status);
  3645. s += " ";
  3646. s += httplib::status_message(status);
  3647. s += "\r\n";
  3648. return strm.write(s.data(), s.size());
  3649. }
  3650. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  3651. ssize_t write_len = 0;
  3652. for (const auto &x : headers) {
  3653. std::string s;
  3654. s = x.first;
  3655. s += ": ";
  3656. s += x.second;
  3657. s += "\r\n";
  3658. auto len = strm.write(s.data(), s.size());
  3659. if (len < 0) { return len; }
  3660. write_len += len;
  3661. }
  3662. auto len = strm.write("\r\n");
  3663. if (len < 0) { return len; }
  3664. write_len += len;
  3665. return write_len;
  3666. }
  3667. inline bool write_data(Stream &strm, const char *d, size_t l) {
  3668. size_t offset = 0;
  3669. while (offset < l) {
  3670. auto length = strm.write(d + offset, l - offset);
  3671. if (length < 0) { return false; }
  3672. offset += static_cast<size_t>(length);
  3673. }
  3674. return true;
  3675. }
  3676. template <typename T>
  3677. inline bool write_content_with_progress(Stream &strm,
  3678. const ContentProvider &content_provider,
  3679. size_t offset, size_t length,
  3680. T is_shutting_down,
  3681. const UploadProgress &upload_progress,
  3682. Error &error) {
  3683. size_t end_offset = offset + length;
  3684. size_t start_offset = offset;
  3685. auto ok = true;
  3686. DataSink data_sink;
  3687. data_sink.write = [&](const char *d, size_t l) -> bool {
  3688. if (ok) {
  3689. if (write_data(strm, d, l)) {
  3690. offset += l;
  3691. if (upload_progress && length > 0) {
  3692. size_t current_written = offset - start_offset;
  3693. if (!upload_progress(current_written, length)) {
  3694. ok = false;
  3695. return false;
  3696. }
  3697. }
  3698. } else {
  3699. ok = false;
  3700. }
  3701. }
  3702. return ok;
  3703. };
  3704. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  3705. while (offset < end_offset && !is_shutting_down()) {
  3706. if (!strm.wait_writable()) {
  3707. error = Error::Write;
  3708. return false;
  3709. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  3710. error = Error::Canceled;
  3711. return false;
  3712. } else if (!ok) {
  3713. error = Error::Write;
  3714. return false;
  3715. }
  3716. }
  3717. error = Error::Success;
  3718. return true;
  3719. }
  3720. template <typename T>
  3721. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  3722. size_t offset, size_t length, T is_shutting_down,
  3723. Error &error) {
  3724. return write_content_with_progress<T>(strm, content_provider, offset, length,
  3725. is_shutting_down, nullptr, error);
  3726. }
  3727. template <typename T>
  3728. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  3729. size_t offset, size_t length,
  3730. const T &is_shutting_down) {
  3731. auto error = Error::Success;
  3732. return write_content(strm, content_provider, offset, length, is_shutting_down,
  3733. error);
  3734. }
  3735. template <typename T>
  3736. inline bool
  3737. write_content_without_length(Stream &strm,
  3738. const ContentProvider &content_provider,
  3739. const T &is_shutting_down) {
  3740. size_t offset = 0;
  3741. auto data_available = true;
  3742. auto ok = true;
  3743. DataSink data_sink;
  3744. data_sink.write = [&](const char *d, size_t l) -> bool {
  3745. if (ok) {
  3746. offset += l;
  3747. if (!write_data(strm, d, l)) { ok = false; }
  3748. }
  3749. return ok;
  3750. };
  3751. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  3752. data_sink.done = [&](void) { data_available = false; };
  3753. while (data_available && !is_shutting_down()) {
  3754. if (!strm.wait_writable()) {
  3755. return false;
  3756. } else if (!content_provider(offset, 0, data_sink)) {
  3757. return false;
  3758. } else if (!ok) {
  3759. return false;
  3760. }
  3761. }
  3762. return true;
  3763. }
  3764. template <typename T, typename U>
  3765. inline bool
  3766. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  3767. const T &is_shutting_down, U &compressor, Error &error) {
  3768. size_t offset = 0;
  3769. auto data_available = true;
  3770. auto ok = true;
  3771. DataSink data_sink;
  3772. data_sink.write = [&](const char *d, size_t l) -> bool {
  3773. if (ok) {
  3774. data_available = l > 0;
  3775. offset += l;
  3776. std::string payload;
  3777. if (compressor.compress(d, l, false,
  3778. [&](const char *data, size_t data_len) {
  3779. payload.append(data, data_len);
  3780. return true;
  3781. })) {
  3782. if (!payload.empty()) {
  3783. // Emit chunked response header and footer for each chunk
  3784. auto chunk =
  3785. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  3786. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  3787. }
  3788. } else {
  3789. ok = false;
  3790. }
  3791. }
  3792. return ok;
  3793. };
  3794. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  3795. auto done_with_trailer = [&](const Headers *trailer) {
  3796. if (!ok) { return; }
  3797. data_available = false;
  3798. std::string payload;
  3799. if (!compressor.compress(nullptr, 0, true,
  3800. [&](const char *data, size_t data_len) {
  3801. payload.append(data, data_len);
  3802. return true;
  3803. })) {
  3804. ok = false;
  3805. return;
  3806. }
  3807. if (!payload.empty()) {
  3808. // Emit chunked response header and footer for each chunk
  3809. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  3810. if (!write_data(strm, chunk.data(), chunk.size())) {
  3811. ok = false;
  3812. return;
  3813. }
  3814. }
  3815. constexpr const char done_marker[] = "0\r\n";
  3816. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  3817. // Trailer
  3818. if (trailer) {
  3819. for (const auto &kv : *trailer) {
  3820. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  3821. if (!write_data(strm, field_line.data(), field_line.size())) {
  3822. ok = false;
  3823. }
  3824. }
  3825. }
  3826. constexpr const char crlf[] = "\r\n";
  3827. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  3828. };
  3829. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  3830. data_sink.done_with_trailer = [&](const Headers &trailer) {
  3831. done_with_trailer(&trailer);
  3832. };
  3833. while (data_available && !is_shutting_down()) {
  3834. if (!strm.wait_writable()) {
  3835. error = Error::Write;
  3836. return false;
  3837. } else if (!content_provider(offset, 0, data_sink)) {
  3838. error = Error::Canceled;
  3839. return false;
  3840. } else if (!ok) {
  3841. error = Error::Write;
  3842. return false;
  3843. }
  3844. }
  3845. error = Error::Success;
  3846. return true;
  3847. }
  3848. template <typename T, typename U>
  3849. inline bool write_content_chunked(Stream &strm,
  3850. const ContentProvider &content_provider,
  3851. const T &is_shutting_down, U &compressor) {
  3852. auto error = Error::Success;
  3853. return write_content_chunked(strm, content_provider, is_shutting_down,
  3854. compressor, error);
  3855. }
  3856. template <typename T>
  3857. inline bool redirect(T &cli, Request &req, Response &res,
  3858. const std::string &path, const std::string &location,
  3859. Error &error) {
  3860. Request new_req = req;
  3861. new_req.path = path;
  3862. new_req.redirect_count_ -= 1;
  3863. if (res.status == StatusCode::SeeOther_303 &&
  3864. (req.method != "GET" && req.method != "HEAD")) {
  3865. new_req.method = "GET";
  3866. new_req.body.clear();
  3867. new_req.headers.clear();
  3868. }
  3869. Response new_res;
  3870. auto ret = cli.send(new_req, new_res, error);
  3871. if (ret) {
  3872. req = new_req;
  3873. res = new_res;
  3874. if (res.location.empty()) { res.location = location; }
  3875. }
  3876. return ret;
  3877. }
  3878. inline std::string params_to_query_str(const Params &params) {
  3879. std::string query;
  3880. for (auto it = params.begin(); it != params.end(); ++it) {
  3881. if (it != params.begin()) { query += "&"; }
  3882. query += it->first;
  3883. query += "=";
  3884. query += encode_query_param(it->second);
  3885. }
  3886. return query;
  3887. }
  3888. inline void parse_query_text(const char *data, std::size_t size,
  3889. Params &params) {
  3890. std::set<std::string> cache;
  3891. split(data, data + size, '&', [&](const char *b, const char *e) {
  3892. std::string kv(b, e);
  3893. if (cache.find(kv) != cache.end()) { return; }
  3894. cache.insert(std::move(kv));
  3895. std::string key;
  3896. std::string val;
  3897. divide(b, static_cast<std::size_t>(e - b), '=',
  3898. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  3899. std::size_t rhs_size) {
  3900. key.assign(lhs_data, lhs_size);
  3901. val.assign(rhs_data, rhs_size);
  3902. });
  3903. if (!key.empty()) {
  3904. params.emplace(decode_url(key, true), decode_url(val, true));
  3905. }
  3906. });
  3907. }
  3908. inline void parse_query_text(const std::string &s, Params &params) {
  3909. parse_query_text(s.data(), s.size(), params);
  3910. }
  3911. inline bool parse_multipart_boundary(const std::string &content_type,
  3912. std::string &boundary) {
  3913. auto boundary_keyword = "boundary=";
  3914. auto pos = content_type.find(boundary_keyword);
  3915. if (pos == std::string::npos) { return false; }
  3916. auto end = content_type.find(';', pos);
  3917. auto beg = pos + strlen(boundary_keyword);
  3918. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  3919. return !boundary.empty();
  3920. }
  3921. inline void parse_disposition_params(const std::string &s, Params &params) {
  3922. std::set<std::string> cache;
  3923. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  3924. std::string kv(b, e);
  3925. if (cache.find(kv) != cache.end()) { return; }
  3926. cache.insert(kv);
  3927. std::string key;
  3928. std::string val;
  3929. split(b, e, '=', [&](const char *b2, const char *e2) {
  3930. if (key.empty()) {
  3931. key.assign(b2, e2);
  3932. } else {
  3933. val.assign(b2, e2);
  3934. }
  3935. });
  3936. if (!key.empty()) {
  3937. params.emplace(trim_double_quotes_copy((key)),
  3938. trim_double_quotes_copy((val)));
  3939. }
  3940. });
  3941. }
  3942. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  3943. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  3944. #else
  3945. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  3946. #endif
  3947. auto is_valid = [](const std::string &str) {
  3948. return std::all_of(str.cbegin(), str.cend(),
  3949. [](unsigned char c) { return std::isdigit(c); });
  3950. };
  3951. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  3952. const auto pos = static_cast<size_t>(6);
  3953. const auto len = static_cast<size_t>(s.size() - 6);
  3954. auto all_valid_ranges = true;
  3955. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  3956. if (!all_valid_ranges) { return; }
  3957. const auto it = std::find(b, e, '-');
  3958. if (it == e) {
  3959. all_valid_ranges = false;
  3960. return;
  3961. }
  3962. const auto lhs = std::string(b, it);
  3963. const auto rhs = std::string(it + 1, e);
  3964. if (!is_valid(lhs) || !is_valid(rhs)) {
  3965. all_valid_ranges = false;
  3966. return;
  3967. }
  3968. const auto first =
  3969. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  3970. const auto last =
  3971. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  3972. if ((first == -1 && last == -1) ||
  3973. (first != -1 && last != -1 && first > last)) {
  3974. all_valid_ranges = false;
  3975. return;
  3976. }
  3977. ranges.emplace_back(first, last);
  3978. });
  3979. return all_valid_ranges && !ranges.empty();
  3980. }
  3981. return false;
  3982. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  3983. }
  3984. #else
  3985. } catch (...) { return false; }
  3986. #endif
  3987. inline bool parse_accept_header(const std::string &s,
  3988. std::vector<std::string> &content_types) {
  3989. content_types.clear();
  3990. // Empty string is considered valid (no preference)
  3991. if (s.empty()) { return true; }
  3992. // Check for invalid patterns: leading/trailing commas or consecutive commas
  3993. if (s.front() == ',' || s.back() == ',' ||
  3994. s.find(",,") != std::string::npos) {
  3995. return false;
  3996. }
  3997. struct AcceptEntry {
  3998. std::string media_type;
  3999. double quality;
  4000. int order; // Original order in header
  4001. };
  4002. std::vector<AcceptEntry> entries;
  4003. int order = 0;
  4004. bool has_invalid_entry = false;
  4005. // Split by comma and parse each entry
  4006. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  4007. std::string entry(b, e);
  4008. entry = trim_copy(entry);
  4009. if (entry.empty()) {
  4010. has_invalid_entry = true;
  4011. return;
  4012. }
  4013. AcceptEntry accept_entry;
  4014. accept_entry.quality = 1.0; // Default quality
  4015. accept_entry.order = order++;
  4016. // Find q= parameter
  4017. auto q_pos = entry.find(";q=");
  4018. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  4019. if (q_pos != std::string::npos) {
  4020. // Extract media type (before q parameter)
  4021. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  4022. // Extract quality value
  4023. auto q_start = entry.find('=', q_pos) + 1;
  4024. auto q_end = entry.find(';', q_start);
  4025. if (q_end == std::string::npos) { q_end = entry.length(); }
  4026. std::string quality_str =
  4027. trim_copy(entry.substr(q_start, q_end - q_start));
  4028. if (quality_str.empty()) {
  4029. has_invalid_entry = true;
  4030. return;
  4031. }
  4032. try {
  4033. accept_entry.quality = std::stod(quality_str);
  4034. // Check if quality is in valid range [0.0, 1.0]
  4035. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  4036. has_invalid_entry = true;
  4037. return;
  4038. }
  4039. } catch (...) {
  4040. has_invalid_entry = true;
  4041. return;
  4042. }
  4043. } else {
  4044. // No quality parameter, use entire entry as media type
  4045. accept_entry.media_type = entry;
  4046. }
  4047. // Remove additional parameters from media type
  4048. auto param_pos = accept_entry.media_type.find(';');
  4049. if (param_pos != std::string::npos) {
  4050. accept_entry.media_type =
  4051. trim_copy(accept_entry.media_type.substr(0, param_pos));
  4052. }
  4053. // Basic validation of media type format
  4054. if (accept_entry.media_type.empty()) {
  4055. has_invalid_entry = true;
  4056. return;
  4057. }
  4058. // Check for basic media type format (should contain '/' or be '*')
  4059. if (accept_entry.media_type != "*" &&
  4060. accept_entry.media_type.find('/') == std::string::npos) {
  4061. has_invalid_entry = true;
  4062. return;
  4063. }
  4064. entries.push_back(accept_entry);
  4065. });
  4066. // Return false if any invalid entry was found
  4067. if (has_invalid_entry) { return false; }
  4068. // Sort by quality (descending), then by original order (ascending)
  4069. std::sort(entries.begin(), entries.end(),
  4070. [](const AcceptEntry &a, const AcceptEntry &b) {
  4071. if (a.quality != b.quality) {
  4072. return a.quality > b.quality; // Higher quality first
  4073. }
  4074. return a.order < b.order; // Earlier order first for same quality
  4075. });
  4076. // Extract sorted media types
  4077. content_types.reserve(entries.size());
  4078. for (const auto &entry : entries) {
  4079. content_types.push_back(entry.media_type);
  4080. }
  4081. return true;
  4082. }
  4083. class MultipartFormDataParser {
  4084. public:
  4085. MultipartFormDataParser() = default;
  4086. void set_boundary(std::string &&boundary) {
  4087. boundary_ = boundary;
  4088. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  4089. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  4090. }
  4091. bool is_valid() const { return is_valid_; }
  4092. bool parse(const char *buf, size_t n, const ContentReceiver &content_callback,
  4093. const MultipartContentHeader &header_callback) {
  4094. buf_append(buf, n);
  4095. while (buf_size() > 0) {
  4096. switch (state_) {
  4097. case 0: { // Initial boundary
  4098. auto pos = buf_find(dash_boundary_crlf_);
  4099. if (pos == buf_size()) { return true; }
  4100. buf_erase(pos + dash_boundary_crlf_.size());
  4101. state_ = 1;
  4102. break;
  4103. }
  4104. case 1: { // New entry
  4105. clear_file_info();
  4106. state_ = 2;
  4107. break;
  4108. }
  4109. case 2: { // Headers
  4110. auto pos = buf_find(crlf_);
  4111. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4112. while (pos < buf_size()) {
  4113. // Empty line
  4114. if (pos == 0) {
  4115. if (!header_callback(file_)) {
  4116. is_valid_ = false;
  4117. return false;
  4118. }
  4119. buf_erase(crlf_.size());
  4120. state_ = 3;
  4121. break;
  4122. }
  4123. const auto header = buf_head(pos);
  4124. if (!parse_header(header.data(), header.data() + header.size(),
  4125. [&](const std::string &, const std::string &) {})) {
  4126. is_valid_ = false;
  4127. return false;
  4128. }
  4129. // parse and emplace space trimmed headers into a map
  4130. if (!parse_header(
  4131. header.data(), header.data() + header.size(),
  4132. [&](const std::string &key, const std::string &val) {
  4133. file_.headers.emplace(key, val);
  4134. })) {
  4135. is_valid_ = false;
  4136. return false;
  4137. }
  4138. constexpr const char header_content_type[] = "Content-Type:";
  4139. if (start_with_case_ignore(header, header_content_type)) {
  4140. file_.content_type =
  4141. trim_copy(header.substr(str_len(header_content_type)));
  4142. } else {
  4143. thread_local const std::regex re_content_disposition(
  4144. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  4145. std::regex_constants::icase);
  4146. std::smatch m;
  4147. if (std::regex_match(header, m, re_content_disposition)) {
  4148. Params params;
  4149. parse_disposition_params(m[1], params);
  4150. auto it = params.find("name");
  4151. if (it != params.end()) {
  4152. file_.name = it->second;
  4153. } else {
  4154. is_valid_ = false;
  4155. return false;
  4156. }
  4157. it = params.find("filename");
  4158. if (it != params.end()) { file_.filename = it->second; }
  4159. it = params.find("filename*");
  4160. if (it != params.end()) {
  4161. // Only allow UTF-8 encoding...
  4162. thread_local const std::regex re_rfc5987_encoding(
  4163. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  4164. std::smatch m2;
  4165. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  4166. file_.filename = decode_url(m2[1], false); // override...
  4167. } else {
  4168. is_valid_ = false;
  4169. return false;
  4170. }
  4171. }
  4172. }
  4173. }
  4174. buf_erase(pos + crlf_.size());
  4175. pos = buf_find(crlf_);
  4176. }
  4177. if (state_ != 3) { return true; }
  4178. break;
  4179. }
  4180. case 3: { // Body
  4181. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  4182. auto pos = buf_find(crlf_dash_boundary_);
  4183. if (pos < buf_size()) {
  4184. if (!content_callback(buf_data(), pos)) {
  4185. is_valid_ = false;
  4186. return false;
  4187. }
  4188. buf_erase(pos + crlf_dash_boundary_.size());
  4189. state_ = 4;
  4190. } else {
  4191. auto len = buf_size() - crlf_dash_boundary_.size();
  4192. if (len > 0) {
  4193. if (!content_callback(buf_data(), len)) {
  4194. is_valid_ = false;
  4195. return false;
  4196. }
  4197. buf_erase(len);
  4198. }
  4199. return true;
  4200. }
  4201. break;
  4202. }
  4203. case 4: { // Boundary
  4204. if (crlf_.size() > buf_size()) { return true; }
  4205. if (buf_start_with(crlf_)) {
  4206. buf_erase(crlf_.size());
  4207. state_ = 1;
  4208. } else {
  4209. if (dash_.size() > buf_size()) { return true; }
  4210. if (buf_start_with(dash_)) {
  4211. buf_erase(dash_.size());
  4212. is_valid_ = true;
  4213. buf_erase(buf_size()); // Remove epilogue
  4214. } else {
  4215. return true;
  4216. }
  4217. }
  4218. break;
  4219. }
  4220. }
  4221. }
  4222. return true;
  4223. }
  4224. private:
  4225. void clear_file_info() {
  4226. file_.name.clear();
  4227. file_.filename.clear();
  4228. file_.content_type.clear();
  4229. file_.headers.clear();
  4230. }
  4231. bool start_with_case_ignore(const std::string &a, const char *b) const {
  4232. const auto b_len = strlen(b);
  4233. if (a.size() < b_len) { return false; }
  4234. for (size_t i = 0; i < b_len; i++) {
  4235. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  4236. return false;
  4237. }
  4238. }
  4239. return true;
  4240. }
  4241. const std::string dash_ = "--";
  4242. const std::string crlf_ = "\r\n";
  4243. std::string boundary_;
  4244. std::string dash_boundary_crlf_;
  4245. std::string crlf_dash_boundary_;
  4246. size_t state_ = 0;
  4247. bool is_valid_ = false;
  4248. MultipartFormData file_;
  4249. // Buffer
  4250. bool start_with(const std::string &a, size_t spos, size_t epos,
  4251. const std::string &b) const {
  4252. if (epos - spos < b.size()) { return false; }
  4253. for (size_t i = 0; i < b.size(); i++) {
  4254. if (a[i + spos] != b[i]) { return false; }
  4255. }
  4256. return true;
  4257. }
  4258. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  4259. const char *buf_data() const { return &buf_[buf_spos_]; }
  4260. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  4261. bool buf_start_with(const std::string &s) const {
  4262. return start_with(buf_, buf_spos_, buf_epos_, s);
  4263. }
  4264. size_t buf_find(const std::string &s) const {
  4265. auto c = s.front();
  4266. size_t off = buf_spos_;
  4267. while (off < buf_epos_) {
  4268. auto pos = off;
  4269. while (true) {
  4270. if (pos == buf_epos_) { return buf_size(); }
  4271. if (buf_[pos] == c) { break; }
  4272. pos++;
  4273. }
  4274. auto remaining_size = buf_epos_ - pos;
  4275. if (s.size() > remaining_size) { return buf_size(); }
  4276. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  4277. off = pos + 1;
  4278. }
  4279. return buf_size();
  4280. }
  4281. void buf_append(const char *data, size_t n) {
  4282. auto remaining_size = buf_size();
  4283. if (remaining_size > 0 && buf_spos_ > 0) {
  4284. for (size_t i = 0; i < remaining_size; i++) {
  4285. buf_[i] = buf_[buf_spos_ + i];
  4286. }
  4287. }
  4288. buf_spos_ = 0;
  4289. buf_epos_ = remaining_size;
  4290. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  4291. for (size_t i = 0; i < n; i++) {
  4292. buf_[buf_epos_ + i] = data[i];
  4293. }
  4294. buf_epos_ += n;
  4295. }
  4296. void buf_erase(size_t size) { buf_spos_ += size; }
  4297. std::string buf_;
  4298. size_t buf_spos_ = 0;
  4299. size_t buf_epos_ = 0;
  4300. };
  4301. inline std::string random_string(size_t length) {
  4302. constexpr const char data[] =
  4303. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  4304. thread_local auto engine([]() {
  4305. // std::random_device might actually be deterministic on some
  4306. // platforms, but due to lack of support in the c++ standard library,
  4307. // doing better requires either some ugly hacks or breaking portability.
  4308. std::random_device seed_gen;
  4309. // Request 128 bits of entropy for initialization
  4310. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  4311. return std::mt19937(seed_sequence);
  4312. }());
  4313. std::string result;
  4314. for (size_t i = 0; i < length; i++) {
  4315. result += data[engine() % (sizeof(data) - 1)];
  4316. }
  4317. return result;
  4318. }
  4319. inline std::string make_multipart_data_boundary() {
  4320. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  4321. }
  4322. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  4323. auto valid = true;
  4324. for (size_t i = 0; i < boundary.size(); i++) {
  4325. auto c = boundary[i];
  4326. if (!std::isalnum(c) && c != '-' && c != '_') {
  4327. valid = false;
  4328. break;
  4329. }
  4330. }
  4331. return valid;
  4332. }
  4333. template <typename T>
  4334. inline std::string
  4335. serialize_multipart_formdata_item_begin(const T &item,
  4336. const std::string &boundary) {
  4337. std::string body = "--" + boundary + "\r\n";
  4338. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4339. if (!item.filename.empty()) {
  4340. body += "; filename=\"" + item.filename + "\"";
  4341. }
  4342. body += "\r\n";
  4343. if (!item.content_type.empty()) {
  4344. body += "Content-Type: " + item.content_type + "\r\n";
  4345. }
  4346. body += "\r\n";
  4347. return body;
  4348. }
  4349. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  4350. inline std::string
  4351. serialize_multipart_formdata_finish(const std::string &boundary) {
  4352. return "--" + boundary + "--\r\n";
  4353. }
  4354. inline std::string
  4355. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  4356. return "multipart/form-data; boundary=" + boundary;
  4357. }
  4358. inline std::string
  4359. serialize_multipart_formdata(const MultipartFormDataItemsForClientInput &items,
  4360. const std::string &boundary, bool finish = true) {
  4361. std::string body;
  4362. for (const auto &item : items) {
  4363. body += serialize_multipart_formdata_item_begin(item, boundary);
  4364. body += item.content + serialize_multipart_formdata_item_end();
  4365. }
  4366. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  4367. return body;
  4368. }
  4369. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  4370. if (ranges.size() <= 1) return;
  4371. // Sort ranges by start position
  4372. std::sort(ranges.begin(), ranges.end(),
  4373. [](const Range &a, const Range &b) { return a.first < b.first; });
  4374. Ranges coalesced;
  4375. coalesced.reserve(ranges.size());
  4376. for (auto &r : ranges) {
  4377. auto first_pos = r.first;
  4378. auto last_pos = r.second;
  4379. // Handle special cases like in range_error
  4380. if (first_pos == -1 && last_pos == -1) {
  4381. first_pos = 0;
  4382. last_pos = static_cast<ssize_t>(content_length);
  4383. }
  4384. if (first_pos == -1) {
  4385. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  4386. last_pos = static_cast<ssize_t>(content_length) - 1;
  4387. }
  4388. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  4389. last_pos = static_cast<ssize_t>(content_length) - 1;
  4390. }
  4391. // Skip invalid ranges
  4392. if (!(0 <= first_pos && first_pos <= last_pos &&
  4393. last_pos < static_cast<ssize_t>(content_length))) {
  4394. continue;
  4395. }
  4396. // Coalesce with previous range if overlapping or adjacent (but not
  4397. // identical)
  4398. if (!coalesced.empty()) {
  4399. auto &prev = coalesced.back();
  4400. // Check if current range overlaps or is adjacent to previous range
  4401. // but don't coalesce identical ranges (allow duplicates)
  4402. if (first_pos <= prev.second + 1 &&
  4403. !(first_pos == prev.first && last_pos == prev.second)) {
  4404. // Extend the previous range
  4405. prev.second = (std::max)(prev.second, last_pos);
  4406. continue;
  4407. }
  4408. }
  4409. // Add new range
  4410. coalesced.emplace_back(first_pos, last_pos);
  4411. }
  4412. ranges = std::move(coalesced);
  4413. }
  4414. inline bool range_error(Request &req, Response &res) {
  4415. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  4416. ssize_t content_len = static_cast<ssize_t>(
  4417. res.content_length_ ? res.content_length_ : res.body.size());
  4418. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  4419. size_t overwrapping_count = 0;
  4420. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  4421. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  4422. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  4423. // Too many ranges
  4424. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  4425. for (auto &r : req.ranges) {
  4426. auto &first_pos = r.first;
  4427. auto &last_pos = r.second;
  4428. if (first_pos == -1 && last_pos == -1) {
  4429. first_pos = 0;
  4430. last_pos = content_len;
  4431. }
  4432. if (first_pos == -1) {
  4433. first_pos = content_len - last_pos;
  4434. last_pos = content_len - 1;
  4435. }
  4436. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  4437. // A client can limit the number of bytes requested without knowing the
  4438. // size of the selected representation. If the last-pos value is absent,
  4439. // or if the value is greater than or equal to the current length of the
  4440. // representation data, the byte range is interpreted as the remainder of
  4441. // the representation (i.e., the server replaces the value of last-pos
  4442. // with a value that is one less than the current length of the selected
  4443. // representation).
  4444. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  4445. if (last_pos == -1 || last_pos >= content_len) {
  4446. last_pos = content_len - 1;
  4447. }
  4448. // Range must be within content length
  4449. if (!(0 <= first_pos && first_pos <= last_pos &&
  4450. last_pos <= content_len - 1)) {
  4451. return true;
  4452. }
  4453. // Request must not have more than two overlapping ranges
  4454. for (const auto &processed_range : processed_ranges) {
  4455. if (!(last_pos < processed_range.first ||
  4456. first_pos > processed_range.second)) {
  4457. overwrapping_count++;
  4458. if (overwrapping_count > 2) { return true; }
  4459. break; // Only count once per range
  4460. }
  4461. }
  4462. processed_ranges.emplace_back(first_pos, last_pos);
  4463. }
  4464. // After validation, coalesce overlapping ranges as per RFC 9110
  4465. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  4466. }
  4467. return false;
  4468. }
  4469. inline std::pair<size_t, size_t>
  4470. get_range_offset_and_length(Range r, size_t content_length) {
  4471. assert(r.first != -1 && r.second != -1);
  4472. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  4473. assert(r.first <= r.second &&
  4474. r.second < static_cast<ssize_t>(content_length));
  4475. (void)(content_length);
  4476. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  4477. }
  4478. inline std::string make_content_range_header_field(
  4479. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  4480. auto st = offset_and_length.first;
  4481. auto ed = st + offset_and_length.second - 1;
  4482. std::string field = "bytes ";
  4483. field += std::to_string(st);
  4484. field += "-";
  4485. field += std::to_string(ed);
  4486. field += "/";
  4487. field += std::to_string(content_length);
  4488. return field;
  4489. }
  4490. template <typename SToken, typename CToken, typename Content>
  4491. bool process_multipart_ranges_data(const Request &req,
  4492. const std::string &boundary,
  4493. const std::string &content_type,
  4494. size_t content_length, SToken stoken,
  4495. CToken ctoken, Content content) {
  4496. for (size_t i = 0; i < req.ranges.size(); i++) {
  4497. ctoken("--");
  4498. stoken(boundary);
  4499. ctoken("\r\n");
  4500. if (!content_type.empty()) {
  4501. ctoken("Content-Type: ");
  4502. stoken(content_type);
  4503. ctoken("\r\n");
  4504. }
  4505. auto offset_and_length =
  4506. get_range_offset_and_length(req.ranges[i], content_length);
  4507. ctoken("Content-Range: ");
  4508. stoken(make_content_range_header_field(offset_and_length, content_length));
  4509. ctoken("\r\n");
  4510. ctoken("\r\n");
  4511. if (!content(offset_and_length.first, offset_and_length.second)) {
  4512. return false;
  4513. }
  4514. ctoken("\r\n");
  4515. }
  4516. ctoken("--");
  4517. stoken(boundary);
  4518. ctoken("--");
  4519. return true;
  4520. }
  4521. inline void make_multipart_ranges_data(const Request &req, Response &res,
  4522. const std::string &boundary,
  4523. const std::string &content_type,
  4524. size_t content_length,
  4525. std::string &data) {
  4526. process_multipart_ranges_data(
  4527. req, boundary, content_type, content_length,
  4528. [&](const std::string &token) { data += token; },
  4529. [&](const std::string &token) { data += token; },
  4530. [&](size_t offset, size_t length) {
  4531. assert(offset + length <= content_length);
  4532. data += res.body.substr(offset, length);
  4533. return true;
  4534. });
  4535. }
  4536. inline size_t get_multipart_ranges_data_length(const Request &req,
  4537. const std::string &boundary,
  4538. const std::string &content_type,
  4539. size_t content_length) {
  4540. size_t data_length = 0;
  4541. process_multipart_ranges_data(
  4542. req, boundary, content_type, content_length,
  4543. [&](const std::string &token) { data_length += token.size(); },
  4544. [&](const std::string &token) { data_length += token.size(); },
  4545. [&](size_t /*offset*/, size_t length) {
  4546. data_length += length;
  4547. return true;
  4548. });
  4549. return data_length;
  4550. }
  4551. template <typename T>
  4552. inline bool
  4553. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  4554. const std::string &boundary,
  4555. const std::string &content_type,
  4556. size_t content_length, const T &is_shutting_down) {
  4557. return process_multipart_ranges_data(
  4558. req, boundary, content_type, content_length,
  4559. [&](const std::string &token) { strm.write(token); },
  4560. [&](const std::string &token) { strm.write(token); },
  4561. [&](size_t offset, size_t length) {
  4562. return write_content(strm, res.content_provider_, offset, length,
  4563. is_shutting_down);
  4564. });
  4565. }
  4566. inline bool expect_content(const Request &req) {
  4567. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  4568. req.method == "DELETE") {
  4569. return true;
  4570. }
  4571. if (req.has_header("Content-Length") &&
  4572. req.get_header_value_u64("Content-Length") > 0) {
  4573. return true;
  4574. }
  4575. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  4576. return false;
  4577. }
  4578. inline bool has_crlf(const std::string &s) {
  4579. auto p = s.c_str();
  4580. while (*p) {
  4581. if (*p == '\r' || *p == '\n') { return true; }
  4582. p++;
  4583. }
  4584. return false;
  4585. }
  4586. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4587. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  4588. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  4589. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  4590. unsigned int hash_length = 0;
  4591. unsigned char hash[EVP_MAX_MD_SIZE];
  4592. EVP_DigestInit_ex(context.get(), algo, nullptr);
  4593. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  4594. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  4595. std::stringstream ss;
  4596. for (auto i = 0u; i < hash_length; ++i) {
  4597. ss << std::hex << std::setw(2) << std::setfill('0')
  4598. << static_cast<unsigned int>(hash[i]);
  4599. }
  4600. return ss.str();
  4601. }
  4602. inline std::string MD5(const std::string &s) {
  4603. return message_digest(s, EVP_md5());
  4604. }
  4605. inline std::string SHA_256(const std::string &s) {
  4606. return message_digest(s, EVP_sha256());
  4607. }
  4608. inline std::string SHA_512(const std::string &s) {
  4609. return message_digest(s, EVP_sha512());
  4610. }
  4611. inline std::pair<std::string, std::string> make_digest_authentication_header(
  4612. const Request &req, const std::map<std::string, std::string> &auth,
  4613. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  4614. const std::string &password, bool is_proxy = false) {
  4615. std::string nc;
  4616. {
  4617. std::stringstream ss;
  4618. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  4619. nc = ss.str();
  4620. }
  4621. std::string qop;
  4622. if (auth.find("qop") != auth.end()) {
  4623. qop = auth.at("qop");
  4624. if (qop.find("auth-int") != std::string::npos) {
  4625. qop = "auth-int";
  4626. } else if (qop.find("auth") != std::string::npos) {
  4627. qop = "auth";
  4628. } else {
  4629. qop.clear();
  4630. }
  4631. }
  4632. std::string algo = "MD5";
  4633. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  4634. std::string response;
  4635. {
  4636. auto H = algo == "SHA-256" ? detail::SHA_256
  4637. : algo == "SHA-512" ? detail::SHA_512
  4638. : detail::MD5;
  4639. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  4640. auto A2 = req.method + ":" + req.path;
  4641. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  4642. if (qop.empty()) {
  4643. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  4644. } else {
  4645. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  4646. ":" + qop + ":" + H(A2));
  4647. }
  4648. }
  4649. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  4650. auto field = "Digest username=\"" + username + "\", realm=\"" +
  4651. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  4652. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  4653. (qop.empty() ? ", response=\""
  4654. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  4655. cnonce + "\", response=\"") +
  4656. response + "\"" +
  4657. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  4658. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  4659. return std::make_pair(key, field);
  4660. }
  4661. inline bool is_ssl_peer_could_be_closed(SSL *ssl, socket_t sock) {
  4662. detail::set_nonblocking(sock, true);
  4663. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  4664. char buf[1];
  4665. return !SSL_peek(ssl, buf, 1) &&
  4666. SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
  4667. }
  4668. #ifdef _WIN32
  4669. // NOTE: This code came up with the following stackoverflow post:
  4670. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  4671. inline bool load_system_certs_on_windows(X509_STORE *store) {
  4672. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  4673. if (!hStore) { return false; }
  4674. auto result = false;
  4675. PCCERT_CONTEXT pContext = NULL;
  4676. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  4677. nullptr) {
  4678. auto encoded_cert =
  4679. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  4680. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  4681. if (x509) {
  4682. X509_STORE_add_cert(store, x509);
  4683. X509_free(x509);
  4684. result = true;
  4685. }
  4686. }
  4687. CertFreeCertificateContext(pContext);
  4688. CertCloseStore(hStore, 0);
  4689. return result;
  4690. }
  4691. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
  4692. #if TARGET_OS_OSX
  4693. template <typename T>
  4694. using CFObjectPtr =
  4695. std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
  4696. inline void cf_object_ptr_deleter(CFTypeRef obj) {
  4697. if (obj) { CFRelease(obj); }
  4698. }
  4699. inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  4700. CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
  4701. CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,
  4702. kCFBooleanTrue};
  4703. CFObjectPtr<CFDictionaryRef> query(
  4704. CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,
  4705. sizeof(keys) / sizeof(keys[0]),
  4706. &kCFTypeDictionaryKeyCallBacks,
  4707. &kCFTypeDictionaryValueCallBacks),
  4708. cf_object_ptr_deleter);
  4709. if (!query) { return false; }
  4710. CFTypeRef security_items = nullptr;
  4711. if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
  4712. CFArrayGetTypeID() != CFGetTypeID(security_items)) {
  4713. return false;
  4714. }
  4715. certs.reset(reinterpret_cast<CFArrayRef>(security_items));
  4716. return true;
  4717. }
  4718. inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  4719. CFArrayRef root_security_items = nullptr;
  4720. if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
  4721. return false;
  4722. }
  4723. certs.reset(root_security_items);
  4724. return true;
  4725. }
  4726. inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
  4727. auto result = false;
  4728. for (auto i = 0; i < CFArrayGetCount(certs); ++i) {
  4729. const auto cert = reinterpret_cast<const __SecCertificate *>(
  4730. CFArrayGetValueAtIndex(certs, i));
  4731. if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }
  4732. CFDataRef cert_data = nullptr;
  4733. if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=
  4734. errSecSuccess) {
  4735. continue;
  4736. }
  4737. CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
  4738. auto encoded_cert = static_cast<const unsigned char *>(
  4739. CFDataGetBytePtr(cert_data_ptr.get()));
  4740. auto x509 =
  4741. d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
  4742. if (x509) {
  4743. X509_STORE_add_cert(store, x509);
  4744. X509_free(x509);
  4745. result = true;
  4746. }
  4747. }
  4748. return result;
  4749. }
  4750. inline bool load_system_certs_on_macos(X509_STORE *store) {
  4751. auto result = false;
  4752. CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);
  4753. if (retrieve_certs_from_keychain(certs) && certs) {
  4754. result = add_certs_to_x509_store(certs.get(), store);
  4755. }
  4756. if (retrieve_root_certs_from_keychain(certs) && certs) {
  4757. result = add_certs_to_x509_store(certs.get(), store) || result;
  4758. }
  4759. return result;
  4760. }
  4761. #endif // TARGET_OS_OSX
  4762. #endif // _WIN32
  4763. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  4764. #ifdef _WIN32
  4765. class WSInit {
  4766. public:
  4767. WSInit() {
  4768. WSADATA wsaData;
  4769. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  4770. }
  4771. ~WSInit() {
  4772. if (is_valid_) WSACleanup();
  4773. }
  4774. bool is_valid_ = false;
  4775. };
  4776. static WSInit wsinit_;
  4777. #endif
  4778. inline bool parse_www_authenticate(const Response &res,
  4779. std::map<std::string, std::string> &auth,
  4780. bool is_proxy) {
  4781. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  4782. if (res.has_header(auth_key)) {
  4783. thread_local auto re =
  4784. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  4785. auto s = res.get_header_value(auth_key);
  4786. auto pos = s.find(' ');
  4787. if (pos != std::string::npos) {
  4788. auto type = s.substr(0, pos);
  4789. if (type == "Basic") {
  4790. return false;
  4791. } else if (type == "Digest") {
  4792. s = s.substr(pos + 1);
  4793. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  4794. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  4795. const auto &m = *i;
  4796. auto key = s.substr(static_cast<size_t>(m.position(1)),
  4797. static_cast<size_t>(m.length(1)));
  4798. auto val = m.length(2) > 0
  4799. ? s.substr(static_cast<size_t>(m.position(2)),
  4800. static_cast<size_t>(m.length(2)))
  4801. : s.substr(static_cast<size_t>(m.position(3)),
  4802. static_cast<size_t>(m.length(3)));
  4803. auth[key] = val;
  4804. }
  4805. return true;
  4806. }
  4807. }
  4808. }
  4809. return false;
  4810. }
  4811. class ContentProviderAdapter {
  4812. public:
  4813. explicit ContentProviderAdapter(
  4814. ContentProviderWithoutLength &&content_provider)
  4815. : content_provider_(content_provider) {}
  4816. bool operator()(size_t offset, size_t, DataSink &sink) {
  4817. return content_provider_(offset, sink);
  4818. }
  4819. private:
  4820. ContentProviderWithoutLength content_provider_;
  4821. };
  4822. } // namespace detail
  4823. inline std::string hosted_at(const std::string &hostname) {
  4824. std::vector<std::string> addrs;
  4825. hosted_at(hostname, addrs);
  4826. if (addrs.empty()) { return std::string(); }
  4827. return addrs[0];
  4828. }
  4829. inline void hosted_at(const std::string &hostname,
  4830. std::vector<std::string> &addrs) {
  4831. struct addrinfo hints;
  4832. struct addrinfo *result;
  4833. memset(&hints, 0, sizeof(struct addrinfo));
  4834. hints.ai_family = AF_UNSPEC;
  4835. hints.ai_socktype = SOCK_STREAM;
  4836. hints.ai_protocol = 0;
  4837. if (getaddrinfo(hostname.c_str(), nullptr, &hints, &result)) {
  4838. #if defined __linux__ && !defined __ANDROID__
  4839. res_init();
  4840. #endif
  4841. return;
  4842. }
  4843. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4844. for (auto rp = result; rp; rp = rp->ai_next) {
  4845. const auto &addr =
  4846. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  4847. std::string ip;
  4848. auto dummy = -1;
  4849. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  4850. dummy)) {
  4851. addrs.push_back(ip);
  4852. }
  4853. }
  4854. }
  4855. inline std::string append_query_params(const std::string &path,
  4856. const Params &params) {
  4857. std::string path_with_query = path;
  4858. thread_local const std::regex re("[^?]+\\?.*");
  4859. auto delm = std::regex_match(path, re) ? '&' : '?';
  4860. path_with_query += delm + detail::params_to_query_str(params);
  4861. return path_with_query;
  4862. }
  4863. // Header utilities
  4864. inline std::pair<std::string, std::string>
  4865. make_range_header(const Ranges &ranges) {
  4866. std::string field = "bytes=";
  4867. auto i = 0;
  4868. for (const auto &r : ranges) {
  4869. if (i != 0) { field += ", "; }
  4870. if (r.first != -1) { field += std::to_string(r.first); }
  4871. field += '-';
  4872. if (r.second != -1) { field += std::to_string(r.second); }
  4873. i++;
  4874. }
  4875. return std::make_pair("Range", std::move(field));
  4876. }
  4877. inline std::pair<std::string, std::string>
  4878. make_basic_authentication_header(const std::string &username,
  4879. const std::string &password, bool is_proxy) {
  4880. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  4881. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  4882. return std::make_pair(key, std::move(field));
  4883. }
  4884. inline std::pair<std::string, std::string>
  4885. make_bearer_token_authentication_header(const std::string &token,
  4886. bool is_proxy = false) {
  4887. auto field = "Bearer " + token;
  4888. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  4889. return std::make_pair(key, std::move(field));
  4890. }
  4891. // Request implementation
  4892. inline bool Request::has_header(const std::string &key) const {
  4893. return detail::has_header(headers, key);
  4894. }
  4895. inline std::string Request::get_header_value(const std::string &key,
  4896. const char *def, size_t id) const {
  4897. return detail::get_header_value(headers, key, def, id);
  4898. }
  4899. inline size_t Request::get_header_value_count(const std::string &key) const {
  4900. auto r = headers.equal_range(key);
  4901. return static_cast<size_t>(std::distance(r.first, r.second));
  4902. }
  4903. inline void Request::set_header(const std::string &key,
  4904. const std::string &val) {
  4905. if (detail::fields::is_field_name(key) &&
  4906. detail::fields::is_field_value(val)) {
  4907. headers.emplace(key, val);
  4908. }
  4909. }
  4910. inline bool Request::has_param(const std::string &key) const {
  4911. return params.find(key) != params.end();
  4912. }
  4913. inline std::string Request::get_param_value(const std::string &key,
  4914. size_t id) const {
  4915. auto rng = params.equal_range(key);
  4916. auto it = rng.first;
  4917. std::advance(it, static_cast<ssize_t>(id));
  4918. if (it != rng.second) { return it->second; }
  4919. return std::string();
  4920. }
  4921. inline size_t Request::get_param_value_count(const std::string &key) const {
  4922. auto r = params.equal_range(key);
  4923. return static_cast<size_t>(std::distance(r.first, r.second));
  4924. }
  4925. inline bool Request::is_multipart_form_data() const {
  4926. const auto &content_type = get_header_value("Content-Type");
  4927. return !content_type.rfind("multipart/form-data", 0);
  4928. }
  4929. inline bool Request::has_file(const std::string &key) const {
  4930. return files.find(key) != files.end();
  4931. }
  4932. inline MultipartFormData Request::get_file_value(const std::string &key) const {
  4933. auto it = files.find(key);
  4934. if (it != files.end()) { return it->second; }
  4935. return MultipartFormData();
  4936. }
  4937. inline std::vector<MultipartFormData>
  4938. Request::get_file_values(const std::string &key) const {
  4939. std::vector<MultipartFormData> values;
  4940. auto rng = files.equal_range(key);
  4941. for (auto it = rng.first; it != rng.second; it++) {
  4942. values.push_back(it->second);
  4943. }
  4944. return values;
  4945. }
  4946. // Response implementation
  4947. inline bool Response::has_header(const std::string &key) const {
  4948. return headers.find(key) != headers.end();
  4949. }
  4950. inline std::string Response::get_header_value(const std::string &key,
  4951. const char *def,
  4952. size_t id) const {
  4953. return detail::get_header_value(headers, key, def, id);
  4954. }
  4955. inline size_t Response::get_header_value_count(const std::string &key) const {
  4956. auto r = headers.equal_range(key);
  4957. return static_cast<size_t>(std::distance(r.first, r.second));
  4958. }
  4959. inline void Response::set_header(const std::string &key,
  4960. const std::string &val) {
  4961. if (detail::fields::is_field_name(key) &&
  4962. detail::fields::is_field_value(val)) {
  4963. headers.emplace(key, val);
  4964. }
  4965. }
  4966. inline void Response::set_redirect(const std::string &url, int stat) {
  4967. if (detail::fields::is_field_value(url)) {
  4968. set_header("Location", url);
  4969. if (300 <= stat && stat < 400) {
  4970. this->status = stat;
  4971. } else {
  4972. this->status = StatusCode::Found_302;
  4973. }
  4974. }
  4975. }
  4976. inline void Response::set_content(const char *s, size_t n,
  4977. const std::string &content_type) {
  4978. body.assign(s, n);
  4979. auto rng = headers.equal_range("Content-Type");
  4980. headers.erase(rng.first, rng.second);
  4981. set_header("Content-Type", content_type);
  4982. }
  4983. inline void Response::set_content(const std::string &s,
  4984. const std::string &content_type) {
  4985. set_content(s.data(), s.size(), content_type);
  4986. }
  4987. inline void Response::set_content(std::string &&s,
  4988. const std::string &content_type) {
  4989. body = std::move(s);
  4990. auto rng = headers.equal_range("Content-Type");
  4991. headers.erase(rng.first, rng.second);
  4992. set_header("Content-Type", content_type);
  4993. }
  4994. inline void Response::set_content_provider(
  4995. size_t in_length, const std::string &content_type, ContentProvider provider,
  4996. ContentProviderResourceReleaser resource_releaser) {
  4997. set_header("Content-Type", content_type);
  4998. content_length_ = in_length;
  4999. if (in_length > 0) { content_provider_ = std::move(provider); }
  5000. content_provider_resource_releaser_ = std::move(resource_releaser);
  5001. is_chunked_content_provider_ = false;
  5002. }
  5003. inline void Response::set_content_provider(
  5004. const std::string &content_type, ContentProviderWithoutLength provider,
  5005. ContentProviderResourceReleaser resource_releaser) {
  5006. set_header("Content-Type", content_type);
  5007. content_length_ = 0;
  5008. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  5009. content_provider_resource_releaser_ = std::move(resource_releaser);
  5010. is_chunked_content_provider_ = false;
  5011. }
  5012. inline void Response::set_chunked_content_provider(
  5013. const std::string &content_type, ContentProviderWithoutLength provider,
  5014. ContentProviderResourceReleaser resource_releaser) {
  5015. set_header("Content-Type", content_type);
  5016. content_length_ = 0;
  5017. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  5018. content_provider_resource_releaser_ = std::move(resource_releaser);
  5019. is_chunked_content_provider_ = true;
  5020. }
  5021. inline void Response::set_file_content(const std::string &path,
  5022. const std::string &content_type) {
  5023. file_content_path_ = path;
  5024. file_content_content_type_ = content_type;
  5025. }
  5026. inline void Response::set_file_content(const std::string &path) {
  5027. file_content_path_ = path;
  5028. }
  5029. // Result implementation
  5030. inline bool Result::has_request_header(const std::string &key) const {
  5031. return request_headers_.find(key) != request_headers_.end();
  5032. }
  5033. inline std::string Result::get_request_header_value(const std::string &key,
  5034. const char *def,
  5035. size_t id) const {
  5036. return detail::get_header_value(request_headers_, key, def, id);
  5037. }
  5038. inline size_t
  5039. Result::get_request_header_value_count(const std::string &key) const {
  5040. auto r = request_headers_.equal_range(key);
  5041. return static_cast<size_t>(std::distance(r.first, r.second));
  5042. }
  5043. // Stream implementation
  5044. inline ssize_t Stream::write(const char *ptr) {
  5045. return write(ptr, strlen(ptr));
  5046. }
  5047. inline ssize_t Stream::write(const std::string &s) {
  5048. return write(s.data(), s.size());
  5049. }
  5050. namespace detail {
  5051. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  5052. time_t timeout_sec, time_t timeout_usec,
  5053. time_t &actual_timeout_sec,
  5054. time_t &actual_timeout_usec) {
  5055. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  5056. auto actual_timeout_msec =
  5057. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  5058. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  5059. actual_timeout_sec = actual_timeout_msec / 1000;
  5060. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  5061. }
  5062. // Socket stream implementation
  5063. inline SocketStream::SocketStream(
  5064. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5065. time_t write_timeout_sec, time_t write_timeout_usec,
  5066. time_t max_timeout_msec,
  5067. std::chrono::time_point<std::chrono::steady_clock> start_time)
  5068. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  5069. read_timeout_usec_(read_timeout_usec),
  5070. write_timeout_sec_(write_timeout_sec),
  5071. write_timeout_usec_(write_timeout_usec),
  5072. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  5073. read_buff_(read_buff_size_, 0) {}
  5074. inline SocketStream::~SocketStream() = default;
  5075. inline bool SocketStream::is_readable() const {
  5076. return read_buff_off_ < read_buff_content_size_;
  5077. }
  5078. inline bool SocketStream::wait_readable() const {
  5079. if (max_timeout_msec_ <= 0) {
  5080. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  5081. }
  5082. time_t read_timeout_sec;
  5083. time_t read_timeout_usec;
  5084. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  5085. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  5086. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  5087. }
  5088. inline bool SocketStream::wait_writable() const {
  5089. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  5090. is_socket_alive(sock_);
  5091. }
  5092. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  5093. #ifdef _WIN32
  5094. size =
  5095. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  5096. #else
  5097. size = (std::min)(size,
  5098. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  5099. #endif
  5100. if (read_buff_off_ < read_buff_content_size_) {
  5101. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  5102. if (size <= remaining_size) {
  5103. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  5104. read_buff_off_ += size;
  5105. return static_cast<ssize_t>(size);
  5106. } else {
  5107. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  5108. read_buff_off_ += remaining_size;
  5109. return static_cast<ssize_t>(remaining_size);
  5110. }
  5111. }
  5112. if (!wait_readable()) { return -1; }
  5113. read_buff_off_ = 0;
  5114. read_buff_content_size_ = 0;
  5115. if (size < read_buff_size_) {
  5116. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  5117. CPPHTTPLIB_RECV_FLAGS);
  5118. if (n <= 0) {
  5119. return n;
  5120. } else if (n <= static_cast<ssize_t>(size)) {
  5121. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  5122. return n;
  5123. } else {
  5124. memcpy(ptr, read_buff_.data(), size);
  5125. read_buff_off_ = size;
  5126. read_buff_content_size_ = static_cast<size_t>(n);
  5127. return static_cast<ssize_t>(size);
  5128. }
  5129. } else {
  5130. return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  5131. }
  5132. }
  5133. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  5134. if (!wait_writable()) { return -1; }
  5135. #if defined(_WIN32) && !defined(_WIN64)
  5136. size =
  5137. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  5138. #endif
  5139. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  5140. }
  5141. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  5142. int &port) const {
  5143. return detail::get_remote_ip_and_port(sock_, ip, port);
  5144. }
  5145. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  5146. int &port) const {
  5147. return detail::get_local_ip_and_port(sock_, ip, port);
  5148. }
  5149. inline socket_t SocketStream::socket() const { return sock_; }
  5150. inline time_t SocketStream::duration() const {
  5151. return std::chrono::duration_cast<std::chrono::milliseconds>(
  5152. std::chrono::steady_clock::now() - start_time_)
  5153. .count();
  5154. }
  5155. // Buffer stream implementation
  5156. inline bool BufferStream::is_readable() const { return true; }
  5157. inline bool BufferStream::wait_readable() const { return true; }
  5158. inline bool BufferStream::wait_writable() const { return true; }
  5159. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  5160. #if defined(_MSC_VER) && _MSC_VER < 1910
  5161. auto len_read = buffer._Copy_s(ptr, size, size, position);
  5162. #else
  5163. auto len_read = buffer.copy(ptr, size, position);
  5164. #endif
  5165. position += static_cast<size_t>(len_read);
  5166. return static_cast<ssize_t>(len_read);
  5167. }
  5168. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  5169. buffer.append(ptr, size);
  5170. return static_cast<ssize_t>(size);
  5171. }
  5172. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  5173. int & /*port*/) const {}
  5174. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  5175. int & /*port*/) const {}
  5176. inline socket_t BufferStream::socket() const { return 0; }
  5177. inline time_t BufferStream::duration() const { return 0; }
  5178. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  5179. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  5180. : MatcherBase(pattern) {
  5181. constexpr const char marker[] = "/:";
  5182. // One past the last ending position of a path param substring
  5183. std::size_t last_param_end = 0;
  5184. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5185. // Needed to ensure that parameter names are unique during matcher
  5186. // construction
  5187. // If exceptions are disabled, only last duplicate path
  5188. // parameter will be set
  5189. std::unordered_set<std::string> param_name_set;
  5190. #endif
  5191. while (true) {
  5192. const auto marker_pos = pattern.find(
  5193. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  5194. if (marker_pos == std::string::npos) { break; }
  5195. static_fragments_.push_back(
  5196. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  5197. const auto param_name_start = marker_pos + str_len(marker);
  5198. auto sep_pos = pattern.find(separator, param_name_start);
  5199. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  5200. auto param_name =
  5201. pattern.substr(param_name_start, sep_pos - param_name_start);
  5202. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5203. if (param_name_set.find(param_name) != param_name_set.cend()) {
  5204. std::string msg = "Encountered path parameter '" + param_name +
  5205. "' multiple times in route pattern '" + pattern + "'.";
  5206. throw std::invalid_argument(msg);
  5207. }
  5208. #endif
  5209. param_names_.push_back(std::move(param_name));
  5210. last_param_end = sep_pos + 1;
  5211. }
  5212. if (last_param_end < pattern.length()) {
  5213. static_fragments_.push_back(pattern.substr(last_param_end));
  5214. }
  5215. }
  5216. inline bool PathParamsMatcher::match(Request &request) const {
  5217. request.matches = std::smatch();
  5218. request.path_params.clear();
  5219. request.path_params.reserve(param_names_.size());
  5220. // One past the position at which the path matched the pattern last time
  5221. std::size_t starting_pos = 0;
  5222. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  5223. const auto &fragment = static_fragments_[i];
  5224. if (starting_pos + fragment.length() > request.path.length()) {
  5225. return false;
  5226. }
  5227. // Avoid unnecessary allocation by using strncmp instead of substr +
  5228. // comparison
  5229. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  5230. fragment.length()) != 0) {
  5231. return false;
  5232. }
  5233. starting_pos += fragment.length();
  5234. // Should only happen when we have a static fragment after a param
  5235. // Example: '/users/:id/subscriptions'
  5236. // The 'subscriptions' fragment here does not have a corresponding param
  5237. if (i >= param_names_.size()) { continue; }
  5238. auto sep_pos = request.path.find(separator, starting_pos);
  5239. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  5240. const auto &param_name = param_names_[i];
  5241. request.path_params.emplace(
  5242. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  5243. // Mark everything up to '/' as matched
  5244. starting_pos = sep_pos + 1;
  5245. }
  5246. // Returns false if the path is longer than the pattern
  5247. return starting_pos >= request.path.length();
  5248. }
  5249. inline bool RegexMatcher::match(Request &request) const {
  5250. request.path_params.clear();
  5251. return std::regex_match(request.path, request.matches, regex_);
  5252. }
  5253. } // namespace detail
  5254. // HTTP server implementation
  5255. inline Server::Server()
  5256. : new_task_queue(
  5257. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  5258. #ifndef _WIN32
  5259. signal(SIGPIPE, SIG_IGN);
  5260. #endif
  5261. }
  5262. inline Server::~Server() = default;
  5263. inline std::unique_ptr<detail::MatcherBase>
  5264. Server::make_matcher(const std::string &pattern) {
  5265. if (pattern.find("/:") != std::string::npos) {
  5266. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  5267. } else {
  5268. return detail::make_unique<detail::RegexMatcher>(pattern);
  5269. }
  5270. }
  5271. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  5272. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5273. return *this;
  5274. }
  5275. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  5276. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5277. return *this;
  5278. }
  5279. inline Server &Server::Post(const std::string &pattern,
  5280. HandlerWithContentReader handler) {
  5281. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5282. std::move(handler));
  5283. return *this;
  5284. }
  5285. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  5286. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5287. return *this;
  5288. }
  5289. inline Server &Server::Put(const std::string &pattern,
  5290. HandlerWithContentReader handler) {
  5291. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5292. std::move(handler));
  5293. return *this;
  5294. }
  5295. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  5296. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5297. return *this;
  5298. }
  5299. inline Server &Server::Patch(const std::string &pattern,
  5300. HandlerWithContentReader handler) {
  5301. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5302. std::move(handler));
  5303. return *this;
  5304. }
  5305. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  5306. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5307. return *this;
  5308. }
  5309. inline Server &Server::Delete(const std::string &pattern,
  5310. HandlerWithContentReader handler) {
  5311. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5312. std::move(handler));
  5313. return *this;
  5314. }
  5315. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  5316. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5317. return *this;
  5318. }
  5319. inline bool Server::set_base_dir(const std::string &dir,
  5320. const std::string &mount_point) {
  5321. return set_mount_point(mount_point, dir);
  5322. }
  5323. inline bool Server::set_mount_point(const std::string &mount_point,
  5324. const std::string &dir, Headers headers) {
  5325. detail::FileStat stat(dir);
  5326. if (stat.is_dir()) {
  5327. std::string mnt = !mount_point.empty() ? mount_point : "/";
  5328. if (!mnt.empty() && mnt[0] == '/') {
  5329. base_dirs_.push_back({mnt, dir, std::move(headers)});
  5330. return true;
  5331. }
  5332. }
  5333. return false;
  5334. }
  5335. inline bool Server::remove_mount_point(const std::string &mount_point) {
  5336. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  5337. if (it->mount_point == mount_point) {
  5338. base_dirs_.erase(it);
  5339. return true;
  5340. }
  5341. }
  5342. return false;
  5343. }
  5344. inline Server &
  5345. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  5346. const std::string &mime) {
  5347. file_extension_and_mimetype_map_[ext] = mime;
  5348. return *this;
  5349. }
  5350. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  5351. default_file_mimetype_ = mime;
  5352. return *this;
  5353. }
  5354. inline Server &Server::set_file_request_handler(Handler handler) {
  5355. file_request_handler_ = std::move(handler);
  5356. return *this;
  5357. }
  5358. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  5359. std::true_type) {
  5360. error_handler_ = std::move(handler);
  5361. return *this;
  5362. }
  5363. inline Server &Server::set_error_handler_core(Handler handler,
  5364. std::false_type) {
  5365. error_handler_ = [handler](const Request &req, Response &res) {
  5366. handler(req, res);
  5367. return HandlerResponse::Handled;
  5368. };
  5369. return *this;
  5370. }
  5371. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  5372. exception_handler_ = std::move(handler);
  5373. return *this;
  5374. }
  5375. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  5376. pre_routing_handler_ = std::move(handler);
  5377. return *this;
  5378. }
  5379. inline Server &Server::set_post_routing_handler(Handler handler) {
  5380. post_routing_handler_ = std::move(handler);
  5381. return *this;
  5382. }
  5383. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  5384. pre_request_handler_ = std::move(handler);
  5385. return *this;
  5386. }
  5387. inline Server &Server::set_logger(Logger logger) {
  5388. logger_ = std::move(logger);
  5389. return *this;
  5390. }
  5391. inline Server &
  5392. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  5393. expect_100_continue_handler_ = std::move(handler);
  5394. return *this;
  5395. }
  5396. inline Server &Server::set_address_family(int family) {
  5397. address_family_ = family;
  5398. return *this;
  5399. }
  5400. inline Server &Server::set_tcp_nodelay(bool on) {
  5401. tcp_nodelay_ = on;
  5402. return *this;
  5403. }
  5404. inline Server &Server::set_ipv6_v6only(bool on) {
  5405. ipv6_v6only_ = on;
  5406. return *this;
  5407. }
  5408. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  5409. socket_options_ = std::move(socket_options);
  5410. return *this;
  5411. }
  5412. inline Server &Server::set_default_headers(Headers headers) {
  5413. default_headers_ = std::move(headers);
  5414. return *this;
  5415. }
  5416. inline Server &Server::set_header_writer(
  5417. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  5418. header_writer_ = writer;
  5419. return *this;
  5420. }
  5421. inline Server &Server::set_keep_alive_max_count(size_t count) {
  5422. keep_alive_max_count_ = count;
  5423. return *this;
  5424. }
  5425. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  5426. keep_alive_timeout_sec_ = sec;
  5427. return *this;
  5428. }
  5429. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  5430. read_timeout_sec_ = sec;
  5431. read_timeout_usec_ = usec;
  5432. return *this;
  5433. }
  5434. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  5435. write_timeout_sec_ = sec;
  5436. write_timeout_usec_ = usec;
  5437. return *this;
  5438. }
  5439. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  5440. idle_interval_sec_ = sec;
  5441. idle_interval_usec_ = usec;
  5442. return *this;
  5443. }
  5444. inline Server &Server::set_payload_max_length(size_t length) {
  5445. payload_max_length_ = length;
  5446. return *this;
  5447. }
  5448. inline bool Server::bind_to_port(const std::string &host, int port,
  5449. int socket_flags) {
  5450. auto ret = bind_internal(host, port, socket_flags);
  5451. if (ret == -1) { is_decommissioned = true; }
  5452. return ret >= 0;
  5453. }
  5454. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  5455. auto ret = bind_internal(host, 0, socket_flags);
  5456. if (ret == -1) { is_decommissioned = true; }
  5457. return ret;
  5458. }
  5459. inline bool Server::listen_after_bind() { return listen_internal(); }
  5460. inline bool Server::listen(const std::string &host, int port,
  5461. int socket_flags) {
  5462. return bind_to_port(host, port, socket_flags) && listen_internal();
  5463. }
  5464. inline bool Server::is_running() const { return is_running_; }
  5465. inline void Server::wait_until_ready() const {
  5466. while (!is_running_ && !is_decommissioned) {
  5467. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  5468. }
  5469. }
  5470. inline void Server::stop() {
  5471. if (is_running_) {
  5472. assert(svr_sock_ != INVALID_SOCKET);
  5473. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  5474. detail::shutdown_socket(sock);
  5475. detail::close_socket(sock);
  5476. }
  5477. is_decommissioned = false;
  5478. }
  5479. inline void Server::decommission() { is_decommissioned = true; }
  5480. inline bool Server::parse_request_line(const char *s, Request &req) const {
  5481. auto len = strlen(s);
  5482. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  5483. len -= 2;
  5484. {
  5485. size_t count = 0;
  5486. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  5487. switch (count) {
  5488. case 0: req.method = std::string(b, e); break;
  5489. case 1: req.target = std::string(b, e); break;
  5490. case 2: req.version = std::string(b, e); break;
  5491. default: break;
  5492. }
  5493. count++;
  5494. });
  5495. if (count != 3) { return false; }
  5496. }
  5497. thread_local const std::set<std::string> methods{
  5498. "GET", "HEAD", "POST", "PUT", "DELETE",
  5499. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  5500. if (methods.find(req.method) == methods.end()) { return false; }
  5501. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { return false; }
  5502. {
  5503. // Skip URL fragment
  5504. for (size_t i = 0; i < req.target.size(); i++) {
  5505. if (req.target[i] == '#') {
  5506. req.target.erase(i);
  5507. break;
  5508. }
  5509. }
  5510. detail::divide(req.target, '?',
  5511. [&](const char *lhs_data, std::size_t lhs_size,
  5512. const char *rhs_data, std::size_t rhs_size) {
  5513. req.path = detail::decode_url(
  5514. std::string(lhs_data, lhs_size), false);
  5515. detail::parse_query_text(rhs_data, rhs_size, req.params);
  5516. });
  5517. }
  5518. return true;
  5519. }
  5520. inline bool Server::write_response(Stream &strm, bool close_connection,
  5521. Request &req, Response &res) {
  5522. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  5523. // incorrectly to the error content.
  5524. req.ranges.clear();
  5525. return write_response_core(strm, close_connection, req, res, false);
  5526. }
  5527. inline bool Server::write_response_with_content(Stream &strm,
  5528. bool close_connection,
  5529. const Request &req,
  5530. Response &res) {
  5531. return write_response_core(strm, close_connection, req, res, true);
  5532. }
  5533. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  5534. const Request &req, Response &res,
  5535. bool need_apply_ranges) {
  5536. assert(res.status != -1);
  5537. if (400 <= res.status && error_handler_ &&
  5538. error_handler_(req, res) == HandlerResponse::Handled) {
  5539. need_apply_ranges = true;
  5540. }
  5541. std::string content_type;
  5542. std::string boundary;
  5543. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  5544. // Prepare additional headers
  5545. if (close_connection || req.get_header_value("Connection") == "close") {
  5546. res.set_header("Connection", "close");
  5547. } else {
  5548. std::string s = "timeout=";
  5549. s += std::to_string(keep_alive_timeout_sec_);
  5550. s += ", max=";
  5551. s += std::to_string(keep_alive_max_count_);
  5552. res.set_header("Keep-Alive", s);
  5553. }
  5554. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  5555. !res.has_header("Content-Type")) {
  5556. res.set_header("Content-Type", "text/plain");
  5557. }
  5558. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  5559. !res.has_header("Content-Length")) {
  5560. res.set_header("Content-Length", "0");
  5561. }
  5562. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  5563. res.set_header("Accept-Ranges", "bytes");
  5564. }
  5565. if (post_routing_handler_) { post_routing_handler_(req, res); }
  5566. // Response line and headers
  5567. {
  5568. detail::BufferStream bstrm;
  5569. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  5570. if (!header_writer_(bstrm, res.headers)) { return false; }
  5571. // Flush buffer
  5572. auto &data = bstrm.get_buffer();
  5573. detail::write_data(strm, data.data(), data.size());
  5574. }
  5575. // Body
  5576. auto ret = true;
  5577. if (req.method != "HEAD") {
  5578. if (!res.body.empty()) {
  5579. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  5580. ret = false;
  5581. }
  5582. } else if (res.content_provider_) {
  5583. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  5584. res.content_provider_success_ = true;
  5585. } else {
  5586. ret = false;
  5587. }
  5588. }
  5589. }
  5590. // Log
  5591. if (logger_) { logger_(req, res); }
  5592. return ret;
  5593. }
  5594. inline bool
  5595. Server::write_content_with_provider(Stream &strm, const Request &req,
  5596. Response &res, const std::string &boundary,
  5597. const std::string &content_type) {
  5598. auto is_shutting_down = [this]() {
  5599. return this->svr_sock_ == INVALID_SOCKET;
  5600. };
  5601. if (res.content_length_ > 0) {
  5602. if (req.ranges.empty()) {
  5603. return detail::write_content(strm, res.content_provider_, 0,
  5604. res.content_length_, is_shutting_down);
  5605. } else if (req.ranges.size() == 1) {
  5606. auto offset_and_length = detail::get_range_offset_and_length(
  5607. req.ranges[0], res.content_length_);
  5608. return detail::write_content(strm, res.content_provider_,
  5609. offset_and_length.first,
  5610. offset_and_length.second, is_shutting_down);
  5611. } else {
  5612. return detail::write_multipart_ranges_data(
  5613. strm, req, res, boundary, content_type, res.content_length_,
  5614. is_shutting_down);
  5615. }
  5616. } else {
  5617. if (res.is_chunked_content_provider_) {
  5618. auto type = detail::encoding_type(req, res);
  5619. std::unique_ptr<detail::compressor> compressor;
  5620. if (type == detail::EncodingType::Gzip) {
  5621. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5622. compressor = detail::make_unique<detail::gzip_compressor>();
  5623. #endif
  5624. } else if (type == detail::EncodingType::Brotli) {
  5625. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5626. compressor = detail::make_unique<detail::brotli_compressor>();
  5627. #endif
  5628. } else if (type == detail::EncodingType::Zstd) {
  5629. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5630. compressor = detail::make_unique<detail::zstd_compressor>();
  5631. #endif
  5632. } else {
  5633. compressor = detail::make_unique<detail::nocompressor>();
  5634. }
  5635. assert(compressor != nullptr);
  5636. return detail::write_content_chunked(strm, res.content_provider_,
  5637. is_shutting_down, *compressor);
  5638. } else {
  5639. return detail::write_content_without_length(strm, res.content_provider_,
  5640. is_shutting_down);
  5641. }
  5642. }
  5643. }
  5644. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  5645. MultipartFormDataMap::iterator cur;
  5646. auto file_count = 0;
  5647. if (read_content_core(
  5648. strm, req, res,
  5649. // Regular
  5650. [&](const char *buf, size_t n) {
  5651. if (req.body.size() + n > req.body.max_size()) { return false; }
  5652. req.body.append(buf, n);
  5653. return true;
  5654. },
  5655. // Multipart
  5656. [&](const MultipartFormData &file) {
  5657. if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  5658. return false;
  5659. }
  5660. cur = req.files.emplace(file.name, file);
  5661. return true;
  5662. },
  5663. [&](const char *buf, size_t n) {
  5664. auto &content = cur->second.content;
  5665. if (content.size() + n > content.max_size()) { return false; }
  5666. content.append(buf, n);
  5667. return true;
  5668. })) {
  5669. const auto &content_type = req.get_header_value("Content-Type");
  5670. if (!content_type.find("application/x-www-form-urlencoded")) {
  5671. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  5672. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  5673. return false;
  5674. }
  5675. detail::parse_query_text(req.body, req.params);
  5676. }
  5677. return true;
  5678. }
  5679. return false;
  5680. }
  5681. inline bool Server::read_content_with_content_receiver(
  5682. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  5683. MultipartContentHeader multipart_header,
  5684. ContentReceiver multipart_receiver) {
  5685. return read_content_core(strm, req, res, std::move(receiver),
  5686. std::move(multipart_header),
  5687. std::move(multipart_receiver));
  5688. }
  5689. inline bool
  5690. Server::read_content_core(Stream &strm, Request &req, Response &res,
  5691. ContentReceiver receiver,
  5692. MultipartContentHeader multipart_header,
  5693. ContentReceiver multipart_receiver) const {
  5694. detail::MultipartFormDataParser multipart_form_data_parser;
  5695. ContentReceiverWithProgress out;
  5696. if (req.is_multipart_form_data()) {
  5697. const auto &content_type = req.get_header_value("Content-Type");
  5698. std::string boundary;
  5699. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  5700. res.status = StatusCode::BadRequest_400;
  5701. return false;
  5702. }
  5703. multipart_form_data_parser.set_boundary(std::move(boundary));
  5704. out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) {
  5705. /* For debug
  5706. size_t pos = 0;
  5707. while (pos < n) {
  5708. auto read_size = (std::min)<size_t>(1, n - pos);
  5709. auto ret = multipart_form_data_parser.parse(
  5710. buf + pos, read_size, multipart_receiver, multipart_header);
  5711. if (!ret) { return false; }
  5712. pos += read_size;
  5713. }
  5714. return true;
  5715. */
  5716. return multipart_form_data_parser.parse(buf, n, multipart_receiver,
  5717. multipart_header);
  5718. };
  5719. } else {
  5720. out = [receiver](const char *buf, size_t n, uint64_t /*off*/,
  5721. uint64_t /*len*/) { return receiver(buf, n); };
  5722. }
  5723. if (req.method == "DELETE" && !req.has_header("Content-Length")) {
  5724. return true;
  5725. }
  5726. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  5727. out, true)) {
  5728. return false;
  5729. }
  5730. if (req.is_multipart_form_data()) {
  5731. if (!multipart_form_data_parser.is_valid()) {
  5732. res.status = StatusCode::BadRequest_400;
  5733. return false;
  5734. }
  5735. }
  5736. return true;
  5737. }
  5738. inline bool Server::handle_file_request(const Request &req, Response &res) {
  5739. for (const auto &entry : base_dirs_) {
  5740. // Prefix match
  5741. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  5742. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  5743. if (detail::is_valid_path(sub_path)) {
  5744. auto path = entry.base_dir + sub_path;
  5745. if (path.back() == '/') { path += "index.html"; }
  5746. detail::FileStat stat(path);
  5747. if (stat.is_dir()) {
  5748. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  5749. return true;
  5750. }
  5751. if (stat.is_file()) {
  5752. for (const auto &kv : entry.headers) {
  5753. res.set_header(kv.first, kv.second);
  5754. }
  5755. auto mm = std::make_shared<detail::mmap>(path.c_str());
  5756. if (!mm->is_open()) { return false; }
  5757. res.set_content_provider(
  5758. mm->size(),
  5759. detail::find_content_type(path, file_extension_and_mimetype_map_,
  5760. default_file_mimetype_),
  5761. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  5762. sink.write(mm->data() + offset, length);
  5763. return true;
  5764. });
  5765. if (req.method != "HEAD" && file_request_handler_) {
  5766. file_request_handler_(req, res);
  5767. }
  5768. return true;
  5769. }
  5770. }
  5771. }
  5772. }
  5773. return false;
  5774. }
  5775. inline socket_t
  5776. Server::create_server_socket(const std::string &host, int port,
  5777. int socket_flags,
  5778. SocketOptions socket_options) const {
  5779. return detail::create_socket(
  5780. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  5781. ipv6_v6only_, std::move(socket_options),
  5782. [](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  5783. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5784. return false;
  5785. }
  5786. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { return false; }
  5787. return true;
  5788. });
  5789. }
  5790. inline int Server::bind_internal(const std::string &host, int port,
  5791. int socket_flags) {
  5792. if (is_decommissioned) { return -1; }
  5793. if (!is_valid()) { return -1; }
  5794. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  5795. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  5796. if (port == 0) {
  5797. struct sockaddr_storage addr;
  5798. socklen_t addr_len = sizeof(addr);
  5799. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  5800. &addr_len) == -1) {
  5801. return -1;
  5802. }
  5803. if (addr.ss_family == AF_INET) {
  5804. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  5805. } else if (addr.ss_family == AF_INET6) {
  5806. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  5807. } else {
  5808. return -1;
  5809. }
  5810. } else {
  5811. return port;
  5812. }
  5813. }
  5814. inline bool Server::listen_internal() {
  5815. if (is_decommissioned) { return false; }
  5816. auto ret = true;
  5817. is_running_ = true;
  5818. auto se = detail::scope_exit([&]() { is_running_ = false; });
  5819. {
  5820. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  5821. while (svr_sock_ != INVALID_SOCKET) {
  5822. #ifndef _WIN32
  5823. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  5824. #endif
  5825. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  5826. idle_interval_usec_);
  5827. if (val == 0) { // Timeout
  5828. task_queue->on_idle();
  5829. continue;
  5830. }
  5831. #ifndef _WIN32
  5832. }
  5833. #endif
  5834. #if defined _WIN32
  5835. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  5836. // OVERLAPPED
  5837. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  5838. #elif defined SOCK_CLOEXEC
  5839. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  5840. #else
  5841. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  5842. #endif
  5843. if (sock == INVALID_SOCKET) {
  5844. if (errno == EMFILE) {
  5845. // The per-process limit of open file descriptors has been reached.
  5846. // Try to accept new connections after a short sleep.
  5847. std::this_thread::sleep_for(std::chrono::microseconds{1});
  5848. continue;
  5849. } else if (errno == EINTR || errno == EAGAIN) {
  5850. continue;
  5851. }
  5852. if (svr_sock_ != INVALID_SOCKET) {
  5853. detail::close_socket(svr_sock_);
  5854. ret = false;
  5855. } else {
  5856. ; // The server socket was closed by user.
  5857. }
  5858. break;
  5859. }
  5860. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  5861. read_timeout_sec_, read_timeout_usec_);
  5862. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  5863. write_timeout_sec_, write_timeout_usec_);
  5864. if (!task_queue->enqueue(
  5865. [this, sock]() { process_and_close_socket(sock); })) {
  5866. detail::shutdown_socket(sock);
  5867. detail::close_socket(sock);
  5868. }
  5869. }
  5870. task_queue->shutdown();
  5871. }
  5872. is_decommissioned = !ret;
  5873. return ret;
  5874. }
  5875. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  5876. if (pre_routing_handler_ &&
  5877. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  5878. return true;
  5879. }
  5880. // File handler
  5881. if ((req.method == "GET" || req.method == "HEAD") &&
  5882. handle_file_request(req, res)) {
  5883. return true;
  5884. }
  5885. if (detail::expect_content(req)) {
  5886. // Content reader handler
  5887. {
  5888. ContentReader reader(
  5889. [&](ContentReceiver receiver) {
  5890. return read_content_with_content_receiver(
  5891. strm, req, res, std::move(receiver), nullptr, nullptr);
  5892. },
  5893. [&](MultipartContentHeader header, ContentReceiver receiver) {
  5894. return read_content_with_content_receiver(strm, req, res, nullptr,
  5895. std::move(header),
  5896. std::move(receiver));
  5897. });
  5898. if (req.method == "POST") {
  5899. if (dispatch_request_for_content_reader(
  5900. req, res, std::move(reader),
  5901. post_handlers_for_content_reader_)) {
  5902. return true;
  5903. }
  5904. } else if (req.method == "PUT") {
  5905. if (dispatch_request_for_content_reader(
  5906. req, res, std::move(reader),
  5907. put_handlers_for_content_reader_)) {
  5908. return true;
  5909. }
  5910. } else if (req.method == "PATCH") {
  5911. if (dispatch_request_for_content_reader(
  5912. req, res, std::move(reader),
  5913. patch_handlers_for_content_reader_)) {
  5914. return true;
  5915. }
  5916. } else if (req.method == "DELETE") {
  5917. if (dispatch_request_for_content_reader(
  5918. req, res, std::move(reader),
  5919. delete_handlers_for_content_reader_)) {
  5920. return true;
  5921. }
  5922. }
  5923. }
  5924. // Read content into `req.body`
  5925. if (!read_content(strm, req, res)) { return false; }
  5926. }
  5927. // Regular handler
  5928. if (req.method == "GET" || req.method == "HEAD") {
  5929. return dispatch_request(req, res, get_handlers_);
  5930. } else if (req.method == "POST") {
  5931. return dispatch_request(req, res, post_handlers_);
  5932. } else if (req.method == "PUT") {
  5933. return dispatch_request(req, res, put_handlers_);
  5934. } else if (req.method == "DELETE") {
  5935. return dispatch_request(req, res, delete_handlers_);
  5936. } else if (req.method == "OPTIONS") {
  5937. return dispatch_request(req, res, options_handlers_);
  5938. } else if (req.method == "PATCH") {
  5939. return dispatch_request(req, res, patch_handlers_);
  5940. }
  5941. res.status = StatusCode::BadRequest_400;
  5942. return false;
  5943. }
  5944. inline bool Server::dispatch_request(Request &req, Response &res,
  5945. const Handlers &handlers) const {
  5946. for (const auto &x : handlers) {
  5947. const auto &matcher = x.first;
  5948. const auto &handler = x.second;
  5949. if (matcher->match(req)) {
  5950. req.matched_route = matcher->pattern();
  5951. if (!pre_request_handler_ ||
  5952. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  5953. handler(req, res);
  5954. }
  5955. return true;
  5956. }
  5957. }
  5958. return false;
  5959. }
  5960. inline void Server::apply_ranges(const Request &req, Response &res,
  5961. std::string &content_type,
  5962. std::string &boundary) const {
  5963. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  5964. auto it = res.headers.find("Content-Type");
  5965. if (it != res.headers.end()) {
  5966. content_type = it->second;
  5967. res.headers.erase(it);
  5968. }
  5969. boundary = detail::make_multipart_data_boundary();
  5970. res.set_header("Content-Type",
  5971. "multipart/byteranges; boundary=" + boundary);
  5972. }
  5973. auto type = detail::encoding_type(req, res);
  5974. if (res.body.empty()) {
  5975. if (res.content_length_ > 0) {
  5976. size_t length = 0;
  5977. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  5978. length = res.content_length_;
  5979. } else if (req.ranges.size() == 1) {
  5980. auto offset_and_length = detail::get_range_offset_and_length(
  5981. req.ranges[0], res.content_length_);
  5982. length = offset_and_length.second;
  5983. auto content_range = detail::make_content_range_header_field(
  5984. offset_and_length, res.content_length_);
  5985. res.set_header("Content-Range", content_range);
  5986. } else {
  5987. length = detail::get_multipart_ranges_data_length(
  5988. req, boundary, content_type, res.content_length_);
  5989. }
  5990. res.set_header("Content-Length", std::to_string(length));
  5991. } else {
  5992. if (res.content_provider_) {
  5993. if (res.is_chunked_content_provider_) {
  5994. res.set_header("Transfer-Encoding", "chunked");
  5995. if (type == detail::EncodingType::Gzip) {
  5996. res.set_header("Content-Encoding", "gzip");
  5997. } else if (type == detail::EncodingType::Brotli) {
  5998. res.set_header("Content-Encoding", "br");
  5999. } else if (type == detail::EncodingType::Zstd) {
  6000. res.set_header("Content-Encoding", "zstd");
  6001. }
  6002. }
  6003. }
  6004. }
  6005. } else {
  6006. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  6007. ;
  6008. } else if (req.ranges.size() == 1) {
  6009. auto offset_and_length =
  6010. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  6011. auto offset = offset_and_length.first;
  6012. auto length = offset_and_length.second;
  6013. auto content_range = detail::make_content_range_header_field(
  6014. offset_and_length, res.body.size());
  6015. res.set_header("Content-Range", content_range);
  6016. assert(offset + length <= res.body.size());
  6017. res.body = res.body.substr(offset, length);
  6018. } else {
  6019. std::string data;
  6020. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  6021. res.body.size(), data);
  6022. res.body.swap(data);
  6023. }
  6024. if (type != detail::EncodingType::None) {
  6025. std::unique_ptr<detail::compressor> compressor;
  6026. std::string content_encoding;
  6027. if (type == detail::EncodingType::Gzip) {
  6028. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6029. compressor = detail::make_unique<detail::gzip_compressor>();
  6030. content_encoding = "gzip";
  6031. #endif
  6032. } else if (type == detail::EncodingType::Brotli) {
  6033. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6034. compressor = detail::make_unique<detail::brotli_compressor>();
  6035. content_encoding = "br";
  6036. #endif
  6037. } else if (type == detail::EncodingType::Zstd) {
  6038. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6039. compressor = detail::make_unique<detail::zstd_compressor>();
  6040. content_encoding = "zstd";
  6041. #endif
  6042. }
  6043. if (compressor) {
  6044. std::string compressed;
  6045. if (compressor->compress(res.body.data(), res.body.size(), true,
  6046. [&](const char *data, size_t data_len) {
  6047. compressed.append(data, data_len);
  6048. return true;
  6049. })) {
  6050. res.body.swap(compressed);
  6051. res.set_header("Content-Encoding", content_encoding);
  6052. }
  6053. }
  6054. }
  6055. auto length = std::to_string(res.body.size());
  6056. res.set_header("Content-Length", length);
  6057. }
  6058. }
  6059. inline bool Server::dispatch_request_for_content_reader(
  6060. Request &req, Response &res, ContentReader content_reader,
  6061. const HandlersForContentReader &handlers) const {
  6062. for (const auto &x : handlers) {
  6063. const auto &matcher = x.first;
  6064. const auto &handler = x.second;
  6065. if (matcher->match(req)) {
  6066. req.matched_route = matcher->pattern();
  6067. if (!pre_request_handler_ ||
  6068. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  6069. handler(req, res, content_reader);
  6070. }
  6071. return true;
  6072. }
  6073. }
  6074. return false;
  6075. }
  6076. inline bool
  6077. Server::process_request(Stream &strm, const std::string &remote_addr,
  6078. int remote_port, const std::string &local_addr,
  6079. int local_port, bool close_connection,
  6080. bool &connection_closed,
  6081. const std::function<void(Request &)> &setup_request) {
  6082. std::array<char, 2048> buf{};
  6083. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  6084. // Connection has been closed on client
  6085. if (!line_reader.getline()) { return false; }
  6086. Request req;
  6087. Response res;
  6088. res.version = "HTTP/1.1";
  6089. res.headers = default_headers_;
  6090. // Request line and headers
  6091. if (!parse_request_line(line_reader.ptr(), req) ||
  6092. !detail::read_headers(strm, req.headers)) {
  6093. res.status = StatusCode::BadRequest_400;
  6094. return write_response(strm, close_connection, req, res);
  6095. }
  6096. // Check if the request URI doesn't exceed the limit
  6097. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  6098. Headers dummy;
  6099. detail::read_headers(strm, dummy);
  6100. res.status = StatusCode::UriTooLong_414;
  6101. return write_response(strm, close_connection, req, res);
  6102. }
  6103. if (req.get_header_value("Connection") == "close") {
  6104. connection_closed = true;
  6105. }
  6106. if (req.version == "HTTP/1.0" &&
  6107. req.get_header_value("Connection") != "Keep-Alive") {
  6108. connection_closed = true;
  6109. }
  6110. req.remote_addr = remote_addr;
  6111. req.remote_port = remote_port;
  6112. req.set_header("REMOTE_ADDR", req.remote_addr);
  6113. req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
  6114. req.local_addr = local_addr;
  6115. req.local_port = local_port;
  6116. req.set_header("LOCAL_ADDR", req.local_addr);
  6117. req.set_header("LOCAL_PORT", std::to_string(req.local_port));
  6118. if (req.has_header("Accept")) {
  6119. const auto &accept_header = req.get_header_value("Accept");
  6120. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  6121. res.status = StatusCode::BadRequest_400;
  6122. return write_response(strm, close_connection, req, res);
  6123. }
  6124. }
  6125. if (req.has_header("Range")) {
  6126. const auto &range_header_value = req.get_header_value("Range");
  6127. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  6128. res.status = StatusCode::RangeNotSatisfiable_416;
  6129. return write_response(strm, close_connection, req, res);
  6130. }
  6131. }
  6132. if (setup_request) { setup_request(req); }
  6133. if (req.get_header_value("Expect") == "100-continue") {
  6134. int status = StatusCode::Continue_100;
  6135. if (expect_100_continue_handler_) {
  6136. status = expect_100_continue_handler_(req, res);
  6137. }
  6138. switch (status) {
  6139. case StatusCode::Continue_100:
  6140. case StatusCode::ExpectationFailed_417:
  6141. detail::write_response_line(strm, status);
  6142. strm.write("\r\n");
  6143. break;
  6144. default:
  6145. connection_closed = true;
  6146. return write_response(strm, true, req, res);
  6147. }
  6148. }
  6149. // Setup `is_connection_closed` method
  6150. auto sock = strm.socket();
  6151. req.is_connection_closed = [sock]() {
  6152. return !detail::is_socket_alive(sock);
  6153. };
  6154. // Routing
  6155. auto routed = false;
  6156. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6157. routed = routing(req, res, strm);
  6158. #else
  6159. try {
  6160. routed = routing(req, res, strm);
  6161. } catch (std::exception &e) {
  6162. if (exception_handler_) {
  6163. auto ep = std::current_exception();
  6164. exception_handler_(req, res, ep);
  6165. routed = true;
  6166. } else {
  6167. res.status = StatusCode::InternalServerError_500;
  6168. std::string val;
  6169. auto s = e.what();
  6170. for (size_t i = 0; s[i]; i++) {
  6171. switch (s[i]) {
  6172. case '\r': val += "\\r"; break;
  6173. case '\n': val += "\\n"; break;
  6174. default: val += s[i]; break;
  6175. }
  6176. }
  6177. res.set_header("EXCEPTION_WHAT", val);
  6178. }
  6179. } catch (...) {
  6180. if (exception_handler_) {
  6181. auto ep = std::current_exception();
  6182. exception_handler_(req, res, ep);
  6183. routed = true;
  6184. } else {
  6185. res.status = StatusCode::InternalServerError_500;
  6186. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  6187. }
  6188. }
  6189. #endif
  6190. if (routed) {
  6191. if (res.status == -1) {
  6192. res.status = req.ranges.empty() ? StatusCode::OK_200
  6193. : StatusCode::PartialContent_206;
  6194. }
  6195. // Serve file content by using a content provider
  6196. if (!res.file_content_path_.empty()) {
  6197. const auto &path = res.file_content_path_;
  6198. auto mm = std::make_shared<detail::mmap>(path.c_str());
  6199. if (!mm->is_open()) {
  6200. res.body.clear();
  6201. res.content_length_ = 0;
  6202. res.content_provider_ = nullptr;
  6203. res.status = StatusCode::NotFound_404;
  6204. return write_response(strm, close_connection, req, res);
  6205. }
  6206. auto content_type = res.file_content_content_type_;
  6207. if (content_type.empty()) {
  6208. content_type = detail::find_content_type(
  6209. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  6210. }
  6211. res.set_content_provider(
  6212. mm->size(), content_type,
  6213. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  6214. sink.write(mm->data() + offset, length);
  6215. return true;
  6216. });
  6217. }
  6218. if (detail::range_error(req, res)) {
  6219. res.body.clear();
  6220. res.content_length_ = 0;
  6221. res.content_provider_ = nullptr;
  6222. res.status = StatusCode::RangeNotSatisfiable_416;
  6223. return write_response(strm, close_connection, req, res);
  6224. }
  6225. return write_response_with_content(strm, close_connection, req, res);
  6226. } else {
  6227. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  6228. return write_response(strm, close_connection, req, res);
  6229. }
  6230. }
  6231. inline bool Server::is_valid() const { return true; }
  6232. inline bool Server::process_and_close_socket(socket_t sock) {
  6233. std::string remote_addr;
  6234. int remote_port = 0;
  6235. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  6236. std::string local_addr;
  6237. int local_port = 0;
  6238. detail::get_local_ip_and_port(sock, local_addr, local_port);
  6239. auto ret = detail::process_server_socket(
  6240. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  6241. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  6242. write_timeout_usec_,
  6243. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  6244. return process_request(strm, remote_addr, remote_port, local_addr,
  6245. local_port, close_connection, connection_closed,
  6246. nullptr);
  6247. });
  6248. detail::shutdown_socket(sock);
  6249. detail::close_socket(sock);
  6250. return ret;
  6251. }
  6252. // HTTP client implementation
  6253. inline ClientImpl::ClientImpl(const std::string &host)
  6254. : ClientImpl(host, 80, std::string(), std::string()) {}
  6255. inline ClientImpl::ClientImpl(const std::string &host, int port)
  6256. : ClientImpl(host, port, std::string(), std::string()) {}
  6257. inline ClientImpl::ClientImpl(const std::string &host, int port,
  6258. const std::string &client_cert_path,
  6259. const std::string &client_key_path)
  6260. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  6261. host_and_port_(adjust_host_string(host_) + ":" + std::to_string(port)),
  6262. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  6263. inline ClientImpl::~ClientImpl() {
  6264. // Wait until all the requests in flight are handled.
  6265. size_t retry_count = 10;
  6266. while (retry_count-- > 0) {
  6267. {
  6268. std::lock_guard<std::mutex> guard(socket_mutex_);
  6269. if (socket_requests_in_flight_ == 0) { break; }
  6270. }
  6271. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  6272. }
  6273. std::lock_guard<std::mutex> guard(socket_mutex_);
  6274. shutdown_socket(socket_);
  6275. close_socket(socket_);
  6276. }
  6277. inline bool ClientImpl::is_valid() const { return true; }
  6278. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  6279. client_cert_path_ = rhs.client_cert_path_;
  6280. client_key_path_ = rhs.client_key_path_;
  6281. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  6282. read_timeout_sec_ = rhs.read_timeout_sec_;
  6283. read_timeout_usec_ = rhs.read_timeout_usec_;
  6284. write_timeout_sec_ = rhs.write_timeout_sec_;
  6285. write_timeout_usec_ = rhs.write_timeout_usec_;
  6286. max_timeout_msec_ = rhs.max_timeout_msec_;
  6287. basic_auth_username_ = rhs.basic_auth_username_;
  6288. basic_auth_password_ = rhs.basic_auth_password_;
  6289. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  6290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6291. digest_auth_username_ = rhs.digest_auth_username_;
  6292. digest_auth_password_ = rhs.digest_auth_password_;
  6293. #endif
  6294. keep_alive_ = rhs.keep_alive_;
  6295. follow_location_ = rhs.follow_location_;
  6296. url_encode_ = rhs.url_encode_;
  6297. address_family_ = rhs.address_family_;
  6298. tcp_nodelay_ = rhs.tcp_nodelay_;
  6299. ipv6_v6only_ = rhs.ipv6_v6only_;
  6300. socket_options_ = rhs.socket_options_;
  6301. compress_ = rhs.compress_;
  6302. decompress_ = rhs.decompress_;
  6303. interface_ = rhs.interface_;
  6304. proxy_host_ = rhs.proxy_host_;
  6305. proxy_port_ = rhs.proxy_port_;
  6306. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  6307. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  6308. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  6309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6310. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  6311. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  6312. #endif
  6313. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6314. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  6315. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  6316. ca_cert_store_ = rhs.ca_cert_store_;
  6317. #endif
  6318. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6319. server_certificate_verification_ = rhs.server_certificate_verification_;
  6320. server_hostname_verification_ = rhs.server_hostname_verification_;
  6321. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  6322. #endif
  6323. logger_ = rhs.logger_;
  6324. }
  6325. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  6326. if (!proxy_host_.empty() && proxy_port_ != -1) {
  6327. return detail::create_client_socket(
  6328. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  6329. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  6330. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  6331. write_timeout_sec_, write_timeout_usec_, interface_, error);
  6332. }
  6333. // Check is custom IP specified for host_
  6334. std::string ip;
  6335. auto it = addr_map_.find(host_);
  6336. if (it != addr_map_.end()) { ip = it->second; }
  6337. return detail::create_client_socket(
  6338. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  6339. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  6340. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  6341. write_timeout_usec_, interface_, error);
  6342. }
  6343. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  6344. Error &error) {
  6345. auto sock = create_client_socket(error);
  6346. if (sock == INVALID_SOCKET) { return false; }
  6347. socket.sock = sock;
  6348. return true;
  6349. }
  6350. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  6351. bool /*shutdown_gracefully*/) {
  6352. // If there are any requests in flight from threads other than us, then it's
  6353. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  6354. assert(socket_requests_in_flight_ == 0 ||
  6355. socket_requests_are_from_thread_ == std::this_thread::get_id());
  6356. }
  6357. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  6358. if (socket.sock == INVALID_SOCKET) { return; }
  6359. detail::shutdown_socket(socket.sock);
  6360. }
  6361. inline void ClientImpl::close_socket(Socket &socket) {
  6362. // If there are requests in flight in another thread, usually closing
  6363. // the socket will be fine and they will simply receive an error when
  6364. // using the closed socket, but it is still a bug since rarely the OS
  6365. // may reassign the socket id to be used for a new socket, and then
  6366. // suddenly they will be operating on a live socket that is different
  6367. // than the one they intended!
  6368. assert(socket_requests_in_flight_ == 0 ||
  6369. socket_requests_are_from_thread_ == std::this_thread::get_id());
  6370. // It is also a bug if this happens while SSL is still active
  6371. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6372. assert(socket.ssl == nullptr);
  6373. #endif
  6374. if (socket.sock == INVALID_SOCKET) { return; }
  6375. detail::close_socket(socket.sock);
  6376. socket.sock = INVALID_SOCKET;
  6377. }
  6378. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  6379. Response &res) const {
  6380. std::array<char, 2048> buf{};
  6381. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  6382. if (!line_reader.getline()) { return false; }
  6383. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6384. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  6385. #else
  6386. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  6387. #endif
  6388. std::cmatch m;
  6389. if (!std::regex_match(line_reader.ptr(), m, re)) {
  6390. return req.method == "CONNECT";
  6391. }
  6392. res.version = std::string(m[1]);
  6393. res.status = std::stoi(std::string(m[2]));
  6394. res.reason = std::string(m[3]);
  6395. // Ignore '100 Continue'
  6396. while (res.status == StatusCode::Continue_100) {
  6397. if (!line_reader.getline()) { return false; } // CRLF
  6398. if (!line_reader.getline()) { return false; } // next response line
  6399. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  6400. res.version = std::string(m[1]);
  6401. res.status = std::stoi(std::string(m[2]));
  6402. res.reason = std::string(m[3]);
  6403. }
  6404. return true;
  6405. }
  6406. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  6407. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  6408. auto ret = send_(req, res, error);
  6409. if (error == Error::SSLPeerCouldBeClosed_) {
  6410. assert(!ret);
  6411. ret = send_(req, res, error);
  6412. }
  6413. return ret;
  6414. }
  6415. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  6416. {
  6417. std::lock_guard<std::mutex> guard(socket_mutex_);
  6418. // Set this to false immediately - if it ever gets set to true by the end of
  6419. // the request, we know another thread instructed us to close the socket.
  6420. socket_should_be_closed_when_request_is_done_ = false;
  6421. auto is_alive = false;
  6422. if (socket_.is_open()) {
  6423. is_alive = detail::is_socket_alive(socket_.sock);
  6424. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6425. if (is_alive && is_ssl()) {
  6426. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  6427. is_alive = false;
  6428. }
  6429. }
  6430. #endif
  6431. if (!is_alive) {
  6432. // Attempt to avoid sigpipe by shutting down non-gracefully if it seems
  6433. // like the other side has already closed the connection Also, there
  6434. // cannot be any requests in flight from other threads since we locked
  6435. // request_mutex_, so safe to close everything immediately
  6436. const bool shutdown_gracefully = false;
  6437. shutdown_ssl(socket_, shutdown_gracefully);
  6438. shutdown_socket(socket_);
  6439. close_socket(socket_);
  6440. }
  6441. }
  6442. if (!is_alive) {
  6443. if (!create_and_connect_socket(socket_, error)) { return false; }
  6444. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6445. // TODO: refactoring
  6446. if (is_ssl()) {
  6447. auto &scli = static_cast<SSLClient &>(*this);
  6448. if (!proxy_host_.empty() && proxy_port_ != -1) {
  6449. auto success = false;
  6450. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  6451. error)) {
  6452. return success;
  6453. }
  6454. }
  6455. if (!scli.initialize_ssl(socket_, error)) { return false; }
  6456. }
  6457. #endif
  6458. }
  6459. // Mark the current socket as being in use so that it cannot be closed by
  6460. // anyone else while this request is ongoing, even though we will be
  6461. // releasing the mutex.
  6462. if (socket_requests_in_flight_ > 1) {
  6463. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  6464. }
  6465. socket_requests_in_flight_ += 1;
  6466. socket_requests_are_from_thread_ = std::this_thread::get_id();
  6467. }
  6468. for (const auto &header : default_headers_) {
  6469. if (req.headers.find(header.first) == req.headers.end()) {
  6470. req.headers.insert(header);
  6471. }
  6472. }
  6473. auto ret = false;
  6474. auto close_connection = !keep_alive_;
  6475. auto se = detail::scope_exit([&]() {
  6476. // Briefly lock mutex in order to mark that a request is no longer ongoing
  6477. std::lock_guard<std::mutex> guard(socket_mutex_);
  6478. socket_requests_in_flight_ -= 1;
  6479. if (socket_requests_in_flight_ <= 0) {
  6480. assert(socket_requests_in_flight_ == 0);
  6481. socket_requests_are_from_thread_ = std::thread::id();
  6482. }
  6483. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  6484. !ret) {
  6485. shutdown_ssl(socket_, true);
  6486. shutdown_socket(socket_);
  6487. close_socket(socket_);
  6488. }
  6489. });
  6490. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  6491. return handle_request(strm, req, res, close_connection, error);
  6492. });
  6493. if (!ret) {
  6494. if (error == Error::Success) { error = Error::Unknown; }
  6495. }
  6496. return ret;
  6497. }
  6498. inline Result ClientImpl::send(const Request &req) {
  6499. auto req2 = req;
  6500. return send_(std::move(req2));
  6501. }
  6502. inline Result ClientImpl::send_(Request &&req) {
  6503. auto res = detail::make_unique<Response>();
  6504. auto error = Error::Success;
  6505. auto ret = send(req, *res, error);
  6506. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  6507. }
  6508. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  6509. Response &res, bool close_connection,
  6510. Error &error) {
  6511. if (req.path.empty()) {
  6512. error = Error::Connection;
  6513. return false;
  6514. }
  6515. auto req_save = req;
  6516. bool ret;
  6517. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  6518. auto req2 = req;
  6519. req2.path = "http://" + host_and_port_ + req.path;
  6520. ret = process_request(strm, req2, res, close_connection, error);
  6521. req = req2;
  6522. req.path = req_save.path;
  6523. } else {
  6524. ret = process_request(strm, req, res, close_connection, error);
  6525. }
  6526. if (!ret) { return false; }
  6527. if (res.get_header_value("Connection") == "close" ||
  6528. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  6529. // TODO this requires a not-entirely-obvious chain of calls to be correct
  6530. // for this to be safe.
  6531. // This is safe to call because handle_request is only called by send_
  6532. // which locks the request mutex during the process. It would be a bug
  6533. // to call it from a different thread since it's a thread-safety issue
  6534. // to do these things to the socket if another thread is using the socket.
  6535. std::lock_guard<std::mutex> guard(socket_mutex_);
  6536. shutdown_ssl(socket_, true);
  6537. shutdown_socket(socket_);
  6538. close_socket(socket_);
  6539. }
  6540. if (300 < res.status && res.status < 400 && follow_location_) {
  6541. req = req_save;
  6542. ret = redirect(req, res, error);
  6543. }
  6544. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6545. if ((res.status == StatusCode::Unauthorized_401 ||
  6546. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  6547. req.authorization_count_ < 5) {
  6548. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  6549. const auto &username =
  6550. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  6551. const auto &password =
  6552. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  6553. if (!username.empty() && !password.empty()) {
  6554. std::map<std::string, std::string> auth;
  6555. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  6556. Request new_req = req;
  6557. new_req.authorization_count_ += 1;
  6558. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  6559. : "Authorization");
  6560. new_req.headers.insert(detail::make_digest_authentication_header(
  6561. req, auth, new_req.authorization_count_, detail::random_string(10),
  6562. username, password, is_proxy));
  6563. Response new_res;
  6564. ret = send(new_req, new_res, error);
  6565. if (ret) { res = new_res; }
  6566. }
  6567. }
  6568. }
  6569. #endif
  6570. return ret;
  6571. }
  6572. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  6573. if (req.redirect_count_ == 0) {
  6574. error = Error::ExceedRedirectCount;
  6575. return false;
  6576. }
  6577. auto location = res.get_header_value("location");
  6578. if (location.empty()) { return false; }
  6579. thread_local const std::regex re(
  6580. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  6581. std::smatch m;
  6582. if (!std::regex_match(location, m, re)) { return false; }
  6583. auto scheme = is_ssl() ? "https" : "http";
  6584. auto next_scheme = m[1].str();
  6585. auto next_host = m[2].str();
  6586. if (next_host.empty()) { next_host = m[3].str(); }
  6587. auto port_str = m[4].str();
  6588. auto next_path = m[5].str();
  6589. auto next_query = m[6].str();
  6590. auto next_port = port_;
  6591. if (!port_str.empty()) {
  6592. next_port = std::stoi(port_str);
  6593. } else if (!next_scheme.empty()) {
  6594. next_port = next_scheme == "https" ? 443 : 80;
  6595. }
  6596. if (next_scheme.empty()) { next_scheme = scheme; }
  6597. if (next_host.empty()) { next_host = host_; }
  6598. if (next_path.empty()) { next_path = "/"; }
  6599. auto path = detail::decode_url(next_path, true) + next_query;
  6600. // Same host redirect - use current client
  6601. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  6602. return detail::redirect(*this, req, res, path, location, error);
  6603. }
  6604. // Cross-host/scheme redirect - create new client with robust setup
  6605. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  6606. path, location, error);
  6607. }
  6608. // New method for robust redirect client creation
  6609. inline bool ClientImpl::create_redirect_client(
  6610. const std::string &scheme, const std::string &host, int port, Request &req,
  6611. Response &res, const std::string &path, const std::string &location,
  6612. Error &error) {
  6613. // Determine if we need SSL
  6614. auto need_ssl = (scheme == "https");
  6615. // Clean up request headers that are host/client specific
  6616. // Remove headers that should not be carried over to new host
  6617. auto headers_to_remove =
  6618. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  6619. for (const auto &header_name : headers_to_remove) {
  6620. auto it = req.headers.find(header_name);
  6621. while (it != req.headers.end()) {
  6622. it = req.headers.erase(it);
  6623. it = req.headers.find(header_name);
  6624. }
  6625. }
  6626. // Create appropriate client type and handle redirect
  6627. if (need_ssl) {
  6628. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6629. // Create SSL client for HTTPS redirect
  6630. SSLClient redirect_client(host, port);
  6631. // Setup basic client configuration first
  6632. setup_redirect_client(redirect_client);
  6633. // SSL-specific configuration for proxy environments
  6634. if (!proxy_host_.empty() && proxy_port_ != -1) {
  6635. // Critical: Disable SSL verification for proxy environments
  6636. redirect_client.enable_server_certificate_verification(false);
  6637. redirect_client.enable_server_hostname_verification(false);
  6638. } else {
  6639. // For direct SSL connections, copy SSL verification settings
  6640. redirect_client.enable_server_certificate_verification(
  6641. server_certificate_verification_);
  6642. redirect_client.enable_server_hostname_verification(
  6643. server_hostname_verification_);
  6644. }
  6645. // Handle CA certificate store and paths if available
  6646. if (ca_cert_store_) { redirect_client.set_ca_cert_store(ca_cert_store_); }
  6647. if (!ca_cert_file_path_.empty()) {
  6648. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  6649. }
  6650. // Client certificates are set through constructor for SSLClient
  6651. // NOTE: SSLClient constructor already takes client_cert_path and
  6652. // client_key_path so we need to create it properly if client certs are
  6653. // needed
  6654. // Execute the redirect
  6655. return detail::redirect(redirect_client, req, res, path, location, error);
  6656. #else
  6657. // SSL not supported - set appropriate error
  6658. error = Error::SSLConnection;
  6659. return false;
  6660. #endif
  6661. } else {
  6662. // HTTP redirect
  6663. ClientImpl redirect_client(host, port);
  6664. // Setup client with robust configuration
  6665. setup_redirect_client(redirect_client);
  6666. // Execute the redirect
  6667. return detail::redirect(redirect_client, req, res, path, location, error);
  6668. }
  6669. }
  6670. // New method for robust client setup (based on basic_manual_redirect.cpp logic)
  6671. template <typename ClientType>
  6672. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  6673. // Copy basic settings first
  6674. client.set_connection_timeout(connection_timeout_sec_);
  6675. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  6676. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  6677. client.set_keep_alive(keep_alive_);
  6678. client.set_follow_location(
  6679. true); // Enable redirects to handle multi-step redirects
  6680. client.set_url_encode(url_encode_);
  6681. client.set_compress(compress_);
  6682. client.set_decompress(decompress_);
  6683. // Copy authentication settings BEFORE proxy setup
  6684. if (!basic_auth_username_.empty()) {
  6685. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  6686. }
  6687. if (!bearer_token_auth_token_.empty()) {
  6688. client.set_bearer_token_auth(bearer_token_auth_token_);
  6689. }
  6690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6691. if (!digest_auth_username_.empty()) {
  6692. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  6693. }
  6694. #endif
  6695. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  6696. // before proxy auth)
  6697. if (!proxy_host_.empty() && proxy_port_ != -1) {
  6698. // First set proxy host and port
  6699. client.set_proxy(proxy_host_, proxy_port_);
  6700. // Then set proxy authentication (order matters!)
  6701. if (!proxy_basic_auth_username_.empty()) {
  6702. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  6703. proxy_basic_auth_password_);
  6704. }
  6705. if (!proxy_bearer_token_auth_token_.empty()) {
  6706. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  6707. }
  6708. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6709. if (!proxy_digest_auth_username_.empty()) {
  6710. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  6711. proxy_digest_auth_password_);
  6712. }
  6713. #endif
  6714. }
  6715. // Copy network and socket settings
  6716. client.set_address_family(address_family_);
  6717. client.set_tcp_nodelay(tcp_nodelay_);
  6718. client.set_ipv6_v6only(ipv6_v6only_);
  6719. if (socket_options_) { client.set_socket_options(socket_options_); }
  6720. if (!interface_.empty()) { client.set_interface(interface_); }
  6721. // Copy logging and headers
  6722. if (logger_) { client.set_logger(logger_); }
  6723. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  6724. // Each new client should generate its own headers based on its target host
  6725. }
  6726. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  6727. const Request &req,
  6728. Error &error) const {
  6729. auto is_shutting_down = []() { return false; };
  6730. if (req.is_chunked_content_provider_) {
  6731. // TODO: Brotli support
  6732. std::unique_ptr<detail::compressor> compressor;
  6733. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6734. if (compress_) {
  6735. compressor = detail::make_unique<detail::gzip_compressor>();
  6736. } else
  6737. #endif
  6738. {
  6739. compressor = detail::make_unique<detail::nocompressor>();
  6740. }
  6741. return detail::write_content_chunked(strm, req.content_provider_,
  6742. is_shutting_down, *compressor, error);
  6743. } else {
  6744. return detail::write_content_with_progress(
  6745. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  6746. req.upload_progress, error);
  6747. }
  6748. }
  6749. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  6750. bool close_connection, Error &error) {
  6751. // Prepare additional headers
  6752. if (close_connection) {
  6753. if (!req.has_header("Connection")) {
  6754. req.set_header("Connection", "close");
  6755. }
  6756. }
  6757. if (!req.has_header("Host")) {
  6758. if (is_ssl()) {
  6759. if (port_ == 443) {
  6760. req.set_header("Host", host_);
  6761. } else {
  6762. req.set_header("Host", host_and_port_);
  6763. }
  6764. } else {
  6765. if (port_ == 80) {
  6766. req.set_header("Host", host_);
  6767. } else {
  6768. req.set_header("Host", host_and_port_);
  6769. }
  6770. }
  6771. }
  6772. if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); }
  6773. if (!req.content_receiver) {
  6774. if (!req.has_header("Accept-Encoding")) {
  6775. std::string accept_encoding;
  6776. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6777. accept_encoding = "br";
  6778. #endif
  6779. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6780. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  6781. accept_encoding += "gzip, deflate";
  6782. #endif
  6783. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6784. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  6785. accept_encoding += "zstd";
  6786. #endif
  6787. req.set_header("Accept-Encoding", accept_encoding);
  6788. }
  6789. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  6790. if (!req.has_header("User-Agent")) {
  6791. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  6792. req.set_header("User-Agent", agent);
  6793. }
  6794. #endif
  6795. };
  6796. if (req.body.empty()) {
  6797. if (req.content_provider_) {
  6798. if (!req.is_chunked_content_provider_) {
  6799. if (!req.has_header("Content-Length")) {
  6800. auto length = std::to_string(req.content_length_);
  6801. req.set_header("Content-Length", length);
  6802. }
  6803. }
  6804. } else {
  6805. if (req.method == "POST" || req.method == "PUT" ||
  6806. req.method == "PATCH") {
  6807. req.set_header("Content-Length", "0");
  6808. }
  6809. }
  6810. } else {
  6811. if (!req.has_header("Content-Type")) {
  6812. req.set_header("Content-Type", "text/plain");
  6813. }
  6814. if (!req.has_header("Content-Length")) {
  6815. auto length = std::to_string(req.body.size());
  6816. req.set_header("Content-Length", length);
  6817. }
  6818. }
  6819. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  6820. if (!req.has_header("Authorization")) {
  6821. req.headers.insert(make_basic_authentication_header(
  6822. basic_auth_username_, basic_auth_password_, false));
  6823. }
  6824. }
  6825. if (!proxy_basic_auth_username_.empty() &&
  6826. !proxy_basic_auth_password_.empty()) {
  6827. if (!req.has_header("Proxy-Authorization")) {
  6828. req.headers.insert(make_basic_authentication_header(
  6829. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  6830. }
  6831. }
  6832. if (!bearer_token_auth_token_.empty()) {
  6833. if (!req.has_header("Authorization")) {
  6834. req.headers.insert(make_bearer_token_authentication_header(
  6835. bearer_token_auth_token_, false));
  6836. }
  6837. }
  6838. if (!proxy_bearer_token_auth_token_.empty()) {
  6839. if (!req.has_header("Proxy-Authorization")) {
  6840. req.headers.insert(make_bearer_token_authentication_header(
  6841. proxy_bearer_token_auth_token_, true));
  6842. }
  6843. }
  6844. // Request line and headers
  6845. {
  6846. detail::BufferStream bstrm;
  6847. const auto &path_with_query =
  6848. req.params.empty() ? req.path
  6849. : append_query_params(req.path, req.params);
  6850. const auto &path =
  6851. url_encode_ ? detail::encode_url(path_with_query) : path_with_query;
  6852. detail::write_request_line(bstrm, req.method, path);
  6853. header_writer_(bstrm, req.headers);
  6854. // Flush buffer
  6855. auto &data = bstrm.get_buffer();
  6856. if (!detail::write_data(strm, data.data(), data.size())) {
  6857. error = Error::Write;
  6858. return false;
  6859. }
  6860. }
  6861. // Body
  6862. if (req.body.empty()) {
  6863. return write_content_with_provider(strm, req, error);
  6864. }
  6865. if (req.upload_progress) {
  6866. auto body_size = req.body.size();
  6867. size_t written = 0;
  6868. auto data = req.body.data();
  6869. while (written < body_size) {
  6870. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  6871. if (!detail::write_data(strm, data + written, to_write)) {
  6872. error = Error::Write;
  6873. return false;
  6874. }
  6875. written += to_write;
  6876. if (!req.upload_progress(written, body_size)) {
  6877. error = Error::Canceled;
  6878. return false;
  6879. }
  6880. }
  6881. } else {
  6882. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  6883. error = Error::Write;
  6884. return false;
  6885. }
  6886. }
  6887. return true;
  6888. }
  6889. inline std::unique_ptr<Response> ClientImpl::send_with_content_provider(
  6890. Request &req, const char *body, size_t content_length,
  6891. ContentProvider content_provider,
  6892. ContentProviderWithoutLength content_provider_without_length,
  6893. const std::string &content_type, Error &error) {
  6894. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  6895. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6896. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  6897. #endif
  6898. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6899. if (compress_ && !content_provider_without_length) {
  6900. // TODO: Brotli support
  6901. detail::gzip_compressor compressor;
  6902. if (content_provider) {
  6903. auto ok = true;
  6904. size_t offset = 0;
  6905. DataSink data_sink;
  6906. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  6907. if (ok) {
  6908. auto last = offset + data_len == content_length;
  6909. auto ret = compressor.compress(
  6910. data, data_len, last,
  6911. [&](const char *compressed_data, size_t compressed_data_len) {
  6912. req.body.append(compressed_data, compressed_data_len);
  6913. return true;
  6914. });
  6915. if (ret) {
  6916. offset += data_len;
  6917. } else {
  6918. ok = false;
  6919. }
  6920. }
  6921. return ok;
  6922. };
  6923. while (ok && offset < content_length) {
  6924. if (!content_provider(offset, content_length - offset, data_sink)) {
  6925. error = Error::Canceled;
  6926. return nullptr;
  6927. }
  6928. }
  6929. } else {
  6930. if (!compressor.compress(body, content_length, true,
  6931. [&](const char *data, size_t data_len) {
  6932. req.body.append(data, data_len);
  6933. return true;
  6934. })) {
  6935. error = Error::Compression;
  6936. return nullptr;
  6937. }
  6938. }
  6939. } else
  6940. #endif
  6941. {
  6942. if (content_provider) {
  6943. req.content_length_ = content_length;
  6944. req.content_provider_ = std::move(content_provider);
  6945. req.is_chunked_content_provider_ = false;
  6946. } else if (content_provider_without_length) {
  6947. req.content_length_ = 0;
  6948. req.content_provider_ = detail::ContentProviderAdapter(
  6949. std::move(content_provider_without_length));
  6950. req.is_chunked_content_provider_ = true;
  6951. req.set_header("Transfer-Encoding", "chunked");
  6952. } else {
  6953. req.body.assign(body, content_length);
  6954. }
  6955. }
  6956. auto res = detail::make_unique<Response>();
  6957. return send(req, *res, error) ? std::move(res) : nullptr;
  6958. }
  6959. inline Result ClientImpl::send_with_content_provider(
  6960. const std::string &method, const std::string &path, const Headers &headers,
  6961. const char *body, size_t content_length, ContentProvider content_provider,
  6962. ContentProviderWithoutLength content_provider_without_length,
  6963. const std::string &content_type, UploadProgress progress) {
  6964. Request req;
  6965. req.method = method;
  6966. req.headers = headers;
  6967. req.path = path;
  6968. req.upload_progress = std::move(progress);
  6969. if (max_timeout_msec_ > 0) {
  6970. req.start_time_ = std::chrono::steady_clock::now();
  6971. }
  6972. auto error = Error::Success;
  6973. auto res = send_with_content_provider(
  6974. req, body, content_length, std::move(content_provider),
  6975. std::move(content_provider_without_length), content_type, error);
  6976. return Result{std::move(res), error, std::move(req.headers)};
  6977. }
  6978. inline std::string
  6979. ClientImpl::adjust_host_string(const std::string &host) const {
  6980. if (host.find(':') != std::string::npos) { return "[" + host + "]"; }
  6981. return host;
  6982. }
  6983. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  6984. Response &res, bool close_connection,
  6985. Error &error) {
  6986. // Send request
  6987. if (!write_request(strm, req, close_connection, error)) { return false; }
  6988. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6989. if (is_ssl()) {
  6990. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  6991. if (!is_proxy_enabled) {
  6992. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  6993. error = Error::SSLPeerCouldBeClosed_;
  6994. return false;
  6995. }
  6996. }
  6997. }
  6998. #endif
  6999. // Receive response and headers
  7000. if (!read_response_line(strm, req, res) ||
  7001. !detail::read_headers(strm, res.headers)) {
  7002. error = Error::Read;
  7003. return false;
  7004. }
  7005. // Body
  7006. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  7007. req.method != "CONNECT") {
  7008. auto redirect = 300 < res.status && res.status < 400 &&
  7009. res.status != StatusCode::NotModified_304 &&
  7010. follow_location_;
  7011. if (req.response_handler && !redirect) {
  7012. if (!req.response_handler(res)) {
  7013. error = Error::Canceled;
  7014. return false;
  7015. }
  7016. }
  7017. auto out =
  7018. req.content_receiver
  7019. ? static_cast<ContentReceiverWithProgress>(
  7020. [&](const char *buf, size_t n, uint64_t off, uint64_t len) {
  7021. if (redirect) { return true; }
  7022. auto ret = req.content_receiver(buf, n, off, len);
  7023. if (!ret) { error = Error::Canceled; }
  7024. return ret;
  7025. })
  7026. : static_cast<ContentReceiverWithProgress>(
  7027. [&](const char *buf, size_t n, uint64_t /*off*/,
  7028. uint64_t /*len*/) {
  7029. assert(res.body.size() + n <= res.body.max_size());
  7030. res.body.append(buf, n);
  7031. return true;
  7032. });
  7033. auto progress = [&](uint64_t current, uint64_t total) {
  7034. if (!req.download_progress || redirect) { return true; }
  7035. auto ret = req.download_progress(current, total);
  7036. if (!ret) { error = Error::Canceled; }
  7037. return ret;
  7038. };
  7039. if (res.has_header("Content-Length")) {
  7040. if (!req.content_receiver) {
  7041. auto len = res.get_header_value_u64("Content-Length");
  7042. if (len > res.body.max_size()) {
  7043. error = Error::Read;
  7044. return false;
  7045. }
  7046. res.body.reserve(static_cast<size_t>(len));
  7047. }
  7048. }
  7049. if (res.status != StatusCode::NotModified_304) {
  7050. int dummy_status;
  7051. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  7052. dummy_status, std::move(progress),
  7053. std::move(out), decompress_)) {
  7054. if (error != Error::Canceled) { error = Error::Read; }
  7055. return false;
  7056. }
  7057. }
  7058. }
  7059. // Log
  7060. if (logger_) { logger_(req, res); }
  7061. return true;
  7062. }
  7063. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  7064. const std::string &boundary,
  7065. const MultipartFormDataItemsForClientInput &items,
  7066. const MultipartFormDataProviderItems &provider_items) const {
  7067. size_t cur_item = 0;
  7068. size_t cur_start = 0;
  7069. // cur_item and cur_start are copied to within the std::function and maintain
  7070. // state between successive calls
  7071. return [&, cur_item, cur_start](size_t offset,
  7072. DataSink &sink) mutable -> bool {
  7073. if (!offset && !items.empty()) {
  7074. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  7075. return true;
  7076. } else if (cur_item < provider_items.size()) {
  7077. if (!cur_start) {
  7078. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  7079. provider_items[cur_item], boundary);
  7080. offset += begin.size();
  7081. cur_start = offset;
  7082. sink.os << begin;
  7083. }
  7084. DataSink cur_sink;
  7085. auto has_data = true;
  7086. cur_sink.write = sink.write;
  7087. cur_sink.done = [&]() { has_data = false; };
  7088. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  7089. return false;
  7090. }
  7091. if (!has_data) {
  7092. sink.os << detail::serialize_multipart_formdata_item_end();
  7093. cur_item++;
  7094. cur_start = 0;
  7095. }
  7096. return true;
  7097. } else {
  7098. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  7099. sink.done();
  7100. return true;
  7101. }
  7102. };
  7103. }
  7104. inline bool ClientImpl::process_socket(
  7105. const Socket &socket,
  7106. std::chrono::time_point<std::chrono::steady_clock> start_time,
  7107. std::function<bool(Stream &strm)> callback) {
  7108. return detail::process_client_socket(
  7109. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  7110. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  7111. }
  7112. inline bool ClientImpl::is_ssl() const { return false; }
  7113. inline Result ClientImpl::Get(const std::string &path,
  7114. DownloadProgress progress) {
  7115. return Get(path, Headers(), std::move(progress));
  7116. }
  7117. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  7118. const Headers &headers,
  7119. DownloadProgress progress) {
  7120. if (params.empty()) { return Get(path, headers); }
  7121. std::string path_with_query = append_query_params(path, params);
  7122. return Get(path_with_query, headers, std::move(progress));
  7123. }
  7124. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  7125. DownloadProgress progress) {
  7126. Request req;
  7127. req.method = "GET";
  7128. req.path = path;
  7129. req.headers = headers;
  7130. req.download_progress = std::move(progress);
  7131. if (max_timeout_msec_ > 0) {
  7132. req.start_time_ = std::chrono::steady_clock::now();
  7133. }
  7134. return send_(std::move(req));
  7135. }
  7136. inline Result ClientImpl::Get(const std::string &path,
  7137. ContentReceiver content_receiver,
  7138. DownloadProgress progress) {
  7139. return Get(path, Headers(), nullptr, std::move(content_receiver),
  7140. std::move(progress));
  7141. }
  7142. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  7143. ContentReceiver content_receiver,
  7144. DownloadProgress progress) {
  7145. return Get(path, headers, nullptr, std::move(content_receiver),
  7146. std::move(progress));
  7147. }
  7148. inline Result ClientImpl::Get(const std::string &path,
  7149. ResponseHandler response_handler,
  7150. ContentReceiver content_receiver,
  7151. DownloadProgress progress) {
  7152. return Get(path, Headers(), std::move(response_handler),
  7153. std::move(content_receiver), std::move(progress));
  7154. }
  7155. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  7156. ResponseHandler response_handler,
  7157. ContentReceiver content_receiver,
  7158. DownloadProgress progress) {
  7159. Request req;
  7160. req.method = "GET";
  7161. req.path = path;
  7162. req.headers = headers;
  7163. req.response_handler = std::move(response_handler);
  7164. req.content_receiver =
  7165. [content_receiver](const char *data, size_t data_length,
  7166. uint64_t /*offset*/, uint64_t /*total_length*/) {
  7167. return content_receiver(data, data_length);
  7168. };
  7169. req.download_progress = std::move(progress);
  7170. if (max_timeout_msec_ > 0) {
  7171. req.start_time_ = std::chrono::steady_clock::now();
  7172. }
  7173. return send_(std::move(req));
  7174. }
  7175. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  7176. const Headers &headers,
  7177. ContentReceiver content_receiver,
  7178. DownloadProgress progress) {
  7179. return Get(path, params, headers, nullptr, std::move(content_receiver),
  7180. std::move(progress));
  7181. }
  7182. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  7183. const Headers &headers,
  7184. ResponseHandler response_handler,
  7185. ContentReceiver content_receiver,
  7186. DownloadProgress progress) {
  7187. if (params.empty()) {
  7188. return Get(path, headers, std::move(response_handler),
  7189. std::move(content_receiver), std::move(progress));
  7190. }
  7191. std::string path_with_query = append_query_params(path, params);
  7192. return Get(path_with_query, headers, std::move(response_handler),
  7193. std::move(content_receiver), std::move(progress));
  7194. }
  7195. inline Result ClientImpl::Head(const std::string &path) {
  7196. return Head(path, Headers());
  7197. }
  7198. inline Result ClientImpl::Head(const std::string &path,
  7199. const Headers &headers) {
  7200. Request req;
  7201. req.method = "HEAD";
  7202. req.headers = headers;
  7203. req.path = path;
  7204. if (max_timeout_msec_ > 0) {
  7205. req.start_time_ = std::chrono::steady_clock::now();
  7206. }
  7207. return send_(std::move(req));
  7208. }
  7209. inline Result ClientImpl::Post(const std::string &path) {
  7210. return Post(path, std::string(), std::string());
  7211. }
  7212. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7213. UploadProgress progress) {
  7214. return Post(path, headers, nullptr, 0, std::string(), progress);
  7215. }
  7216. inline Result ClientImpl::Post(const std::string &path, const char *body,
  7217. size_t content_length,
  7218. const std::string &content_type,
  7219. UploadProgress progress) {
  7220. return Post(path, Headers(), body, content_length, content_type, progress);
  7221. }
  7222. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  7223. const std::string &content_type,
  7224. UploadProgress progress) {
  7225. return Post(path, Headers(), body, content_type, progress);
  7226. }
  7227. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  7228. return Post(path, Headers(), params);
  7229. }
  7230. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  7231. ContentProvider content_provider,
  7232. const std::string &content_type,
  7233. UploadProgress progress) {
  7234. return Post(path, Headers(), content_length, std::move(content_provider),
  7235. content_type, progress);
  7236. }
  7237. inline Result ClientImpl::Post(const std::string &path,
  7238. ContentProviderWithoutLength content_provider,
  7239. const std::string &content_type,
  7240. UploadProgress progress) {
  7241. return Post(path, Headers(), std::move(content_provider), content_type,
  7242. progress);
  7243. }
  7244. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7245. const Params &params) {
  7246. auto query = detail::params_to_query_str(params);
  7247. return Post(path, headers, query, "application/x-www-form-urlencoded");
  7248. }
  7249. inline Result
  7250. ClientImpl::Post(const std::string &path,
  7251. const MultipartFormDataItemsForClientInput &items,
  7252. UploadProgress progress) {
  7253. return Post(path, Headers(), items, progress);
  7254. }
  7255. inline Result
  7256. ClientImpl::Post(const std::string &path, const Headers &headers,
  7257. const MultipartFormDataItemsForClientInput &items,
  7258. UploadProgress progress) {
  7259. const auto &boundary = detail::make_multipart_data_boundary();
  7260. const auto &content_type =
  7261. detail::serialize_multipart_formdata_get_content_type(boundary);
  7262. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7263. return Post(path, headers, body, content_type, progress);
  7264. }
  7265. inline Result
  7266. ClientImpl::Post(const std::string &path, const Headers &headers,
  7267. const MultipartFormDataItemsForClientInput &items,
  7268. const std::string &boundary, UploadProgress progress) {
  7269. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  7270. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  7271. }
  7272. const auto &content_type =
  7273. detail::serialize_multipart_formdata_get_content_type(boundary);
  7274. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7275. return Post(path, headers, body, content_type, progress);
  7276. }
  7277. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7278. const char *body, size_t content_length,
  7279. const std::string &content_type,
  7280. UploadProgress progress) {
  7281. return send_with_content_provider("POST", path, headers, body, content_length,
  7282. nullptr, nullptr, content_type, progress);
  7283. }
  7284. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7285. const std::string &body,
  7286. const std::string &content_type,
  7287. UploadProgress progress) {
  7288. return send_with_content_provider("POST", path, headers, body.data(),
  7289. body.size(), nullptr, nullptr, content_type,
  7290. progress);
  7291. }
  7292. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7293. size_t content_length,
  7294. ContentProvider content_provider,
  7295. const std::string &content_type,
  7296. UploadProgress progress) {
  7297. return send_with_content_provider("POST", path, headers, nullptr,
  7298. content_length, std::move(content_provider),
  7299. nullptr, content_type, progress);
  7300. }
  7301. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7302. ContentProviderWithoutLength content_provider,
  7303. const std::string &content_type,
  7304. UploadProgress progress) {
  7305. return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr,
  7306. std::move(content_provider), content_type,
  7307. progress);
  7308. }
  7309. inline Result
  7310. ClientImpl::Post(const std::string &path, const Headers &headers,
  7311. const MultipartFormDataItemsForClientInput &items,
  7312. const MultipartFormDataProviderItems &provider_items,
  7313. UploadProgress progress) {
  7314. const auto &boundary = detail::make_multipart_data_boundary();
  7315. const auto &content_type =
  7316. detail::serialize_multipart_formdata_get_content_type(boundary);
  7317. return send_with_content_provider(
  7318. "POST", path, headers, nullptr, 0, nullptr,
  7319. get_multipart_content_provider(boundary, items, provider_items),
  7320. content_type, progress);
  7321. }
  7322. inline Result ClientImpl::Put(const std::string &path) {
  7323. return Put(path, std::string(), std::string());
  7324. }
  7325. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7326. UploadProgress progress) {
  7327. return Put(path, headers, nullptr, 0, std::string(), progress);
  7328. }
  7329. inline Result ClientImpl::Put(const std::string &path, const char *body,
  7330. size_t content_length,
  7331. const std::string &content_type,
  7332. UploadProgress progress) {
  7333. return Put(path, Headers(), body, content_length, content_type, progress);
  7334. }
  7335. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  7336. const std::string &content_type,
  7337. UploadProgress progress) {
  7338. return Put(path, Headers(), body, content_type, progress);
  7339. }
  7340. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  7341. return Put(path, Headers(), params);
  7342. }
  7343. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  7344. ContentProvider content_provider,
  7345. const std::string &content_type,
  7346. UploadProgress progress) {
  7347. return Put(path, Headers(), content_length, std::move(content_provider),
  7348. content_type, progress);
  7349. }
  7350. inline Result ClientImpl::Put(const std::string &path,
  7351. ContentProviderWithoutLength content_provider,
  7352. const std::string &content_type,
  7353. UploadProgress progress) {
  7354. return Put(path, Headers(), std::move(content_provider), content_type,
  7355. progress);
  7356. }
  7357. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7358. const Params &params) {
  7359. auto query = detail::params_to_query_str(params);
  7360. return Put(path, headers, query, "application/x-www-form-urlencoded");
  7361. }
  7362. inline Result ClientImpl::Put(const std::string &path,
  7363. const MultipartFormDataItemsForClientInput &items,
  7364. UploadProgress progress) {
  7365. return Put(path, Headers(), items, progress);
  7366. }
  7367. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7368. const MultipartFormDataItemsForClientInput &items,
  7369. UploadProgress progress) {
  7370. const auto &boundary = detail::make_multipart_data_boundary();
  7371. const auto &content_type =
  7372. detail::serialize_multipart_formdata_get_content_type(boundary);
  7373. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7374. return Put(path, headers, body, content_type, progress);
  7375. }
  7376. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7377. const MultipartFormDataItemsForClientInput &items,
  7378. const std::string &boundary,
  7379. UploadProgress progress) {
  7380. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  7381. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  7382. }
  7383. const auto &content_type =
  7384. detail::serialize_multipart_formdata_get_content_type(boundary);
  7385. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7386. return Put(path, headers, body, content_type, progress);
  7387. }
  7388. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7389. const char *body, size_t content_length,
  7390. const std::string &content_type,
  7391. UploadProgress progress) {
  7392. return send_with_content_provider("PUT", path, headers, body, content_length,
  7393. nullptr, nullptr, content_type, progress);
  7394. }
  7395. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7396. const std::string &body,
  7397. const std::string &content_type,
  7398. UploadProgress progress) {
  7399. return send_with_content_provider("PUT", path, headers, body.data(),
  7400. body.size(), nullptr, nullptr, content_type,
  7401. progress);
  7402. }
  7403. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7404. size_t content_length,
  7405. ContentProvider content_provider,
  7406. const std::string &content_type,
  7407. UploadProgress progress) {
  7408. return send_with_content_provider("PUT", path, headers, nullptr,
  7409. content_length, std::move(content_provider),
  7410. nullptr, content_type, progress);
  7411. }
  7412. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7413. ContentProviderWithoutLength content_provider,
  7414. const std::string &content_type,
  7415. UploadProgress progress) {
  7416. return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr,
  7417. std::move(content_provider), content_type,
  7418. progress);
  7419. }
  7420. inline Result
  7421. ClientImpl::Put(const std::string &path, const Headers &headers,
  7422. const MultipartFormDataItemsForClientInput &items,
  7423. const MultipartFormDataProviderItems &provider_items,
  7424. UploadProgress progress) {
  7425. const auto &boundary = detail::make_multipart_data_boundary();
  7426. const auto &content_type =
  7427. detail::serialize_multipart_formdata_get_content_type(boundary);
  7428. return send_with_content_provider(
  7429. "PUT", path, headers, nullptr, 0, nullptr,
  7430. get_multipart_content_provider(boundary, items, provider_items),
  7431. content_type, progress);
  7432. }
  7433. inline Result ClientImpl::Patch(const std::string &path) {
  7434. return Patch(path, std::string(), std::string());
  7435. }
  7436. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7437. UploadProgress progress) {
  7438. return Patch(path, headers, nullptr, 0, std::string(), progress);
  7439. }
  7440. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  7441. size_t content_length,
  7442. const std::string &content_type,
  7443. UploadProgress progress) {
  7444. return Patch(path, Headers(), body, content_length, content_type, progress);
  7445. }
  7446. inline Result ClientImpl::Patch(const std::string &path,
  7447. const std::string &body,
  7448. const std::string &content_type,
  7449. UploadProgress progress) {
  7450. return Patch(path, Headers(), body, content_type, progress);
  7451. }
  7452. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  7453. return Patch(path, Headers(), params);
  7454. }
  7455. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  7456. ContentProvider content_provider,
  7457. const std::string &content_type,
  7458. UploadProgress progress) {
  7459. return Patch(path, Headers(), content_length, std::move(content_provider),
  7460. content_type, progress);
  7461. }
  7462. inline Result ClientImpl::Patch(const std::string &path,
  7463. ContentProviderWithoutLength content_provider,
  7464. const std::string &content_type,
  7465. UploadProgress progress) {
  7466. return Patch(path, Headers(), std::move(content_provider), content_type,
  7467. progress);
  7468. }
  7469. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7470. const Params &params) {
  7471. auto query = detail::params_to_query_str(params);
  7472. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  7473. }
  7474. inline Result
  7475. ClientImpl::Patch(const std::string &path,
  7476. const MultipartFormDataItemsForClientInput &items,
  7477. UploadProgress progress) {
  7478. return Patch(path, Headers(), items, progress);
  7479. }
  7480. inline Result
  7481. ClientImpl::Patch(const std::string &path, const Headers &headers,
  7482. const MultipartFormDataItemsForClientInput &items,
  7483. UploadProgress progress) {
  7484. const auto &boundary = detail::make_multipart_data_boundary();
  7485. const auto &content_type =
  7486. detail::serialize_multipart_formdata_get_content_type(boundary);
  7487. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7488. return Patch(path, headers, body, content_type, progress);
  7489. }
  7490. inline Result
  7491. ClientImpl::Patch(const std::string &path, const Headers &headers,
  7492. const MultipartFormDataItemsForClientInput &items,
  7493. const std::string &boundary, UploadProgress progress) {
  7494. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  7495. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  7496. }
  7497. const auto &content_type =
  7498. detail::serialize_multipart_formdata_get_content_type(boundary);
  7499. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7500. return Patch(path, headers, body, content_type, progress);
  7501. }
  7502. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7503. const char *body, size_t content_length,
  7504. const std::string &content_type,
  7505. UploadProgress progress) {
  7506. return send_with_content_provider("PATCH", path, headers, body,
  7507. content_length, nullptr, nullptr,
  7508. content_type, progress);
  7509. }
  7510. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7511. const std::string &body,
  7512. const std::string &content_type,
  7513. UploadProgress progress) {
  7514. return send_with_content_provider("PATCH", path, headers, body.data(),
  7515. body.size(), nullptr, nullptr, content_type,
  7516. progress);
  7517. }
  7518. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7519. size_t content_length,
  7520. ContentProvider content_provider,
  7521. const std::string &content_type,
  7522. UploadProgress progress) {
  7523. return send_with_content_provider("PATCH", path, headers, nullptr,
  7524. content_length, std::move(content_provider),
  7525. nullptr, content_type, progress);
  7526. }
  7527. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7528. ContentProviderWithoutLength content_provider,
  7529. const std::string &content_type,
  7530. UploadProgress progress) {
  7531. return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr,
  7532. std::move(content_provider), content_type,
  7533. progress);
  7534. }
  7535. inline Result
  7536. ClientImpl::Patch(const std::string &path, const Headers &headers,
  7537. const MultipartFormDataItemsForClientInput &items,
  7538. const MultipartFormDataProviderItems &provider_items,
  7539. UploadProgress progress) {
  7540. const auto &boundary = detail::make_multipart_data_boundary();
  7541. const auto &content_type =
  7542. detail::serialize_multipart_formdata_get_content_type(boundary);
  7543. return send_with_content_provider(
  7544. "PATCH", path, headers, nullptr, 0, nullptr,
  7545. get_multipart_content_provider(boundary, items, provider_items),
  7546. content_type, progress);
  7547. }
  7548. inline Result ClientImpl::Delete(const std::string &path,
  7549. DownloadProgress progress) {
  7550. return Delete(path, Headers(), std::string(), std::string(), progress);
  7551. }
  7552. inline Result ClientImpl::Delete(const std::string &path,
  7553. const Headers &headers,
  7554. DownloadProgress progress) {
  7555. return Delete(path, headers, std::string(), std::string(), progress);
  7556. }
  7557. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  7558. size_t content_length,
  7559. const std::string &content_type,
  7560. DownloadProgress progress) {
  7561. return Delete(path, Headers(), body, content_length, content_type, progress);
  7562. }
  7563. inline Result ClientImpl::Delete(const std::string &path,
  7564. const std::string &body,
  7565. const std::string &content_type,
  7566. DownloadProgress progress) {
  7567. return Delete(path, Headers(), body.data(), body.size(), content_type,
  7568. progress);
  7569. }
  7570. inline Result ClientImpl::Delete(const std::string &path,
  7571. const Headers &headers,
  7572. const std::string &body,
  7573. const std::string &content_type,
  7574. DownloadProgress progress) {
  7575. return Delete(path, headers, body.data(), body.size(), content_type,
  7576. progress);
  7577. }
  7578. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  7579. DownloadProgress progress) {
  7580. return Delete(path, Headers(), params, progress);
  7581. }
  7582. inline Result ClientImpl::Delete(const std::string &path,
  7583. const Headers &headers, const Params &params,
  7584. DownloadProgress progress) {
  7585. auto query = detail::params_to_query_str(params);
  7586. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  7587. progress);
  7588. }
  7589. inline Result ClientImpl::Delete(const std::string &path,
  7590. const Headers &headers, const char *body,
  7591. size_t content_length,
  7592. const std::string &content_type,
  7593. DownloadProgress progress) {
  7594. Request req;
  7595. req.method = "DELETE";
  7596. req.headers = headers;
  7597. req.path = path;
  7598. req.download_progress = std::move(progress);
  7599. if (max_timeout_msec_ > 0) {
  7600. req.start_time_ = std::chrono::steady_clock::now();
  7601. }
  7602. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  7603. req.body.assign(body, content_length);
  7604. return send_(std::move(req));
  7605. }
  7606. inline Result ClientImpl::Options(const std::string &path) {
  7607. return Options(path, Headers());
  7608. }
  7609. inline Result ClientImpl::Options(const std::string &path,
  7610. const Headers &headers) {
  7611. Request req;
  7612. req.method = "OPTIONS";
  7613. req.headers = headers;
  7614. req.path = path;
  7615. if (max_timeout_msec_ > 0) {
  7616. req.start_time_ = std::chrono::steady_clock::now();
  7617. }
  7618. return send_(std::move(req));
  7619. }
  7620. inline void ClientImpl::stop() {
  7621. std::lock_guard<std::mutex> guard(socket_mutex_);
  7622. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  7623. // do is to shutdown_socket, so that threads using this socket suddenly
  7624. // discover they can't read/write any more and error out. Everything else
  7625. // (closing the socket, shutting ssl down) is unsafe because these actions are
  7626. // not thread-safe.
  7627. if (socket_requests_in_flight_ > 0) {
  7628. shutdown_socket(socket_);
  7629. // Aside from that, we set a flag for the socket to be closed when we're
  7630. // done.
  7631. socket_should_be_closed_when_request_is_done_ = true;
  7632. return;
  7633. }
  7634. // Otherwise, still holding the mutex, we can shut everything down ourselves
  7635. shutdown_ssl(socket_, true);
  7636. shutdown_socket(socket_);
  7637. close_socket(socket_);
  7638. }
  7639. inline std::string ClientImpl::host() const { return host_; }
  7640. inline int ClientImpl::port() const { return port_; }
  7641. inline size_t ClientImpl::is_socket_open() const {
  7642. std::lock_guard<std::mutex> guard(socket_mutex_);
  7643. return socket_.is_open();
  7644. }
  7645. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  7646. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  7647. connection_timeout_sec_ = sec;
  7648. connection_timeout_usec_ = usec;
  7649. }
  7650. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  7651. read_timeout_sec_ = sec;
  7652. read_timeout_usec_ = usec;
  7653. }
  7654. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  7655. write_timeout_sec_ = sec;
  7656. write_timeout_usec_ = usec;
  7657. }
  7658. inline void ClientImpl::set_max_timeout(time_t msec) {
  7659. max_timeout_msec_ = msec;
  7660. }
  7661. inline void ClientImpl::set_basic_auth(const std::string &username,
  7662. const std::string &password) {
  7663. basic_auth_username_ = username;
  7664. basic_auth_password_ = password;
  7665. }
  7666. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  7667. bearer_token_auth_token_ = token;
  7668. }
  7669. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7670. inline void ClientImpl::set_digest_auth(const std::string &username,
  7671. const std::string &password) {
  7672. digest_auth_username_ = username;
  7673. digest_auth_password_ = password;
  7674. }
  7675. #endif
  7676. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  7677. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  7678. inline void ClientImpl::set_url_encode(bool on) { url_encode_ = on; }
  7679. inline void
  7680. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  7681. addr_map_ = std::move(addr_map);
  7682. }
  7683. inline void ClientImpl::set_default_headers(Headers headers) {
  7684. default_headers_ = std::move(headers);
  7685. }
  7686. inline void ClientImpl::set_header_writer(
  7687. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7688. header_writer_ = writer;
  7689. }
  7690. inline void ClientImpl::set_address_family(int family) {
  7691. address_family_ = family;
  7692. }
  7693. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  7694. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  7695. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  7696. socket_options_ = std::move(socket_options);
  7697. }
  7698. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  7699. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  7700. inline void ClientImpl::set_interface(const std::string &intf) {
  7701. interface_ = intf;
  7702. }
  7703. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  7704. proxy_host_ = host;
  7705. proxy_port_ = port;
  7706. }
  7707. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  7708. const std::string &password) {
  7709. proxy_basic_auth_username_ = username;
  7710. proxy_basic_auth_password_ = password;
  7711. }
  7712. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  7713. proxy_bearer_token_auth_token_ = token;
  7714. }
  7715. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7716. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  7717. const std::string &password) {
  7718. proxy_digest_auth_username_ = username;
  7719. proxy_digest_auth_password_ = password;
  7720. }
  7721. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  7722. const std::string &ca_cert_dir_path) {
  7723. ca_cert_file_path_ = ca_cert_file_path;
  7724. ca_cert_dir_path_ = ca_cert_dir_path;
  7725. }
  7726. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  7727. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  7728. ca_cert_store_ = ca_cert_store;
  7729. }
  7730. }
  7731. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  7732. std::size_t size) const {
  7733. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  7734. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  7735. if (!mem) { return nullptr; }
  7736. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  7737. if (!inf) { return nullptr; }
  7738. auto cts = X509_STORE_new();
  7739. if (cts) {
  7740. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  7741. auto itmp = sk_X509_INFO_value(inf, i);
  7742. if (!itmp) { continue; }
  7743. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  7744. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  7745. }
  7746. }
  7747. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  7748. return cts;
  7749. }
  7750. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  7751. server_certificate_verification_ = enabled;
  7752. }
  7753. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  7754. server_hostname_verification_ = enabled;
  7755. }
  7756. inline void ClientImpl::set_server_certificate_verifier(
  7757. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  7758. server_certificate_verifier_ = verifier;
  7759. }
  7760. #endif
  7761. inline void ClientImpl::set_logger(Logger logger) {
  7762. logger_ = std::move(logger);
  7763. }
  7764. /*
  7765. * SSL Implementation
  7766. */
  7767. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7768. namespace detail {
  7769. template <typename U, typename V>
  7770. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  7771. U SSL_connect_or_accept, V setup) {
  7772. SSL *ssl = nullptr;
  7773. {
  7774. std::lock_guard<std::mutex> guard(ctx_mutex);
  7775. ssl = SSL_new(ctx);
  7776. }
  7777. if (ssl) {
  7778. set_nonblocking(sock, true);
  7779. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  7780. BIO_set_nbio(bio, 1);
  7781. SSL_set_bio(ssl, bio, bio);
  7782. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  7783. SSL_shutdown(ssl);
  7784. {
  7785. std::lock_guard<std::mutex> guard(ctx_mutex);
  7786. SSL_free(ssl);
  7787. }
  7788. set_nonblocking(sock, false);
  7789. return nullptr;
  7790. }
  7791. BIO_set_nbio(bio, 0);
  7792. set_nonblocking(sock, false);
  7793. }
  7794. return ssl;
  7795. }
  7796. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock,
  7797. bool shutdown_gracefully) {
  7798. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  7799. // the remote has closed the network connection
  7800. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  7801. // best-efforts.
  7802. if (shutdown_gracefully) {
  7803. (void)(sock);
  7804. // SSL_shutdown() returns 0 on first call (indicating close_notify alert
  7805. // sent) and 1 on subsequent call (indicating close_notify alert received)
  7806. if (SSL_shutdown(ssl) == 0) {
  7807. // Expected to return 1, but even if it doesn't, we free ssl
  7808. SSL_shutdown(ssl);
  7809. }
  7810. }
  7811. std::lock_guard<std::mutex> guard(ctx_mutex);
  7812. SSL_free(ssl);
  7813. }
  7814. template <typename U>
  7815. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  7816. U ssl_connect_or_accept,
  7817. time_t timeout_sec,
  7818. time_t timeout_usec) {
  7819. auto res = 0;
  7820. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  7821. auto err = SSL_get_error(ssl, res);
  7822. switch (err) {
  7823. case SSL_ERROR_WANT_READ:
  7824. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  7825. break;
  7826. case SSL_ERROR_WANT_WRITE:
  7827. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  7828. break;
  7829. default: break;
  7830. }
  7831. return false;
  7832. }
  7833. return true;
  7834. }
  7835. template <typename T>
  7836. inline bool process_server_socket_ssl(
  7837. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  7838. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7839. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7840. time_t write_timeout_usec, T callback) {
  7841. return process_server_socket_core(
  7842. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7843. [&](bool close_connection, bool &connection_closed) {
  7844. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  7845. write_timeout_sec, write_timeout_usec);
  7846. return callback(strm, close_connection, connection_closed);
  7847. });
  7848. }
  7849. template <typename T>
  7850. inline bool process_client_socket_ssl(
  7851. SSL *ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  7852. time_t write_timeout_sec, time_t write_timeout_usec,
  7853. time_t max_timeout_msec,
  7854. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7855. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  7856. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7857. start_time);
  7858. return callback(strm);
  7859. }
  7860. // SSL socket stream implementation
  7861. inline SSLSocketStream::SSLSocketStream(
  7862. socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec,
  7863. time_t write_timeout_sec, time_t write_timeout_usec,
  7864. time_t max_timeout_msec,
  7865. std::chrono::time_point<std::chrono::steady_clock> start_time)
  7866. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  7867. read_timeout_usec_(read_timeout_usec),
  7868. write_timeout_sec_(write_timeout_sec),
  7869. write_timeout_usec_(write_timeout_usec),
  7870. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  7871. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  7872. }
  7873. inline SSLSocketStream::~SSLSocketStream() = default;
  7874. inline bool SSLSocketStream::is_readable() const {
  7875. return SSL_pending(ssl_) > 0;
  7876. }
  7877. inline bool SSLSocketStream::wait_readable() const {
  7878. if (max_timeout_msec_ <= 0) {
  7879. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  7880. }
  7881. time_t read_timeout_sec;
  7882. time_t read_timeout_usec;
  7883. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  7884. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  7885. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  7886. }
  7887. inline bool SSLSocketStream::wait_writable() const {
  7888. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  7889. is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_);
  7890. }
  7891. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  7892. if (SSL_pending(ssl_) > 0) {
  7893. return SSL_read(ssl_, ptr, static_cast<int>(size));
  7894. } else if (wait_readable()) {
  7895. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  7896. if (ret < 0) {
  7897. auto err = SSL_get_error(ssl_, ret);
  7898. auto n = 1000;
  7899. #ifdef _WIN32
  7900. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  7901. (err == SSL_ERROR_SYSCALL &&
  7902. WSAGetLastError() == WSAETIMEDOUT))) {
  7903. #else
  7904. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  7905. #endif
  7906. if (SSL_pending(ssl_) > 0) {
  7907. return SSL_read(ssl_, ptr, static_cast<int>(size));
  7908. } else if (wait_readable()) {
  7909. std::this_thread::sleep_for(std::chrono::microseconds{10});
  7910. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  7911. if (ret >= 0) { return ret; }
  7912. err = SSL_get_error(ssl_, ret);
  7913. } else {
  7914. return -1;
  7915. }
  7916. }
  7917. }
  7918. return ret;
  7919. } else {
  7920. return -1;
  7921. }
  7922. }
  7923. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  7924. if (wait_writable()) {
  7925. auto handle_size = static_cast<int>(
  7926. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  7927. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  7928. if (ret < 0) {
  7929. auto err = SSL_get_error(ssl_, ret);
  7930. auto n = 1000;
  7931. #ifdef _WIN32
  7932. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  7933. (err == SSL_ERROR_SYSCALL &&
  7934. WSAGetLastError() == WSAETIMEDOUT))) {
  7935. #else
  7936. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  7937. #endif
  7938. if (wait_writable()) {
  7939. std::this_thread::sleep_for(std::chrono::microseconds{10});
  7940. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  7941. if (ret >= 0) { return ret; }
  7942. err = SSL_get_error(ssl_, ret);
  7943. } else {
  7944. return -1;
  7945. }
  7946. }
  7947. }
  7948. return ret;
  7949. }
  7950. return -1;
  7951. }
  7952. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  7953. int &port) const {
  7954. detail::get_remote_ip_and_port(sock_, ip, port);
  7955. }
  7956. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  7957. int &port) const {
  7958. detail::get_local_ip_and_port(sock_, ip, port);
  7959. }
  7960. inline socket_t SSLSocketStream::socket() const { return sock_; }
  7961. inline time_t SSLSocketStream::duration() const {
  7962. return std::chrono::duration_cast<std::chrono::milliseconds>(
  7963. std::chrono::steady_clock::now() - start_time_)
  7964. .count();
  7965. }
  7966. } // namespace detail
  7967. // SSL HTTP server implementation
  7968. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  7969. const char *client_ca_cert_file_path,
  7970. const char *client_ca_cert_dir_path,
  7971. const char *private_key_password) {
  7972. ctx_ = SSL_CTX_new(TLS_server_method());
  7973. if (ctx_) {
  7974. SSL_CTX_set_options(ctx_,
  7975. SSL_OP_NO_COMPRESSION |
  7976. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7977. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  7978. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  7979. SSL_CTX_set_default_passwd_cb_userdata(
  7980. ctx_,
  7981. reinterpret_cast<void *>(const_cast<char *>(private_key_password)));
  7982. }
  7983. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  7984. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  7985. 1 ||
  7986. SSL_CTX_check_private_key(ctx_) != 1) {
  7987. SSL_CTX_free(ctx_);
  7988. ctx_ = nullptr;
  7989. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  7990. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  7991. client_ca_cert_dir_path);
  7992. SSL_CTX_set_verify(
  7993. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  7994. }
  7995. }
  7996. }
  7997. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  7998. X509_STORE *client_ca_cert_store) {
  7999. ctx_ = SSL_CTX_new(TLS_server_method());
  8000. if (ctx_) {
  8001. SSL_CTX_set_options(ctx_,
  8002. SSL_OP_NO_COMPRESSION |
  8003. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  8004. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  8005. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  8006. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  8007. SSL_CTX_free(ctx_);
  8008. ctx_ = nullptr;
  8009. } else if (client_ca_cert_store) {
  8010. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  8011. SSL_CTX_set_verify(
  8012. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  8013. }
  8014. }
  8015. }
  8016. inline SSLServer::SSLServer(
  8017. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  8018. ctx_ = SSL_CTX_new(TLS_method());
  8019. if (ctx_) {
  8020. if (!setup_ssl_ctx_callback(*ctx_)) {
  8021. SSL_CTX_free(ctx_);
  8022. ctx_ = nullptr;
  8023. }
  8024. }
  8025. }
  8026. inline SSLServer::~SSLServer() {
  8027. if (ctx_) { SSL_CTX_free(ctx_); }
  8028. }
  8029. inline bool SSLServer::is_valid() const { return ctx_; }
  8030. inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  8031. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  8032. X509_STORE *client_ca_cert_store) {
  8033. std::lock_guard<std::mutex> guard(ctx_mutex_);
  8034. SSL_CTX_use_certificate(ctx_, cert);
  8035. SSL_CTX_use_PrivateKey(ctx_, private_key);
  8036. if (client_ca_cert_store != nullptr) {
  8037. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  8038. }
  8039. }
  8040. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  8041. auto ssl = detail::ssl_new(
  8042. sock, ctx_, ctx_mutex_,
  8043. [&](SSL *ssl2) {
  8044. return detail::ssl_connect_or_accept_nonblocking(
  8045. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_);
  8046. },
  8047. [](SSL * /*ssl2*/) { return true; });
  8048. auto ret = false;
  8049. if (ssl) {
  8050. std::string remote_addr;
  8051. int remote_port = 0;
  8052. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8053. std::string local_addr;
  8054. int local_port = 0;
  8055. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8056. ret = detail::process_server_socket_ssl(
  8057. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8058. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8059. write_timeout_usec_,
  8060. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8061. return process_request(strm, remote_addr, remote_port, local_addr,
  8062. local_port, close_connection,
  8063. connection_closed,
  8064. [&](Request &req) { req.ssl = ssl; });
  8065. });
  8066. // Shutdown gracefully if the result seemed successful, non-gracefully if
  8067. // the connection appeared to be closed.
  8068. const bool shutdown_gracefully = ret;
  8069. detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
  8070. }
  8071. detail::shutdown_socket(sock);
  8072. detail::close_socket(sock);
  8073. return ret;
  8074. }
  8075. // SSL HTTP client implementation
  8076. inline SSLClient::SSLClient(const std::string &host)
  8077. : SSLClient(host, 443, std::string(), std::string()) {}
  8078. inline SSLClient::SSLClient(const std::string &host, int port)
  8079. : SSLClient(host, port, std::string(), std::string()) {}
  8080. inline SSLClient::SSLClient(const std::string &host, int port,
  8081. const std::string &client_cert_path,
  8082. const std::string &client_key_path,
  8083. const std::string &private_key_password)
  8084. : ClientImpl(host, port, client_cert_path, client_key_path) {
  8085. ctx_ = SSL_CTX_new(TLS_client_method());
  8086. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  8087. detail::split(&host_[0], &host_[host_.size()], '.',
  8088. [&](const char *b, const char *e) {
  8089. host_components_.emplace_back(b, e);
  8090. });
  8091. if (!client_cert_path.empty() && !client_key_path.empty()) {
  8092. if (!private_key_password.empty()) {
  8093. SSL_CTX_set_default_passwd_cb_userdata(
  8094. ctx_, reinterpret_cast<void *>(
  8095. const_cast<char *>(private_key_password.c_str())));
  8096. }
  8097. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  8098. SSL_FILETYPE_PEM) != 1 ||
  8099. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  8100. SSL_FILETYPE_PEM) != 1) {
  8101. SSL_CTX_free(ctx_);
  8102. ctx_ = nullptr;
  8103. }
  8104. }
  8105. }
  8106. inline SSLClient::SSLClient(const std::string &host, int port,
  8107. X509 *client_cert, EVP_PKEY *client_key,
  8108. const std::string &private_key_password)
  8109. : ClientImpl(host, port) {
  8110. ctx_ = SSL_CTX_new(TLS_client_method());
  8111. detail::split(&host_[0], &host_[host_.size()], '.',
  8112. [&](const char *b, const char *e) {
  8113. host_components_.emplace_back(b, e);
  8114. });
  8115. if (client_cert != nullptr && client_key != nullptr) {
  8116. if (!private_key_password.empty()) {
  8117. SSL_CTX_set_default_passwd_cb_userdata(
  8118. ctx_, reinterpret_cast<void *>(
  8119. const_cast<char *>(private_key_password.c_str())));
  8120. }
  8121. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  8122. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  8123. SSL_CTX_free(ctx_);
  8124. ctx_ = nullptr;
  8125. }
  8126. }
  8127. }
  8128. inline SSLClient::~SSLClient() {
  8129. if (ctx_) { SSL_CTX_free(ctx_); }
  8130. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  8131. // base function rather than the derived function once we get to the
  8132. // base class destructor, and won't free the SSL (causing a leak).
  8133. shutdown_ssl_impl(socket_, true);
  8134. }
  8135. inline bool SSLClient::is_valid() const { return ctx_; }
  8136. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  8137. if (ca_cert_store) {
  8138. if (ctx_) {
  8139. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  8140. // Free memory allocated for old cert and use new store `ca_cert_store`
  8141. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  8142. }
  8143. } else {
  8144. X509_STORE_free(ca_cert_store);
  8145. }
  8146. }
  8147. }
  8148. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  8149. std::size_t size) {
  8150. set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
  8151. }
  8152. inline long SSLClient::get_openssl_verify_result() const {
  8153. return verify_result_;
  8154. }
  8155. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  8156. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  8157. return is_valid() && ClientImpl::create_and_connect_socket(socket, error);
  8158. }
  8159. // Assumes that socket_mutex_ is locked and that there are no requests in flight
  8160. inline bool SSLClient::connect_with_proxy(
  8161. Socket &socket,
  8162. std::chrono::time_point<std::chrono::steady_clock> start_time,
  8163. Response &res, bool &success, Error &error) {
  8164. success = true;
  8165. Response proxy_res;
  8166. if (!detail::process_client_socket(
  8167. socket.sock, read_timeout_sec_, read_timeout_usec_,
  8168. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  8169. start_time, [&](Stream &strm) {
  8170. Request req2;
  8171. req2.method = "CONNECT";
  8172. req2.path = host_and_port_;
  8173. if (max_timeout_msec_ > 0) {
  8174. req2.start_time_ = std::chrono::steady_clock::now();
  8175. }
  8176. return process_request(strm, req2, proxy_res, false, error);
  8177. })) {
  8178. // Thread-safe to close everything because we are assuming there are no
  8179. // requests in flight
  8180. shutdown_ssl(socket, true);
  8181. shutdown_socket(socket);
  8182. close_socket(socket);
  8183. success = false;
  8184. return false;
  8185. }
  8186. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  8187. if (!proxy_digest_auth_username_.empty() &&
  8188. !proxy_digest_auth_password_.empty()) {
  8189. std::map<std::string, std::string> auth;
  8190. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  8191. // Close the current socket and create a new one for the authenticated
  8192. // request
  8193. shutdown_ssl(socket, true);
  8194. shutdown_socket(socket);
  8195. close_socket(socket);
  8196. // Create a new socket for the authenticated CONNECT request
  8197. if (!create_and_connect_socket(socket, error)) {
  8198. success = false;
  8199. return false;
  8200. }
  8201. proxy_res = Response();
  8202. if (!detail::process_client_socket(
  8203. socket.sock, read_timeout_sec_, read_timeout_usec_,
  8204. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  8205. start_time, [&](Stream &strm) {
  8206. Request req3;
  8207. req3.method = "CONNECT";
  8208. req3.path = host_and_port_;
  8209. req3.headers.insert(detail::make_digest_authentication_header(
  8210. req3, auth, 1, detail::random_string(10),
  8211. proxy_digest_auth_username_, proxy_digest_auth_password_,
  8212. true));
  8213. if (max_timeout_msec_ > 0) {
  8214. req3.start_time_ = std::chrono::steady_clock::now();
  8215. }
  8216. return process_request(strm, req3, proxy_res, false, error);
  8217. })) {
  8218. // Thread-safe to close everything because we are assuming there are
  8219. // no requests in flight
  8220. shutdown_ssl(socket, true);
  8221. shutdown_socket(socket);
  8222. close_socket(socket);
  8223. success = false;
  8224. return false;
  8225. }
  8226. }
  8227. }
  8228. }
  8229. // If status code is not 200, proxy request is failed.
  8230. // Set error to ProxyConnection and return proxy response
  8231. // as the response of the request
  8232. if (proxy_res.status != StatusCode::OK_200) {
  8233. error = Error::ProxyConnection;
  8234. res = std::move(proxy_res);
  8235. // Thread-safe to close everything because we are assuming there are
  8236. // no requests in flight
  8237. shutdown_ssl(socket, true);
  8238. shutdown_socket(socket);
  8239. close_socket(socket);
  8240. return false;
  8241. }
  8242. return true;
  8243. }
  8244. inline bool SSLClient::load_certs() {
  8245. auto ret = true;
  8246. std::call_once(initialize_cert_, [&]() {
  8247. std::lock_guard<std::mutex> guard(ctx_mutex_);
  8248. if (!ca_cert_file_path_.empty()) {
  8249. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  8250. nullptr)) {
  8251. ret = false;
  8252. }
  8253. } else if (!ca_cert_dir_path_.empty()) {
  8254. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  8255. ca_cert_dir_path_.c_str())) {
  8256. ret = false;
  8257. }
  8258. } else {
  8259. auto loaded = false;
  8260. #ifdef _WIN32
  8261. loaded =
  8262. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  8263. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
  8264. #if TARGET_OS_OSX
  8265. loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
  8266. #endif // TARGET_OS_OSX
  8267. #endif // _WIN32
  8268. if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }
  8269. }
  8270. });
  8271. return ret;
  8272. }
  8273. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  8274. auto ssl = detail::ssl_new(
  8275. socket.sock, ctx_, ctx_mutex_,
  8276. [&](SSL *ssl2) {
  8277. if (server_certificate_verification_) {
  8278. if (!load_certs()) {
  8279. error = Error::SSLLoadingCerts;
  8280. return false;
  8281. }
  8282. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  8283. }
  8284. if (!detail::ssl_connect_or_accept_nonblocking(
  8285. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  8286. connection_timeout_usec_)) {
  8287. error = Error::SSLConnection;
  8288. return false;
  8289. }
  8290. if (server_certificate_verification_) {
  8291. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  8292. if (server_certificate_verifier_) {
  8293. verification_status = server_certificate_verifier_(ssl2);
  8294. }
  8295. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  8296. error = Error::SSLServerVerification;
  8297. return false;
  8298. }
  8299. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  8300. verify_result_ = SSL_get_verify_result(ssl2);
  8301. if (verify_result_ != X509_V_OK) {
  8302. error = Error::SSLServerVerification;
  8303. return false;
  8304. }
  8305. auto server_cert = SSL_get1_peer_certificate(ssl2);
  8306. auto se = detail::scope_exit([&] { X509_free(server_cert); });
  8307. if (server_cert == nullptr) {
  8308. error = Error::SSLServerVerification;
  8309. return false;
  8310. }
  8311. if (server_hostname_verification_) {
  8312. if (!verify_host(server_cert)) {
  8313. error = Error::SSLServerHostnameVerification;
  8314. return false;
  8315. }
  8316. }
  8317. }
  8318. }
  8319. return true;
  8320. },
  8321. [&](SSL *ssl2) {
  8322. #if defined(OPENSSL_IS_BORINGSSL)
  8323. SSL_set_tlsext_host_name(ssl2, host_.c_str());
  8324. #else
  8325. // NOTE: Direct call instead of using the OpenSSL macro to suppress
  8326. // -Wold-style-cast warning
  8327. SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  8328. static_cast<void *>(const_cast<char *>(host_.c_str())));
  8329. #endif
  8330. return true;
  8331. });
  8332. if (ssl) {
  8333. socket.ssl = ssl;
  8334. return true;
  8335. }
  8336. shutdown_socket(socket);
  8337. close_socket(socket);
  8338. return false;
  8339. }
  8340. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  8341. shutdown_ssl_impl(socket, shutdown_gracefully);
  8342. }
  8343. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  8344. bool shutdown_gracefully) {
  8345. if (socket.sock == INVALID_SOCKET) {
  8346. assert(socket.ssl == nullptr);
  8347. return;
  8348. }
  8349. if (socket.ssl) {
  8350. detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock,
  8351. shutdown_gracefully);
  8352. socket.ssl = nullptr;
  8353. }
  8354. assert(socket.ssl == nullptr);
  8355. }
  8356. inline bool SSLClient::process_socket(
  8357. const Socket &socket,
  8358. std::chrono::time_point<std::chrono::steady_clock> start_time,
  8359. std::function<bool(Stream &strm)> callback) {
  8360. assert(socket.ssl);
  8361. return detail::process_client_socket_ssl(
  8362. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  8363. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  8364. std::move(callback));
  8365. }
  8366. inline bool SSLClient::is_ssl() const { return true; }
  8367. inline bool SSLClient::verify_host(X509 *server_cert) const {
  8368. /* Quote from RFC2818 section 3.1 "Server Identity"
  8369. If a subjectAltName extension of type dNSName is present, that MUST
  8370. be used as the identity. Otherwise, the (most specific) Common Name
  8371. field in the Subject field of the certificate MUST be used. Although
  8372. the use of the Common Name is existing practice, it is deprecated and
  8373. Certification Authorities are encouraged to use the dNSName instead.
  8374. Matching is performed using the matching rules specified by
  8375. [RFC2459]. If more than one identity of a given type is present in
  8376. the certificate (e.g., more than one dNSName name, a match in any one
  8377. of the set is considered acceptable.) Names may contain the wildcard
  8378. character * which is considered to match any single domain name
  8379. component or component fragment. E.g., *.a.com matches foo.a.com but
  8380. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  8381. In some cases, the URI is specified as an IP address rather than a
  8382. hostname. In this case, the iPAddress subjectAltName must be present
  8383. in the certificate and must exactly match the IP in the URI.
  8384. */
  8385. return verify_host_with_subject_alt_name(server_cert) ||
  8386. verify_host_with_common_name(server_cert);
  8387. }
  8388. inline bool
  8389. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  8390. auto ret = false;
  8391. auto type = GEN_DNS;
  8392. struct in6_addr addr6 = {};
  8393. struct in_addr addr = {};
  8394. size_t addr_len = 0;
  8395. #ifndef __MINGW32__
  8396. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  8397. type = GEN_IPADD;
  8398. addr_len = sizeof(struct in6_addr);
  8399. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  8400. type = GEN_IPADD;
  8401. addr_len = sizeof(struct in_addr);
  8402. }
  8403. #endif
  8404. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  8405. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  8406. if (alt_names) {
  8407. auto dsn_matched = false;
  8408. auto ip_matched = false;
  8409. auto count = sk_GENERAL_NAME_num(alt_names);
  8410. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  8411. auto val = sk_GENERAL_NAME_value(alt_names, i);
  8412. if (val->type == type) {
  8413. auto name =
  8414. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  8415. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  8416. switch (type) {
  8417. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  8418. case GEN_IPADD:
  8419. if (!memcmp(&addr6, name, addr_len) ||
  8420. !memcmp(&addr, name, addr_len)) {
  8421. ip_matched = true;
  8422. }
  8423. break;
  8424. }
  8425. }
  8426. }
  8427. if (dsn_matched || ip_matched) { ret = true; }
  8428. }
  8429. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  8430. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  8431. return ret;
  8432. }
  8433. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  8434. const auto subject_name = X509_get_subject_name(server_cert);
  8435. if (subject_name != nullptr) {
  8436. char name[BUFSIZ];
  8437. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  8438. name, sizeof(name));
  8439. if (name_len != -1) {
  8440. return check_host_name(name, static_cast<size_t>(name_len));
  8441. }
  8442. }
  8443. return false;
  8444. }
  8445. inline bool SSLClient::check_host_name(const char *pattern,
  8446. size_t pattern_len) const {
  8447. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  8448. // Wildcard match
  8449. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  8450. std::vector<std::string> pattern_components;
  8451. detail::split(&pattern[0], &pattern[pattern_len], '.',
  8452. [&](const char *b, const char *e) {
  8453. pattern_components.emplace_back(b, e);
  8454. });
  8455. if (host_components_.size() != pattern_components.size()) { return false; }
  8456. auto itr = pattern_components.begin();
  8457. for (const auto &h : host_components_) {
  8458. auto &p = *itr;
  8459. if (p != h && p != "*") {
  8460. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  8461. !p.compare(0, p.size() - 1, h));
  8462. if (!partial_match) { return false; }
  8463. }
  8464. ++itr;
  8465. }
  8466. return true;
  8467. }
  8468. #endif
  8469. // Universal client implementation
  8470. inline Client::Client(const std::string &scheme_host_port)
  8471. : Client(scheme_host_port, std::string(), std::string()) {}
  8472. inline Client::Client(const std::string &scheme_host_port,
  8473. const std::string &client_cert_path,
  8474. const std::string &client_key_path) {
  8475. const static std::regex re(
  8476. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  8477. std::smatch m;
  8478. if (std::regex_match(scheme_host_port, m, re)) {
  8479. auto scheme = m[1].str();
  8480. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8481. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  8482. #else
  8483. if (!scheme.empty() && scheme != "http") {
  8484. #endif
  8485. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8486. std::string msg = "'" + scheme + "' scheme is not supported.";
  8487. throw std::invalid_argument(msg);
  8488. #endif
  8489. return;
  8490. }
  8491. auto is_ssl = scheme == "https";
  8492. auto host = m[2].str();
  8493. if (host.empty()) { host = m[3].str(); }
  8494. auto port_str = m[4].str();
  8495. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  8496. if (is_ssl) {
  8497. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8498. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  8499. client_key_path);
  8500. is_ssl_ = is_ssl;
  8501. #endif
  8502. } else {
  8503. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  8504. client_key_path);
  8505. }
  8506. } else {
  8507. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  8508. // if port param below changes.
  8509. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  8510. client_cert_path, client_key_path);
  8511. }
  8512. } // namespace detail
  8513. inline Client::Client(const std::string &host, int port)
  8514. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  8515. inline Client::Client(const std::string &host, int port,
  8516. const std::string &client_cert_path,
  8517. const std::string &client_key_path)
  8518. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  8519. client_key_path)) {}
  8520. inline Client::~Client() = default;
  8521. inline bool Client::is_valid() const {
  8522. return cli_ != nullptr && cli_->is_valid();
  8523. }
  8524. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  8525. return cli_->Get(path, std::move(progress));
  8526. }
  8527. inline Result Client::Get(const std::string &path, const Headers &headers,
  8528. DownloadProgress progress) {
  8529. return cli_->Get(path, headers, std::move(progress));
  8530. }
  8531. inline Result Client::Get(const std::string &path,
  8532. ContentReceiver content_receiver,
  8533. DownloadProgress progress) {
  8534. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  8535. }
  8536. inline Result Client::Get(const std::string &path, const Headers &headers,
  8537. ContentReceiver content_receiver,
  8538. DownloadProgress progress) {
  8539. return cli_->Get(path, headers, std::move(content_receiver),
  8540. std::move(progress));
  8541. }
  8542. inline Result Client::Get(const std::string &path,
  8543. ResponseHandler response_handler,
  8544. ContentReceiver content_receiver,
  8545. DownloadProgress progress) {
  8546. return cli_->Get(path, std::move(response_handler),
  8547. std::move(content_receiver), std::move(progress));
  8548. }
  8549. inline Result Client::Get(const std::string &path, const Headers &headers,
  8550. ResponseHandler response_handler,
  8551. ContentReceiver content_receiver,
  8552. DownloadProgress progress) {
  8553. return cli_->Get(path, headers, std::move(response_handler),
  8554. std::move(content_receiver), std::move(progress));
  8555. }
  8556. inline Result Client::Get(const std::string &path, const Params &params,
  8557. const Headers &headers, DownloadProgress progress) {
  8558. return cli_->Get(path, params, headers, std::move(progress));
  8559. }
  8560. inline Result Client::Get(const std::string &path, const Params &params,
  8561. const Headers &headers,
  8562. ContentReceiver content_receiver,
  8563. DownloadProgress progress) {
  8564. return cli_->Get(path, params, headers, std::move(content_receiver),
  8565. std::move(progress));
  8566. }
  8567. inline Result Client::Get(const std::string &path, const Params &params,
  8568. const Headers &headers,
  8569. ResponseHandler response_handler,
  8570. ContentReceiver content_receiver,
  8571. DownloadProgress progress) {
  8572. return cli_->Get(path, params, headers, std::move(response_handler),
  8573. std::move(content_receiver), std::move(progress));
  8574. }
  8575. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  8576. inline Result Client::Head(const std::string &path, const Headers &headers) {
  8577. return cli_->Head(path, headers);
  8578. }
  8579. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  8580. inline Result Client::Post(const std::string &path, const Headers &headers,
  8581. UploadProgress progress) {
  8582. return cli_->Post(path, headers, progress);
  8583. }
  8584. inline Result Client::Post(const std::string &path, const char *body,
  8585. size_t content_length,
  8586. const std::string &content_type,
  8587. UploadProgress progress) {
  8588. return cli_->Post(path, body, content_length, content_type, progress);
  8589. }
  8590. inline Result Client::Post(const std::string &path, const Headers &headers,
  8591. const char *body, size_t content_length,
  8592. const std::string &content_type,
  8593. UploadProgress progress) {
  8594. return cli_->Post(path, headers, body, content_length, content_type,
  8595. progress);
  8596. }
  8597. inline Result Client::Post(const std::string &path, const std::string &body,
  8598. const std::string &content_type,
  8599. UploadProgress progress) {
  8600. return cli_->Post(path, body, content_type, progress);
  8601. }
  8602. inline Result Client::Post(const std::string &path, const Headers &headers,
  8603. const std::string &body,
  8604. const std::string &content_type,
  8605. UploadProgress progress) {
  8606. return cli_->Post(path, headers, body, content_type, progress);
  8607. }
  8608. inline Result Client::Post(const std::string &path, size_t content_length,
  8609. ContentProvider content_provider,
  8610. const std::string &content_type,
  8611. UploadProgress progress) {
  8612. return cli_->Post(path, content_length, std::move(content_provider),
  8613. content_type, progress);
  8614. }
  8615. inline Result Client::Post(const std::string &path,
  8616. ContentProviderWithoutLength content_provider,
  8617. const std::string &content_type,
  8618. UploadProgress progress) {
  8619. return cli_->Post(path, std::move(content_provider), content_type, progress);
  8620. }
  8621. inline Result Client::Post(const std::string &path, const Headers &headers,
  8622. size_t content_length,
  8623. ContentProvider content_provider,
  8624. const std::string &content_type,
  8625. UploadProgress progress) {
  8626. return cli_->Post(path, headers, content_length, std::move(content_provider),
  8627. content_type, progress);
  8628. }
  8629. inline Result Client::Post(const std::string &path, const Headers &headers,
  8630. ContentProviderWithoutLength content_provider,
  8631. const std::string &content_type,
  8632. UploadProgress progress) {
  8633. return cli_->Post(path, headers, std::move(content_provider), content_type,
  8634. progress);
  8635. }
  8636. inline Result Client::Post(const std::string &path, const Params &params) {
  8637. return cli_->Post(path, params);
  8638. }
  8639. inline Result Client::Post(const std::string &path, const Headers &headers,
  8640. const Params &params) {
  8641. return cli_->Post(path, headers, params);
  8642. }
  8643. inline Result Client::Post(const std::string &path,
  8644. const MultipartFormDataItemsForClientInput &items,
  8645. UploadProgress progress) {
  8646. return cli_->Post(path, items, progress);
  8647. }
  8648. inline Result Client::Post(const std::string &path, const Headers &headers,
  8649. const MultipartFormDataItemsForClientInput &items,
  8650. UploadProgress progress) {
  8651. return cli_->Post(path, headers, items, progress);
  8652. }
  8653. inline Result Client::Post(const std::string &path, const Headers &headers,
  8654. const MultipartFormDataItemsForClientInput &items,
  8655. const std::string &boundary,
  8656. UploadProgress progress) {
  8657. return cli_->Post(path, headers, items, boundary, progress);
  8658. }
  8659. inline Result Client::Post(const std::string &path, const Headers &headers,
  8660. const MultipartFormDataItemsForClientInput &items,
  8661. const MultipartFormDataProviderItems &provider_items,
  8662. UploadProgress progress) {
  8663. return cli_->Post(path, headers, items, provider_items, progress);
  8664. }
  8665. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  8666. inline Result Client::Put(const std::string &path, const Headers &headers,
  8667. UploadProgress progress) {
  8668. return cli_->Put(path, headers, progress);
  8669. }
  8670. inline Result Client::Put(const std::string &path, const char *body,
  8671. size_t content_length,
  8672. const std::string &content_type,
  8673. UploadProgress progress) {
  8674. return cli_->Put(path, body, content_length, content_type, progress);
  8675. }
  8676. inline Result Client::Put(const std::string &path, const Headers &headers,
  8677. const char *body, size_t content_length,
  8678. const std::string &content_type,
  8679. UploadProgress progress) {
  8680. return cli_->Put(path, headers, body, content_length, content_type, progress);
  8681. }
  8682. inline Result Client::Put(const std::string &path, const std::string &body,
  8683. const std::string &content_type,
  8684. UploadProgress progress) {
  8685. return cli_->Put(path, body, content_type, progress);
  8686. }
  8687. inline Result Client::Put(const std::string &path, const Headers &headers,
  8688. const std::string &body,
  8689. const std::string &content_type,
  8690. UploadProgress progress) {
  8691. return cli_->Put(path, headers, body, content_type, progress);
  8692. }
  8693. inline Result Client::Put(const std::string &path, size_t content_length,
  8694. ContentProvider content_provider,
  8695. const std::string &content_type,
  8696. UploadProgress progress) {
  8697. return cli_->Put(path, content_length, std::move(content_provider),
  8698. content_type, progress);
  8699. }
  8700. inline Result Client::Put(const std::string &path,
  8701. ContentProviderWithoutLength content_provider,
  8702. const std::string &content_type,
  8703. UploadProgress progress) {
  8704. return cli_->Put(path, std::move(content_provider), content_type, progress);
  8705. }
  8706. inline Result Client::Put(const std::string &path, const Headers &headers,
  8707. size_t content_length,
  8708. ContentProvider content_provider,
  8709. const std::string &content_type,
  8710. UploadProgress progress) {
  8711. return cli_->Put(path, headers, content_length, std::move(content_provider),
  8712. content_type, progress);
  8713. }
  8714. inline Result Client::Put(const std::string &path, const Headers &headers,
  8715. ContentProviderWithoutLength content_provider,
  8716. const std::string &content_type,
  8717. UploadProgress progress) {
  8718. return cli_->Put(path, headers, std::move(content_provider), content_type,
  8719. progress);
  8720. }
  8721. inline Result Client::Put(const std::string &path, const Params &params) {
  8722. return cli_->Put(path, params);
  8723. }
  8724. inline Result Client::Put(const std::string &path, const Headers &headers,
  8725. const Params &params) {
  8726. return cli_->Put(path, headers, params);
  8727. }
  8728. inline Result Client::Put(const std::string &path,
  8729. const MultipartFormDataItemsForClientInput &items,
  8730. UploadProgress progress) {
  8731. return cli_->Put(path, items, progress);
  8732. }
  8733. inline Result Client::Put(const std::string &path, const Headers &headers,
  8734. const MultipartFormDataItemsForClientInput &items,
  8735. UploadProgress progress) {
  8736. return cli_->Put(path, headers, items, progress);
  8737. }
  8738. inline Result Client::Put(const std::string &path, const Headers &headers,
  8739. const MultipartFormDataItemsForClientInput &items,
  8740. const std::string &boundary,
  8741. UploadProgress progress) {
  8742. return cli_->Put(path, headers, items, boundary, progress);
  8743. }
  8744. inline Result Client::Put(const std::string &path, const Headers &headers,
  8745. const MultipartFormDataItemsForClientInput &items,
  8746. const MultipartFormDataProviderItems &provider_items,
  8747. UploadProgress progress) {
  8748. return cli_->Put(path, headers, items, provider_items, progress);
  8749. }
  8750. inline Result Client::Patch(const std::string &path) {
  8751. return cli_->Patch(path);
  8752. }
  8753. inline Result Client::Patch(const std::string &path, const Headers &headers,
  8754. UploadProgress progress) {
  8755. return cli_->Patch(path, headers, progress);
  8756. }
  8757. inline Result Client::Patch(const std::string &path, const char *body,
  8758. size_t content_length,
  8759. const std::string &content_type,
  8760. UploadProgress progress) {
  8761. return cli_->Patch(path, body, content_length, content_type, progress);
  8762. }
  8763. inline Result Client::Patch(const std::string &path, const Headers &headers,
  8764. const char *body, size_t content_length,
  8765. const std::string &content_type,
  8766. UploadProgress progress) {
  8767. return cli_->Patch(path, headers, body, content_length, content_type,
  8768. progress);
  8769. }
  8770. inline Result Client::Patch(const std::string &path, const std::string &body,
  8771. const std::string &content_type,
  8772. UploadProgress progress) {
  8773. return cli_->Patch(path, body, content_type, progress);
  8774. }
  8775. inline Result Client::Patch(const std::string &path, const Headers &headers,
  8776. const std::string &body,
  8777. const std::string &content_type,
  8778. UploadProgress progress) {
  8779. return cli_->Patch(path, headers, body, content_type, progress);
  8780. }
  8781. inline Result Client::Patch(const std::string &path, size_t content_length,
  8782. ContentProvider content_provider,
  8783. const std::string &content_type,
  8784. UploadProgress progress) {
  8785. return cli_->Patch(path, content_length, std::move(content_provider),
  8786. content_type, progress);
  8787. }
  8788. inline Result Client::Patch(const std::string &path,
  8789. ContentProviderWithoutLength content_provider,
  8790. const std::string &content_type,
  8791. UploadProgress progress) {
  8792. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  8793. }
  8794. inline Result Client::Patch(const std::string &path, const Headers &headers,
  8795. size_t content_length,
  8796. ContentProvider content_provider,
  8797. const std::string &content_type,
  8798. UploadProgress progress) {
  8799. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  8800. content_type, progress);
  8801. }
  8802. inline Result Client::Patch(const std::string &path, const Headers &headers,
  8803. ContentProviderWithoutLength content_provider,
  8804. const std::string &content_type,
  8805. UploadProgress progress) {
  8806. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  8807. progress);
  8808. }
  8809. inline Result Client::Patch(const std::string &path, const Params &params) {
  8810. return cli_->Patch(path, params);
  8811. }
  8812. inline Result Client::Patch(const std::string &path, const Headers &headers,
  8813. const Params &params) {
  8814. return cli_->Patch(path, headers, params);
  8815. }
  8816. inline Result Client::Patch(const std::string &path,
  8817. const MultipartFormDataItemsForClientInput &items,
  8818. UploadProgress progress) {
  8819. return cli_->Patch(path, items, progress);
  8820. }
  8821. inline Result Client::Patch(const std::string &path, const Headers &headers,
  8822. const MultipartFormDataItemsForClientInput &items,
  8823. UploadProgress progress) {
  8824. return cli_->Patch(path, headers, items, progress);
  8825. }
  8826. inline Result Client::Patch(const std::string &path, const Headers &headers,
  8827. const MultipartFormDataItemsForClientInput &items,
  8828. const std::string &boundary,
  8829. UploadProgress progress) {
  8830. return cli_->Patch(path, headers, items, boundary, progress);
  8831. }
  8832. inline Result
  8833. Client::Patch(const std::string &path, const Headers &headers,
  8834. const MultipartFormDataItemsForClientInput &items,
  8835. const MultipartFormDataProviderItems &provider_items,
  8836. UploadProgress progress) {
  8837. return cli_->Patch(path, headers, items, provider_items, progress);
  8838. }
  8839. inline Result Client::Delete(const std::string &path,
  8840. DownloadProgress progress) {
  8841. return cli_->Delete(path, progress);
  8842. }
  8843. inline Result Client::Delete(const std::string &path, const Headers &headers,
  8844. DownloadProgress progress) {
  8845. return cli_->Delete(path, headers, progress);
  8846. }
  8847. inline Result Client::Delete(const std::string &path, const char *body,
  8848. size_t content_length,
  8849. const std::string &content_type,
  8850. DownloadProgress progress) {
  8851. return cli_->Delete(path, body, content_length, content_type, progress);
  8852. }
  8853. inline Result Client::Delete(const std::string &path, const Headers &headers,
  8854. const char *body, size_t content_length,
  8855. const std::string &content_type,
  8856. DownloadProgress progress) {
  8857. return cli_->Delete(path, headers, body, content_length, content_type,
  8858. progress);
  8859. }
  8860. inline Result Client::Delete(const std::string &path, const std::string &body,
  8861. const std::string &content_type,
  8862. DownloadProgress progress) {
  8863. return cli_->Delete(path, body, content_type, progress);
  8864. }
  8865. inline Result Client::Delete(const std::string &path, const Headers &headers,
  8866. const std::string &body,
  8867. const std::string &content_type,
  8868. DownloadProgress progress) {
  8869. return cli_->Delete(path, headers, body, content_type, progress);
  8870. }
  8871. inline Result Client::Delete(const std::string &path, const Params &params,
  8872. DownloadProgress progress) {
  8873. return cli_->Delete(path, params, progress);
  8874. }
  8875. inline Result Client::Delete(const std::string &path, const Headers &headers,
  8876. const Params &params, DownloadProgress progress) {
  8877. return cli_->Delete(path, headers, params, progress);
  8878. }
  8879. inline Result Client::Options(const std::string &path) {
  8880. return cli_->Options(path);
  8881. }
  8882. inline Result Client::Options(const std::string &path, const Headers &headers) {
  8883. return cli_->Options(path, headers);
  8884. }
  8885. inline bool Client::send(Request &req, Response &res, Error &error) {
  8886. return cli_->send(req, res, error);
  8887. }
  8888. inline Result Client::send(const Request &req) { return cli_->send(req); }
  8889. inline void Client::stop() { cli_->stop(); }
  8890. inline std::string Client::host() const { return cli_->host(); }
  8891. inline int Client::port() const { return cli_->port(); }
  8892. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  8893. inline socket_t Client::socket() const { return cli_->socket(); }
  8894. inline void
  8895. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  8896. cli_->set_hostname_addr_map(std::move(addr_map));
  8897. }
  8898. inline void Client::set_default_headers(Headers headers) {
  8899. cli_->set_default_headers(std::move(headers));
  8900. }
  8901. inline void Client::set_header_writer(
  8902. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  8903. cli_->set_header_writer(writer);
  8904. }
  8905. inline void Client::set_address_family(int family) {
  8906. cli_->set_address_family(family);
  8907. }
  8908. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  8909. inline void Client::set_socket_options(SocketOptions socket_options) {
  8910. cli_->set_socket_options(std::move(socket_options));
  8911. }
  8912. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  8913. cli_->set_connection_timeout(sec, usec);
  8914. }
  8915. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  8916. cli_->set_read_timeout(sec, usec);
  8917. }
  8918. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  8919. cli_->set_write_timeout(sec, usec);
  8920. }
  8921. inline void Client::set_basic_auth(const std::string &username,
  8922. const std::string &password) {
  8923. cli_->set_basic_auth(username, password);
  8924. }
  8925. inline void Client::set_bearer_token_auth(const std::string &token) {
  8926. cli_->set_bearer_token_auth(token);
  8927. }
  8928. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8929. inline void Client::set_digest_auth(const std::string &username,
  8930. const std::string &password) {
  8931. cli_->set_digest_auth(username, password);
  8932. }
  8933. #endif
  8934. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  8935. inline void Client::set_follow_location(bool on) {
  8936. cli_->set_follow_location(on);
  8937. }
  8938. inline void Client::set_url_encode(bool on) { cli_->set_url_encode(on); }
  8939. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  8940. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  8941. inline void Client::set_interface(const std::string &intf) {
  8942. cli_->set_interface(intf);
  8943. }
  8944. inline void Client::set_proxy(const std::string &host, int port) {
  8945. cli_->set_proxy(host, port);
  8946. }
  8947. inline void Client::set_proxy_basic_auth(const std::string &username,
  8948. const std::string &password) {
  8949. cli_->set_proxy_basic_auth(username, password);
  8950. }
  8951. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  8952. cli_->set_proxy_bearer_token_auth(token);
  8953. }
  8954. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8955. inline void Client::set_proxy_digest_auth(const std::string &username,
  8956. const std::string &password) {
  8957. cli_->set_proxy_digest_auth(username, password);
  8958. }
  8959. #endif
  8960. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8961. inline void Client::enable_server_certificate_verification(bool enabled) {
  8962. cli_->enable_server_certificate_verification(enabled);
  8963. }
  8964. inline void Client::enable_server_hostname_verification(bool enabled) {
  8965. cli_->enable_server_hostname_verification(enabled);
  8966. }
  8967. inline void Client::set_server_certificate_verifier(
  8968. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  8969. cli_->set_server_certificate_verifier(verifier);
  8970. }
  8971. #endif
  8972. inline void Client::set_logger(Logger logger) {
  8973. cli_->set_logger(std::move(logger));
  8974. }
  8975. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8976. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  8977. const std::string &ca_cert_dir_path) {
  8978. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  8979. }
  8980. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  8981. if (is_ssl_) {
  8982. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  8983. } else {
  8984. cli_->set_ca_cert_store(ca_cert_store);
  8985. }
  8986. }
  8987. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  8988. set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
  8989. }
  8990. inline long Client::get_openssl_verify_result() const {
  8991. if (is_ssl_) {
  8992. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  8993. }
  8994. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  8995. }
  8996. inline SSL_CTX *Client::ssl_context() const {
  8997. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  8998. return nullptr;
  8999. }
  9000. #endif
  9001. // ----------------------------------------------------------------------------
  9002. } // namespace httplib
  9003. #endif // CPPHTTPLIB_HTTPLIB_H